code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import math import os import pytest import subprocess import time from watchtower.streamer.writer import dropbox_writer from watchtower.streamer.writer.disk_writer import DiskWriter def test_dropbox_writer_integration(writer, random_data, tmp_path): """ Integration test to feed a DropboxWriter chunks of data ...
watchtower/tests/streamer/writer/test_dropbox_writer.py
import math import os import pytest import subprocess import time from watchtower.streamer.writer import dropbox_writer from watchtower.streamer.writer.disk_writer import DiskWriter def test_dropbox_writer_integration(writer, random_data, tmp_path): """ Integration test to feed a DropboxWriter chunks of data ...
0.392803
0.405684
__all__ = ('SpoonAnalyser',) from typing import Any, Iterator, List, Mapping, Sequence import contextlib import json import os import shlex import subprocess from dockerblade import DockerDaemon as DockerBladeDockerDaemon from loguru import logger import attr from .analysis import SpoonFunction, SpoonStatement from ...
lib/kaskara/spoon/analyser.py
__all__ = ('SpoonAnalyser',) from typing import Any, Iterator, List, Mapping, Sequence import contextlib import json import os import shlex import subprocess from dockerblade import DockerDaemon as DockerBladeDockerDaemon from loguru import logger import attr from .analysis import SpoonFunction, SpoonStatement from ...
0.687945
0.09236
import os import sys import ctypes from decouple import config target_dir = config('CARGO_TARGET_DIR', os.path.join(os.path.dirname(__file__), '../../target')) build_profile = config('BUILD_PROFILE', 'debug') ext = 'dylib' if sys.platform == 'darwin' else 'so' dll = ctypes.cdll.LoadLibrary(os.path.join(target_dir, '%...
integration-tests/bot/chainbinding.py
import os import sys import ctypes from decouple import config target_dir = config('CARGO_TARGET_DIR', os.path.join(os.path.dirname(__file__), '../../target')) build_profile = config('BUILD_PROFILE', 'debug') ext = 'dylib' if sys.platform == 'darwin' else 'so' dll = ctypes.cdll.LoadLibrary(os.path.join(target_dir, '%...
0.188548
0.064418
import pytest import datetime from dateutil.tz import tzoffset from decimal import Decimal from pyticketswitch.mixins import JSONMixin, PaginationMixin, SeatPricingMixin class TestJSONMixin: ZULU = tzoffset('ZULU', 0) class Foo(JSONMixin, object): def __init__(self, bar): self.bar = bar...
tests/test_mixins.py
import pytest import datetime from dateutil.tz import tzoffset from decimal import Decimal from pyticketswitch.mixins import JSONMixin, PaginationMixin, SeatPricingMixin class TestJSONMixin: ZULU = tzoffset('ZULU', 0) class Foo(JSONMixin, object): def __init__(self, bar): self.bar = bar...
0.719186
0.458834
from hdmm.workload import * from hdmm import templates def __race1(): # single race only, two or more races aggregated # binary encoding: 1 indicates particular race is checked race1 = np.zeros((7, 64)) for i in range(6): race1[i, 2**i] = 1.0 race1[6,:] = 1.0 - race1[0:6].sum(axis=0) re...
hdmm/examples/census.py
from hdmm.workload import * from hdmm import templates def __race1(): # single race only, two or more races aggregated # binary encoding: 1 indicates particular race is checked race1 = np.zeros((7, 64)) for i in range(6): race1[i, 2**i] = 1.0 race1[6,:] = 1.0 - race1[0:6].sum(axis=0) re...
0.428233
0.513181
from pathlib import Path import sys import cv2 import depthai as dai import numpy as np import time ''' Mobilenet SSD device side decoding demo The "mobilenet-ssd" model is a Single-Shot multibox Detection (SSD) network intended to perform object detection. This model is implemented using the Caffe* framework. ...
code/02_tripple_mobilenet.py
from pathlib import Path import sys import cv2 import depthai as dai import numpy as np import time ''' Mobilenet SSD device side decoding demo The "mobilenet-ssd" model is a Single-Shot multibox Detection (SSD) network intended to perform object detection. This model is implemented using the Caffe* framework. ...
0.633864
0.333965
import sys import unittest import pybullet from qibullet import SimulationManager from qibullet import NaoVirtual, PepperVirtual, RomeoVirtual from qibullet import Camera, CameraRgb, CameraDepth, CameraResolution class CameraTest(unittest.TestCase): """ Unittests for virtual cameras (virtual class, don't use ...
tests/camera_test.py
import sys import unittest import pybullet from qibullet import SimulationManager from qibullet import NaoVirtual, PepperVirtual, RomeoVirtual from qibullet import Camera, CameraRgb, CameraDepth, CameraResolution class CameraTest(unittest.TestCase): """ Unittests for virtual cameras (virtual class, don't use ...
0.705176
0.862728
import functools import itertools import operator import unittest import dual @functools.lru_cache(maxsize=None) def stirling(n, k): # [[https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind]] if n == 0 and k == 0: return 1 elif n == 0 or k == 0: return 0 else: return stirling(n-1, k-1...
test.py
import functools import itertools import operator import unittest import dual @functools.lru_cache(maxsize=None) def stirling(n, k): # [[https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind]] if n == 0 and k == 0: return 1 elif n == 0 or k == 0: return 0 else: return stirling(n-1, k-1...
0.541651
0.510069
import os import boto3 from botocore.exceptions import NoCredentialsError from flask import Flask, redirect, Blueprint, request, url_for, render_template, flash from flask_login import current_user, login_required, login_user, logout_user from werkzeug.utils import secure_filename from datetime import datetime, date,...
views/admin.py
import os import boto3 from botocore.exceptions import NoCredentialsError from flask import Flask, redirect, Blueprint, request, url_for, render_template, flash from flask_login import current_user, login_required, login_user, logout_user from werkzeug.utils import secure_filename from datetime import datetime, date,...
0.308086
0.043244
import os import xlsxwriter import time import pickle import random import numpy as np import matplotlib.pyplot as plt from classes.quiz import Quiz from classes.save import Save from classes.result import Overall_Results, Result from classes.answer import Picture_Answer, Text_Answer, Answer from classes.school import...
main.py
import os import xlsxwriter import time import pickle import random import numpy as np import matplotlib.pyplot as plt from classes.quiz import Quiz from classes.save import Save from classes.result import Overall_Results, Result from classes.answer import Picture_Answer, Text_Answer, Answer from classes.school import...
0.380529
0.277479
import argparse import glob import json import os import shlex import shutil import subprocess import sys import tarfile import tempfile def create_env(name, pkgs, channel=None, yes=False): cmd = 'conda create --name {name}'.format(name=name) if channel: cmd = '{cmd} --channel {channel}'.format(cmd=cm...
openmdao.devtools/src/openmdao/devtools/conda_build.py
import argparse import glob import json import os import shlex import shutil import subprocess import sys import tarfile import tempfile def create_env(name, pkgs, channel=None, yes=False): cmd = 'conda create --name {name}'.format(name=name) if channel: cmd = '{cmd} --channel {channel}'.format(cmd=cm...
0.203233
0.083143
from __future__ import absolute_import, unicode_literals from collections import defaultdict from datetime import timedelta from django.conf import settings from celery import states from celery.events.state import Task from celery.events.snapshot import Polaroid from celery.five import monotonic from celery.utils.l...
djcelery/snapshot.py
from __future__ import absolute_import, unicode_literals from collections import defaultdict from datetime import timedelta from django.conf import settings from celery import states from celery.events.state import Task from celery.events.snapshot import Polaroid from celery.five import monotonic from celery.utils.l...
0.623377
0.110759
from unittest import TestCase from unittest.mock import MagicMock from pyramid.config import Configurator from pyramid_restful.routers import ViewSetRouter, Route from pyramid_restful.viewsets import ModelCRUDViewSet, APIViewSet from pyramid_restful.exceptions import ImproperlyConfigured class MyCRUDViewSet(ModelCR...
tests/test_routers.py
from unittest import TestCase from unittest.mock import MagicMock from pyramid.config import Configurator from pyramid_restful.routers import ViewSetRouter, Route from pyramid_restful.viewsets import ModelCRUDViewSet, APIViewSet from pyramid_restful.exceptions import ImproperlyConfigured class MyCRUDViewSet(ModelCR...
0.667906
0.316316
import sys import os from ngsutils.gtf import GTF def usage(msg=None): if msg: print '%s\n' % msg print __doc__ print '''\ Usage: gtfutils tobed [type] filename.gtf{.gz} Where type is one of: -genes The gene from start to end (including introns) -exons Each annotated exon -intro...
ngsutils/gtf/tobed.py
import sys import os from ngsutils.gtf import GTF def usage(msg=None): if msg: print '%s\n' % msg print __doc__ print '''\ Usage: gtfutils tobed [type] filename.gtf{.gz} Where type is one of: -genes The gene from start to end (including introns) -exons Each annotated exon -intro...
0.203985
0.370112
import inspect import torch import warnings from pd_mesh_net.models import (DualPrimalMeshClassifier, DualPrimalMeshSegmenter, DualPrimalUNetMeshSegmenter) def create_model(model_name, should_initialize_weights, **model_params): r"""Creates an insta...
pd_mesh_net/utils/models.py
import inspect import torch import warnings from pd_mesh_net.models import (DualPrimalMeshClassifier, DualPrimalMeshSegmenter, DualPrimalUNetMeshSegmenter) def create_model(model_name, should_initialize_weights, **model_params): r"""Creates an insta...
0.917474
0.467271
import os import json import math import time import torch from torch.utils.data import (DataLoader, SequentialSampler) import numpy as np from tqdm import tqdm import pickle from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components from special_partition.special_partition import cluste...
blink/biencoder/eval_cluster_linking.py
import os import json import math import time import torch from torch.utils.data import (DataLoader, SequentialSampler) import numpy as np from tqdm import tqdm import pickle from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components from special_partition.special_partition import cluste...
0.755817
0.368576
import threading import gzip import time from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS from twisted.internet import reactor, ssl from twisted.internet.protocol import ReconnectingClientFactory from twisted.internet.error import ReactorAlreadyRunning import ujson as...
bitrue/websockets.py
import threading import gzip import time from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS from twisted.internet import reactor, ssl from twisted.internet.protocol import ReconnectingClientFactory from twisted.internet.error import ReactorAlreadyRunning import ujson as...
0.508544
0.053576
import pandas as pd, numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn import svm,metrics from sklearn.calibration import CalibratedClassifierCV from sklearn.model_selection import StratifiedKFold column = "review" train = pd.read_csv('./data/train.csv',lineterm...
clafiyy/new/baseline.py
import pandas as pd, numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn import svm,metrics from sklearn.calibration import CalibratedClassifierCV from sklearn.model_selection import StratifiedKFold column = "review" train = pd.read_csv('./data/train.csv',lineterm...
0.187914
0.213029
import db_handler import models from Tkinter import Tk def copy_to_clipboard(text): r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(text) r.destroy() def print_member_details(member_id, email=None, use_prev_title=False): ''' Print the member details for the supplied ID Subst...
common_modules/db_explorer.py
import db_handler import models from Tkinter import Tk def copy_to_clipboard(text): r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append(text) r.destroy() def print_member_details(member_id, email=None, use_prev_title=False): ''' Print the member details for the supplied ID Subst...
0.185172
0.118793
from unittest import TestCase import jwt from piccolo.apps.user.tables import BaseUser from starlette.exceptions import HTTPException from starlette.routing import Route, Router from starlette.testclient import TestClient from piccolo_api.jwt_auth.middleware import JWTMiddleware from piccolo_api.token_auth.tables imp...
tests/jwt_auth/test_jwt_middleware.py
from unittest import TestCase import jwt from piccolo.apps.user.tables import BaseUser from starlette.exceptions import HTTPException from starlette.routing import Route, Router from starlette.testclient import TestClient from piccolo_api.jwt_auth.middleware import JWTMiddleware from piccolo_api.token_auth.tables imp...
0.552057
0.338159
from typing import Text import numpy as np from numpy import ndarray from oqupy.config import NpDtype SIGMA = {"id":[[1, 0], [0, 1]], "x":[[0, 1], [1, 0]], "y":[[0, -1j], [1j, 0]], "z":[[1, 0], [0, -1]], "+":[[0, 1], [0, 0]], "-":[[0, 0], [1, 0]]} SPIN_DM = {"up":[[1, 0...
oqupy/operators.py
from typing import Text import numpy as np from numpy import ndarray from oqupy.config import NpDtype SIGMA = {"id":[[1, 0], [0, 1]], "x":[[0, 1], [1, 0]], "y":[[0, -1j], [1j, 0]], "z":[[1, 0], [0, -1]], "+":[[0, 1], [0, 0]], "-":[[0, 0], [1, 0]]} SPIN_DM = {"up":[[1, 0...
0.899315
0.624408
import os import pandas as pd from src.config.labels import ALGORITHM_LABEL, CALIBRATION_LABEL, FAIRNESS_METRIC_LABEL, LAMBDA_LABEL, \ LAMBDA_VALUE_LABEL, EVALUATION_METRIC_LABEL, EVALUATION_VALUE_LABEL, EVALUATION_LIST_LABELS from src.config.path_dir_files import data_results_path, ALL_FOLDS_FILE, ALL_RECOMMENDE...
src/processing/merge_results.py
import os import pandas as pd from src.config.labels import ALGORITHM_LABEL, CALIBRATION_LABEL, FAIRNESS_METRIC_LABEL, LAMBDA_LABEL, \ LAMBDA_VALUE_LABEL, EVALUATION_METRIC_LABEL, EVALUATION_VALUE_LABEL, EVALUATION_LIST_LABELS from src.config.path_dir_files import data_results_path, ALL_FOLDS_FILE, ALL_RECOMMENDE...
0.249264
0.164148
import numpy as np import matplotlib.pyplot as plt from python_codes.transformations import * class MK2Robot(object): HOME_0 = 0 HOME_1 = np.pi def __init__(self, link_lengths): self.a = link_lengths self.q = [] self.T = [] self.pose = [] self.s = [] # self...
python_codes/mk2Robot.py
import numpy as np import matplotlib.pyplot as plt from python_codes.transformations import * class MK2Robot(object): HOME_0 = 0 HOME_1 = np.pi def __init__(self, link_lengths): self.a = link_lengths self.q = [] self.T = [] self.pose = [] self.s = [] # self...
0.569972
0.551211
import PlayCards import CommonCardsType # 该模块中list_list和Cardlist的内容一样 # 这个函数用于计算手牌中各种牌面的张数,接收一个手牌列表作为参数,返回一个记录各种牌面张数列表 def GetList_count(Cardlist=[]): list_count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for item in Cardlist: number = item[0] list_count[number] = list_count[number] + 1 ...
AutoPlayForShisanshui/SpecialCardsType.py
import PlayCards import CommonCardsType # 该模块中list_list和Cardlist的内容一样 # 这个函数用于计算手牌中各种牌面的张数,接收一个手牌列表作为参数,返回一个记录各种牌面张数列表 def GetList_count(Cardlist=[]): list_count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for item in Cardlist: number = item[0] list_count[number] = list_count[number] + 1 ...
0.090809
0.201224
import requests import json from pprint import pprint from glob import glob from semantic_version import Version import getpass import sys def main(): version = "" with open('files/version.txt') as f: version = f.read().strip() base_url = 'https://api.github.com/repos/jyapayne/Electrify/release...
upload_release.py
import requests import json from pprint import pprint from glob import glob from semantic_version import Version import getpass import sys def main(): version = "" with open('files/version.txt') as f: version = f.read().strip() base_url = 'https://api.github.com/repos/jyapayne/Electrify/release...
0.127476
0.060613
import numpy as np f1_alpha=1000 #set alpha of f1 f3_epsilon=1e-6 #set epsilon of f3 f45_q=10**8 def f1(x): #ellipsoid function dim=x.shape[0] #dimension number result=0 for i in range(dim): result+=f1_alpha**(i/(dim-1))*x[i]**2 return result def g1(x): dim=x.shape[0] result=np.zero...
functions.py
import numpy as np f1_alpha=1000 #set alpha of f1 f3_epsilon=1e-6 #set epsilon of f3 f45_q=10**8 def f1(x): #ellipsoid function dim=x.shape[0] #dimension number result=0 for i in range(dim): result+=f1_alpha**(i/(dim-1))*x[i]**2 return result def g1(x): dim=x.shape[0] result=np.zero...
0.214527
0.399724
from typing import Tuple, Union import pandas as pd from rdkit import Chem from rdkit.Chem.Descriptors import ExactMolWt from rdkit import rdBase from rdkit.Chem.rdchem import Mol functionality_smarts = { "ols": "[C,c;!$(C=O)][OH]", "aliphatic_ols": "[C;!$(C=O);!$([a])][OH]", "acids": "[#6][#6](=[#8:4])(...
m2p/monomers.py
from typing import Tuple, Union import pandas as pd from rdkit import Chem from rdkit.Chem.Descriptors import ExactMolWt from rdkit import rdBase from rdkit.Chem.rdchem import Mol functionality_smarts = { "ols": "[C,c;!$(C=O)][OH]", "aliphatic_ols": "[C;!$(C=O);!$([a])][OH]", "acids": "[#6][#6](=[#8:4])(...
0.799442
0.358943
import sys import codecs import re pat = "\[.*?(\d)\]" reg = re.compile(pat) JSON = {} def removeStems(s): s = s.replace(u'。', '') # Dirty idx = s.find("(") if idx!= -1: s = s[:idx] return s.strip() def getStem(s): stem_r = re.search(ur'\(.+\)', s) if stem_r: ...
txt/moedict.py
import sys import codecs import re pat = "\[.*?(\d)\]" reg = re.compile(pat) JSON = {} def removeStems(s): s = s.replace(u'。', '') # Dirty idx = s.find("(") if idx!= -1: s = s[:idx] return s.strip() def getStem(s): stem_r = re.search(ur'\(.+\)', s) if stem_r: ...
0.078722
0.180702
import math import os import random from string import ascii_lowercase import psutil import torch import torchvision import torchvision.transforms.functional as F from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms from src.data.transforms import Crop, StatefulRan...
src/data/lrs2.py
import math import os import random from string import ascii_lowercase import psutil import torch import torchvision import torchvision.transforms.functional as F from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms from src.data.transforms import Crop, StatefulRan...
0.696991
0.300157
import xdl import unittest import numpy as np import sys from xdl.python.lib.datatype import * from xdl.python.lib.graph import execute try: from xdl.python.backend.mxnet.mxnet_backend import * except ImportError: sys.exit(0) def main(): dense = xdl.mock_dense_op(shape=[1, 16], value=0.01, name_="dense") gear...
xdl/test/python/unit_test/backend/mxnet_backend_test.py
import xdl import unittest import numpy as np import sys from xdl.python.lib.datatype import * from xdl.python.lib.graph import execute try: from xdl.python.backend.mxnet.mxnet_backend import * except ImportError: sys.exit(0) def main(): dense = xdl.mock_dense_op(shape=[1, 16], value=0.01, name_="dense") gear...
0.392453
0.407776
import numpy as np from utils.unit_conversions import db_to_lin, lin_to_db from utils import constants import atm def get_thermal_noise(bandwidth_hz, noise_figure_db=0, temp_ext_k=0): """ N = thermal_noise(bw,nf,t_ext) Compute the total noise power, given the receiver's noise bandwidth, noise figure, and...
noise/model.py
import numpy as np from utils.unit_conversions import db_to_lin, lin_to_db from utils import constants import atm def get_thermal_noise(bandwidth_hz, noise_figure_db=0, temp_ext_k=0): """ N = thermal_noise(bw,nf,t_ext) Compute the total noise power, given the receiver's noise bandwidth, noise figure, and...
0.911642
0.610395
# --- imports ----------------------------------------------------------------- import torch.nn as nn import tensorflow as tf from network.wrappers.NetworkBase import NetworkBase class ResNet(NetworkBase): def __init__(self, network_type, loss, accuracy, lr, framework, training, trainable_layers=None, num_filt...
network/wrappers/ResNet.py
# --- imports ----------------------------------------------------------------- import torch.nn as nn import tensorflow as tf from network.wrappers.NetworkBase import NetworkBase class ResNet(NetworkBase): def __init__(self, network_type, loss, accuracy, lr, framework, training, trainable_layers=None, num_filt...
0.945676
0.467636
import numpy as np from skimage.io import imread, imsave import os import sys def color_transfer(content_img, style_img): ''' Transfer style image color to content image. Method described in https://arxiv.org/abs/1606.05897 Args: content_img: type=ndarray, shape=(Wc,Hc,C=3) s...
AGD_ST/search/util_visual/colortransfer.py
import numpy as np from skimage.io import imread, imsave import os import sys def color_transfer(content_img, style_img): ''' Transfer style image color to content image. Method described in https://arxiv.org/abs/1606.05897 Args: content_img: type=ndarray, shape=(Wc,Hc,C=3) s...
0.432782
0.422922
import numpy as np import tensorflow as tf from sklearn.neighbors import KDTree from tqdm import tqdm from config import read_config from data_loader import DataLoader from sincnet import create_print_maker def check_norms(vectors): norms = [np.linalg.norm(v) for v in vectors] assert abs(1 - min(norms)) < 1e...
test_print_maker.py
import numpy as np import tensorflow as tf from sklearn.neighbors import KDTree from tqdm import tqdm from config import read_config from data_loader import DataLoader from sincnet import create_print_maker def check_norms(vectors): norms = [np.linalg.norm(v) for v in vectors] assert abs(1 - min(norms)) < 1e...
0.663342
0.49939
from boto.s3.key import Key from sdk_release_tools import log from sdk_release_tools.versions import parse_major_minor import os __all__ = ['Delete', 'Download', 'Pin', 'Unpin', 'Upload', 'delete', 'download', 'pin', 'unpin', 'upload'] def absolute(root): if not os.path.isabs(root): root = os...
node_modules/twilio-sync/tools/sdk-release-tool/sdk_release_tools/ops.py
from boto.s3.key import Key from sdk_release_tools import log from sdk_release_tools.versions import parse_major_minor import os __all__ = ['Delete', 'Download', 'Pin', 'Unpin', 'Upload', 'delete', 'download', 'pin', 'unpin', 'upload'] def absolute(root): if not os.path.isabs(root): root = os...
0.587352
0.121921
from rest_framework import viewsets, status, filters, generics from rest_framework.response import Response from obeflix_back.models import Video, Categoria from obeflix_back.serializer import VideoSerializer, CategoriaSerializer, ListaVideoPorCategoriaSerializer class VideosViewSet(viewsets.ModelViewSet): """Ex...
obeflix_back/views.py
from rest_framework import viewsets, status, filters, generics from rest_framework.response import Response from obeflix_back.models import Video, Categoria from obeflix_back.serializer import VideoSerializer, CategoriaSerializer, ListaVideoPorCategoriaSerializer class VideosViewSet(viewsets.ModelViewSet): """Ex...
0.478041
0.146362
from user import User from credentials import Credentials import random def greetings(): print(" __ __ ") print(" /\ /\ | | | | ") print("| | | | ________ | | | | _____ ") print("| |____| | | _...
run.py
from user import User from credentials import Credentials import random def greetings(): print(" __ __ ") print(" /\ /\ | | | | ") print("| | | | ________ | | | | _____ ") print("| |____| | | _...
0.290176
0.13759
import numpy as np import math from scipy.sparse import diags from scipy import linalg import matplotlib.pyplot as plt import pandas as pd from sklearn import metrics import base64 # Material class defines a dictionary conditioning an information # on material characteristics of each element layer class Material: d...
calc/htool.py
import numpy as np import math from scipy.sparse import diags from scipy import linalg import matplotlib.pyplot as plt import pandas as pd from sklearn import metrics import base64 # Material class defines a dictionary conditioning an information # on material characteristics of each element layer class Material: d...
0.293202
0.342159
from __future__ import print_function import copy import json import re import traceback import zipfile import arrow from passive_data_kit.models import DataPoint from passive_data_kit_external_data.models import annotate_field from ..utils import hash_content, encrypt_content, create_engagement_event, queue_batch...
importers/facebook.py
from __future__ import print_function import copy import json import re import traceback import zipfile import arrow from passive_data_kit.models import DataPoint from passive_data_kit_external_data.models import annotate_field from ..utils import hash_content, encrypt_content, create_engagement_event, queue_batch...
0.38827
0.070144
import pytest import pgdb from test_02_submit_rider import generic_rider_insert from test_03_submit_driver import generic_driver_insert from test_04_matches import getMatcherActivityStats, getMatchRecord @pytest.fixture def pgdbConnMatchEngine(dbhost, db, matchengineuser): return pgdb.connect(...
db/test/test_05_user_actions.py
import pytest import pgdb from test_02_submit_rider import generic_rider_insert from test_03_submit_driver import generic_driver_insert from test_04_matches import getMatcherActivityStats, getMatchRecord @pytest.fixture def pgdbConnMatchEngine(dbhost, db, matchengineuser): return pgdb.connect(...
0.342901
0.120905
import pandas as pd class Dataset: def __init__(self): self.train_set = None self.vocab_index = {} self.index_vocab = {} self.vocab_length = -1 def load_dataset(self): self.train_set = pd.read_csv('data/dataset_annotated.csv', encoding='ISO-8859-1') # print(tr...
dataset.py
import pandas as pd class Dataset: def __init__(self): self.train_set = None self.vocab_index = {} self.index_vocab = {} self.vocab_length = -1 def load_dataset(self): self.train_set = pd.read_csv('data/dataset_annotated.csv', encoding='ISO-8859-1') # print(tr...
0.328637
0.108519
import math from collections import OrderedDict import torch import torch.nn as nn from torch.utils import model_zoo class CBR(nn.Module): """ This class defines the convolution layer with batch normalization and PReLU activation """ def __init__(self, n_in: int, n_out: int, k_size: int, stride: int...
src/daain/backbones/esp_net/layers.py
import math from collections import OrderedDict import torch import torch.nn as nn from torch.utils import model_zoo class CBR(nn.Module): """ This class defines the convolution layer with batch normalization and PReLU activation """ def __init__(self, n_in: int, n_out: int, k_size: int, stride: int...
0.967333
0.606061
import uuid from datetime import date, datetime, timedelta from typing import Dict, List, Optional, Union import numpy as np import pandas as pd import pyarrow from pydantic import StrictStr from pydantic.typing import Literal from tenacity import Retrying, retry_if_exception_type, stop_after_delay, wait_fixed from f...
sdk/python/feast/infra/offline_stores/maxcompute.py
import uuid from datetime import date, datetime, timedelta from typing import Dict, List, Optional, Union import numpy as np import pandas as pd import pyarrow from pydantic import StrictStr from pydantic.typing import Literal from tenacity import Retrying, retry_if_exception_type, stop_after_delay, wait_fixed from f...
0.730482
0.225566
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('general_business', '0001_initial'), ('product', '0002_productpriceobj'), ] operations = [ migrations.CreateModel( name='P...
product/migrations/0003_auto_20210616_0915.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('general_business', '0001_initial'), ('product', '0002_productpriceobj'), ] operations = [ migrations.CreateModel( name='P...
0.506103
0.120387
import logging import os import webapp2 from webapp2_extras import jinja2 from appengine_module.cr_rev import controller class BaseHandler(webapp2.RequestHandler): """Provide a cached Jinja environment to each request.""" def __init__(self, *args, **kwargs): webapp2.RequestHandler.__init__(self, *args, **k...
appengine/cr_rev/appengine_module/cr_rev/views.py
import logging import os import webapp2 from webapp2_extras import jinja2 from appengine_module.cr_rev import controller class BaseHandler(webapp2.RequestHandler): """Provide a cached Jinja environment to each request.""" def __init__(self, *args, **kwargs): webapp2.RequestHandler.__init__(self, *args, **k...
0.709321
0.06724
import os import cv2 import numpy as np class Image: ''' This class contains all the image utils for the package but You can also use it. Methods: bgr_to_grey bgr_to_rgb resize crop read_img read_video ''' def __init__(self): pass d...
visionlib/utils/imgutils.py
import os import cv2 import numpy as np class Image: ''' This class contains all the image utils for the package but You can also use it. Methods: bgr_to_grey bgr_to_rgb resize crop read_img read_video ''' def __init__(self): pass d...
0.825097
0.465873
from argparse import ArgumentParser from tabulate import tabulate from termcolor import colored from taoist.read_project_dict import read_project_dict from taoist.read_label_dict import read_label_dict from taoist.parent_project import parent_project async def run_task(args: ArgumentParser) -> None: """ Run ...
taoist/run_task.py
from argparse import ArgumentParser from tabulate import tabulate from termcolor import colored from taoist.read_project_dict import read_project_dict from taoist.read_label_dict import read_label_dict from taoist.parent_project import parent_project async def run_task(args: ArgumentParser) -> None: """ Run ...
0.348645
0.1382
from pipeline import phot_pipeline from pipeline import spec_pipeline from pipeline import analysis from astropy.io import fits, ascii import os import matplotlib.pyplot as plt import pdb import numpy as np def test_binning(): """ Test the binning function""" x = np.linspace(0,10,1024) y = np.random.randn(...
tshirt/tser_tests.py
from pipeline import phot_pipeline from pipeline import spec_pipeline from pipeline import analysis from astropy.io import fits, ascii import os import matplotlib.pyplot as plt import pdb import numpy as np def test_binning(): """ Test the binning function""" x = np.linspace(0,10,1024) y = np.random.randn(...
0.546254
0.387227
import os from pypeline.common.fileutils import missing_files from pypeline.atomiccmd.builder import apply_options from pypeline.nodes.adapterremoval import \ SE_AdapterRemovalNode, \ PE_AdapterRemovalNode, \ VERSION_14, \ VERSION_15 from pypeline.nodes.validation import \ ValidateFASTQFilesNode ...
pypeline/tools/bam_pipeline/parts/reads.py
import os from pypeline.common.fileutils import missing_files from pypeline.atomiccmd.builder import apply_options from pypeline.nodes.adapterremoval import \ SE_AdapterRemovalNode, \ PE_AdapterRemovalNode, \ VERSION_14, \ VERSION_15 from pypeline.nodes.validation import \ ValidateFASTQFilesNode ...
0.41561
0.255077
import sys import queue import numbers import math if len(sys.argv) != 2: print("Help: {} <filename>".format(sys.argv[0])) sys.exit(0) class Number: def __init__(self, number_string): self.arr = [int(x) if x.isnumeric() else x for x in list(number_string)] def process(self, spl...
puzzle/day18.py
import sys import queue import numbers import math if len(sys.argv) != 2: print("Help: {} <filename>".format(sys.argv[0])) sys.exit(0) class Number: def __init__(self, number_string): self.arr = [int(x) if x.isnumeric() else x for x in list(number_string)] def process(self, spl...
0.127925
0.125065
import os import time import json import argparse from deeprob.utils.data import DataStandardizer from deeprob.spn.utils.statistics import compute_statistics from deeprob.spn.structure.leaf import Bernoulli, Gaussian from deeprob.spn.learning.wrappers import learn_estimator from experiments.datasets import load_binar...
experiments/spn.py
import os import time import json import argparse from deeprob.utils.data import DataStandardizer from deeprob.spn.utils.statistics import compute_statistics from deeprob.spn.structure.leaf import Bernoulli, Gaussian from deeprob.spn.learning.wrappers import learn_estimator from experiments.datasets import load_binar...
0.750918
0.26514
import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>#@(*%7!*9#q%pgyedotv%lp@9nfbj' ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'rogue.iplantcollaborative.org', 'data.cyverse.org', '*'] # SECURITY WARNING: don't run with...
django/settings.py
import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>#@(*%7!*9#q%pgyedotv%lp@9nfbj' ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'rogue.iplantcollaborative.org', 'data.cyverse.org', '*'] # SECURITY WARNING: don't run with...
0.196518
0.097176
import torch.nn.functional as F import geometry import os import numpy as np import torch import collections def parse_intrinsics_hdf5(raw_data, trgt_sidelength=None, invert_y=False): s = raw_data[...].tostring() s = s.decode('utf-8') lines = s.split('\n') f, cx, cy, _ = map(float, lines[0].split())...
util.py
import torch.nn.functional as F import geometry import os import numpy as np import torch import collections def parse_intrinsics_hdf5(raw_data, trgt_sidelength=None, invert_y=False): s = raw_data[...].tostring() s = s.decode('utf-8') lines = s.split('\n') f, cx, cy, _ = map(float, lines[0].split())...
0.557845
0.511595
from unittest.mock import Mock import pytest from airflow.models import DAG from airflow.models.baseoperator import BaseOperator from airflow.ti_deps.dep_context import DepContext from airflow.ti_deps.deps.prev_dagrun_dep import PrevDagrunDep from airflow.utils.state import State from airflow.utils.timezone import ...
tests/ti_deps/deps/test_prev_dagrun_dep.py
from unittest.mock import Mock import pytest from airflow.models import DAG from airflow.models.baseoperator import BaseOperator from airflow.ti_deps.dep_context import DepContext from airflow.ti_deps.deps.prev_dagrun_dep import PrevDagrunDep from airflow.utils.state import State from airflow.utils.timezone import ...
0.618089
0.462352
from server.custom_exceptions.input_missing import InputMissing from server.custom_exceptions.input_not_int import InputNotInteger from server.custom_exceptions.paper_trade_id_missing import PaperTradeIdMissing from server.custom_exceptions.paper_trade_id_not_int import PaperTradeIdNotInt from server.custom_exceptions....
server/service_layer/implementation_classes/paper_trade_service.py
from server.custom_exceptions.input_missing import InputMissing from server.custom_exceptions.input_not_int import InputNotInteger from server.custom_exceptions.paper_trade_id_missing import PaperTradeIdMissing from server.custom_exceptions.paper_trade_id_not_int import PaperTradeIdNotInt from server.custom_exceptions....
0.760651
0.177205
import time from pathlib import Path import os import numpy as np from py_diff_pd.env.env_base import EnvBase from py_diff_pd.common.common import create_folder, ndarray from py_diff_pd.common.hex_mesh import generate_hex_mesh, hex2obj from py_diff_pd.common.tet_mesh import generate_tet_mesh, tet2obj, tetrahedralize ...
python/py_diff_pd/env/bunny_env_3d.py
import time from pathlib import Path import os import numpy as np from py_diff_pd.env.env_base import EnvBase from py_diff_pd.common.common import create_folder, ndarray from py_diff_pd.common.hex_mesh import generate_hex_mesh, hex2obj from py_diff_pd.common.tet_mesh import generate_tet_mesh, tet2obj, tetrahedralize ...
0.555918
0.325668
import asyncio import disnake from typing import Dict, List from disnake import RawMessageDeleteEvent, RawMessageUpdateEvent from disnake.ext.commands import Bot import utilities.random from models.database.message import Message from services.database.message_db import retrieve_copy_messages from services.database....
services/portal/transmission.py
import asyncio import disnake from typing import Dict, List from disnake import RawMessageDeleteEvent, RawMessageUpdateEvent from disnake.ext.commands import Bot import utilities.random from models.database.message import Message from services.database.message_db import retrieve_copy_messages from services.database....
0.72487
0.064535
"""E(x)hentai components.""" import os import re import requests from bs4 import BeautifulSoup import modules.misc as misc from modules import exception _LOGIN_URL = 'https://forums.e-hentai.org/index.php' _ACCOUNT_URL = 'https://e-hentai.org/home.php' _EXHENTAI_URL = 'https://exhentai.org/' def _ban_checker(html:...
modules/ehentai/core.py
"""E(x)hentai components.""" import os import re import requests from bs4 import BeautifulSoup import modules.misc as misc from modules import exception _LOGIN_URL = 'https://forums.e-hentai.org/index.php' _ACCOUNT_URL = 'https://e-hentai.org/home.php' _EXHENTAI_URL = 'https://exhentai.org/' def _ban_checker(html:...
0.412412
0.132178
import c4d from c4d import utils from c4d.modules import bodypaint def main(): # Retrieves active UVSet handle = bodypaint.GetActiveUVSet(doc, c4d.GETACTIVEUVSET_ALL) if not handle: print "No active UVSet!" return # Prints UVSet information print "UV Handle Data:" print "Hand...
scripts/release18/CallUVCommand.py
import c4d from c4d import utils from c4d.modules import bodypaint def main(): # Retrieves active UVSet handle = bodypaint.GetActiveUVSet(doc, c4d.GETACTIVEUVSET_ALL) if not handle: print "No active UVSet!" return # Prints UVSet information print "UV Handle Data:" print "Hand...
0.441914
0.09611
from biokbase.workspace.client import Workspace import biokbase.auth import os from getpass import getpass import json import time prod_ws = 'https://kbase.us/services/ws' ci_ws = 'https://ci.kbase.us/services/ws' ws_metadata = { 'is_temporary': False, 'narrative_nice_name': None } def fetch_narrative(nar_id,...
src/biokbase/narrative/tests/narrative_test_helper.py
from biokbase.workspace.client import Workspace import biokbase.auth import os from getpass import getpass import json import time prod_ws = 'https://kbase.us/services/ws' ci_ws = 'https://ci.kbase.us/services/ws' ws_metadata = { 'is_temporary': False, 'narrative_nice_name': None } def fetch_narrative(nar_id,...
0.494873
0.188324
import os import unittest import json import trebek import entities import fakeredis import time import datetime # Reference this SO post on getting distances between strings: # http://stackoverflow.com/a/1471603/98562 def get_clue_json(): with open('test-json-output.json') as json_data: clue = json.load(j...
test_trebek.py
import os import unittest import json import trebek import entities import fakeredis import time import datetime # Reference this SO post on getting distances between strings: # http://stackoverflow.com/a/1471603/98562 def get_clue_json(): with open('test-json-output.json') as json_data: clue = json.load(j...
0.443359
0.208703
import numpy as np from nose.plugins.attrib import attr from ion_functions.data.perf.test_performance import PerformanceTestCase from ion_functions.data import adcp_functions as af # Note, the VADCP related data products use the same internal functions as the # family of beam wrapper functions (e.g. adcp_beam_eastwar...
ion_functions/data/perf/test_adcp_performance.py
import numpy as np from nose.plugins.attrib import attr from ion_functions.data.perf.test_performance import PerformanceTestCase from ion_functions.data import adcp_functions as af # Note, the VADCP related data products use the same internal functions as the # family of beam wrapper functions (e.g. adcp_beam_eastwar...
0.654453
0.540014
import copy import logging import os import subprocess import time import traceback from functools import wraps from thundra import constants from thundra.application.global_application_info_provider import GlobalApplicationInfoProvider from thundra.compat import PY2, TimeoutError from thundra.config import config_nam...
thundra/wrappers/aws_lambda/lambda_wrapper.py
import copy import logging import os import subprocess import time import traceback from functools import wraps from thundra import constants from thundra.application.global_application_info_provider import GlobalApplicationInfoProvider from thundra.compat import PY2, TimeoutError from thundra.config import config_nam...
0.336222
0.042245
import time from odoo.tests.common import TransactionCase class TestHrAttendance(TransactionCase): """Tests for attendance date ranges validity""" def setUp(self): super(TestHrAttendance, self).setUp() self.attendance = self.env["res.partner.attendance"] self.test_partner = self.env...
base_attendance/tests/test_hr_attendance_constraints.py
import time from odoo.tests.common import TransactionCase class TestHrAttendance(TransactionCase): """Tests for attendance date ranges validity""" def setUp(self): super(TestHrAttendance, self).setUp() self.attendance = self.env["res.partner.attendance"] self.test_partner = self.env...
0.496338
0.295573
from django.db import models from apps.ventas.producto.models import Producto from datetime import datetime # Create your models here. date = datetime.now() class Proveedor(models.Model): """[summary] Args: models ([Proveedor]): [Contiene la informacion de los proveedores] """ nombre_pro...
sysvet/apps/compras/models.py
from django.db import models from apps.ventas.producto.models import Producto from datetime import datetime # Create your models here. date = datetime.now() class Proveedor(models.Model): """[summary] Args: models ([Proveedor]): [Contiene la informacion de los proveedores] """ nombre_pro...
0.60964
0.207135
import numpy as np def forward(Observation, Emission, Transition, Initial): """ Performs the forward algorithm for a hidden markov model: Observation is a numpy.ndarray of shape (T,) that contains the index of the observation T is the number of observations Emission is a numpy.ndarray of ...
unsupervised_learning/0x02-hmm/6-baum_welch.py
import numpy as np def forward(Observation, Emission, Transition, Initial): """ Performs the forward algorithm for a hidden markov model: Observation is a numpy.ndarray of shape (T,) that contains the index of the observation T is the number of observations Emission is a numpy.ndarray of ...
0.899723
0.930046
from pprint import pformat from six import iteritems import re class V1ServiceSpec(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attri...
mac/google-cloud-sdk/lib/third_party/kubernetes/client/models/v1_service_spec.py
from pprint import pformat from six import iteritems import re class V1ServiceSpec(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attri...
0.680135
0.115761
from __future__ import print_function import copy import os import shutil import sys import mock from chromite.lib import constants from chromite.cli import command_unittest from chromite.cli.cros import cros_chrome_sdk from chromite.lib import cache from chromite.lib import cros_build_lib from chromite.lib import c...
cli/cros/cros_chrome_sdk_unittest.py
from __future__ import print_function import copy import os import shutil import sys import mock from chromite.lib import constants from chromite.cli import command_unittest from chromite.cli.cros import cros_chrome_sdk from chromite.lib import cache from chromite.lib import cros_build_lib from chromite.lib import c...
0.525856
0.107531
from __clrclasses__.System.Runtime.CompilerServices import AccessedThroughPropertyAttribute from __clrclasses__.System.Runtime.CompilerServices import AsyncStateMachineAttribute from __clrclasses__.System.Runtime.CompilerServices import AsyncTaskMethodBuilder from __clrclasses__.System.Runtime.CompilerServices import A...
extensions/.stubs/clrclasses/System/Runtime/CompilerServices/__init__.py
from __clrclasses__.System.Runtime.CompilerServices import AccessedThroughPropertyAttribute from __clrclasses__.System.Runtime.CompilerServices import AsyncStateMachineAttribute from __clrclasses__.System.Runtime.CompilerServices import AsyncTaskMethodBuilder from __clrclasses__.System.Runtime.CompilerServices import A...
0.613121
0.031232
import os import torch import torch.nn.functional as F import yaml import copy from ast import literal_eval from typing import Callable, Iterable, List, TypeVar import torch.distributed as dist from typing import Tuple import argparse A = TypeVar("A") B = TypeVar("B") class TimeDistributed(torch.nn.Module): """ ...
src/util.py
import os import torch import torch.nn.functional as F import yaml import copy from ast import literal_eval from typing import Callable, Iterable, List, TypeVar import torch.distributed as dist from typing import Tuple import argparse A = TypeVar("A") B = TypeVar("B") class TimeDistributed(torch.nn.Module): """ ...
0.883845
0.498901
import pandas as pd import numpy as np import argparse import sys import os import pdb import collections import glob import rpy2 from multiprocessing import Pool sys.path.append('../common/') import utilities as util import analysis import mutation_base def get_options(): parser = argparse.ArgumentParser(descripti...
copy_number/interesting_genes_trichotomized_zscores.py
import pandas as pd import numpy as np import argparse import sys import os import pdb import collections import glob import rpy2 from multiprocessing import Pool sys.path.append('../common/') import utilities as util import analysis import mutation_base def get_options(): parser = argparse.ArgumentParser(descripti...
0.241042
0.118819
from footmark.ecs.connection import ECSConnection from tests.unit import ACSMockServiceTestCase import json DESCRIBE_INSTANCE = ''' { "Instances": { "Instance": [ { "CreationTime": "2016-06-20T21:37Z", "DeviceAvailable": true, "EipAddress": {}, "ExpiredTime": "2016-10-22T16:...
tests/unit/ecs/test_instance.py
from footmark.ecs.connection import ECSConnection from tests.unit import ACSMockServiceTestCase import json DESCRIBE_INSTANCE = ''' { "Instances": { "Instance": [ { "CreationTime": "2016-06-20T21:37Z", "DeviceAvailable": true, "EipAddress": {}, "ExpiredTime": "2016-10-22T16:...
0.464416
0.27506
import argparse import tempfile import hashlib from bioconverters import convert import shutil import urllib.request as request from contextlib import closing import time import gzip import sys import string import re import os from datetime import datetime from dbutils import saveDocumentsToDatabase def download_...
convertPubmed.py
import argparse import tempfile import hashlib from bioconverters import convert import shutil import urllib.request as request from contextlib import closing import time import gzip import sys import string import re import os from datetime import datetime from dbutils import saveDocumentsToDatabase def download_...
0.217836
0.29438
from decapod_common import log from decapod_common import playbook_plugin from decapod_common import playbook_plugin_hints from decapod_common.models import cluster_data DESCRIPTION = "Add RBD Mirroring host" """Plugin description.""" HINTS_SCHEMA = { "remote_username": { "description": "Remote user keyr...
plugins/playbook/add_rbdmirror/decapod_plugin_playbook_add_rbdmirror/plugin.py
from decapod_common import log from decapod_common import playbook_plugin from decapod_common import playbook_plugin_hints from decapod_common.models import cluster_data DESCRIPTION = "Add RBD Mirroring host" """Plugin description.""" HINTS_SCHEMA = { "remote_username": { "description": "Remote user keyr...
0.719088
0.259126
from univers.gem import GemRequirement from univers.gem import GemVersion from univers.gem import InvalidVersionError def assert_bumped_version_equal(expected, unbumped): # Assert that bumping the +unbumped+ version yields the +expected+. assert_version_eql(expected, GemVersion(unbumped).bump()) def test_...
tests/test_rubygems_gem_version.py
from univers.gem import GemRequirement from univers.gem import GemVersion from univers.gem import InvalidVersionError def assert_bumped_version_equal(expected, unbumped): # Assert that bumping the +unbumped+ version yields the +expected+. assert_version_eql(expected, GemVersion(unbumped).bump()) def test_...
0.747708
0.640397
import argparse import json import requests #### Gather CLI arguments # Requres a PR message to be passed in as a text file to --prmessage parser = argparse.ArgumentParser() parser.add_argument("--prmessage", help="File path to a newline separated PR description", required=True) parser.add_argument("--outputfile", hel...
tryodaf-check-pr.py
import argparse import json import requests #### Gather CLI arguments # Requres a PR message to be passed in as a text file to --prmessage parser = argparse.ArgumentParser() parser.add_argument("--prmessage", help="File path to a newline separated PR description", required=True) parser.add_argument("--outputfile", hel...
0.051
0.164684
import json import logging import logging.config import os import sys from pathlib import Path import pretty_errors # NOQA: F401 (imported but unused) from rich.logging import RichHandler # Configuration NOCACHE = os.environ.get("SOCCERDATA_NOCACHE", 'False').lower() in ('true', '1', 't') NOSTORE = os.environ.get("...
soccerdata/_config.py
import json import logging import logging.config import os import sys from pathlib import Path import pretty_errors # NOQA: F401 (imported but unused) from rich.logging import RichHandler # Configuration NOCACHE = os.environ.get("SOCCERDATA_NOCACHE", 'False').lower() in ('true', '1', 't') NOSTORE = os.environ.get("...
0.171963
0.198899
import hashlib import unittest from binascii import hexlify, unhexlify from context import bitcoinutils from bitcoinutils.setup import setup from bitcoinutils.keys import PrivateKey, P2pkhAddress, P2shAddress, P2wpkhAddress from bitcoinutils.constants import SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE, \ SIGHASH_ANY...
tests/test_p2wpkh_txs.py
import hashlib import unittest from binascii import hexlify, unhexlify from context import bitcoinutils from bitcoinutils.setup import setup from bitcoinutils.keys import PrivateKey, P2pkhAddress, P2shAddress, P2wpkhAddress from bitcoinutils.constants import SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE, \ SIGHASH_ANY...
0.341692
0.266906
UNO_CARDS = [ ":R1:549406471633371147", ":R2:549406503602356245", ":R3:549406530298970124", ":R4:549406528642220033", ":R5:549406529602846742", ":R6:549406531347808284", ":R7:549406528470253579", ":R8:549406531079372815", ":R9:549406531700129792", ":RR:549406530437644289", ":RS:549406531679158272", ":RP:54940653093...
cogs/game/minigames/uno/variables.py
UNO_CARDS = [ ":R1:549406471633371147", ":R2:549406503602356245", ":R3:549406530298970124", ":R4:549406528642220033", ":R5:549406529602846742", ":R6:549406531347808284", ":R7:549406528470253579", ":R8:549406531079372815", ":R9:549406531700129792", ":RR:549406530437644289", ":RS:549406531679158272", ":RP:54940653093...
0.177098
0.482917
import torch from torch.optim.optimizer import Optimizer from pytorch_optimizer.base_optimizer import BaseOptimizer from pytorch_optimizer.types import CLOSURE, DEFAULTS, LOSS, PARAMETERS from pytorch_optimizer.utils import neuron_mean, neuron_norm class Nero(Optimizer, BaseOptimizer): """ Reference : https:...
pytorch_optimizer/nero.py
import torch from torch.optim.optimizer import Optimizer from pytorch_optimizer.base_optimizer import BaseOptimizer from pytorch_optimizer.types import CLOSURE, DEFAULTS, LOSS, PARAMETERS from pytorch_optimizer.utils import neuron_mean, neuron_norm class Nero(Optimizer, BaseOptimizer): """ Reference : https:...
0.90226
0.412441
from __future__ import absolute_import import fileinfo import os import numpy as np def ie_filename(theoryname, R = 1.0, oper=False, tag="", fullpath = False, clusteronly = False, theta = 0.0, absh=1.0): if fullpath: dirname = fileinfo.XARPATH else: dirname = "" if oper: if cluster...
namegen.py
from __future__ import absolute_import import fileinfo import os import numpy as np def ie_filename(theoryname, R = 1.0, oper=False, tag="", fullpath = False, clusteronly = False, theta = 0.0, absh=1.0): if fullpath: dirname = fileinfo.XARPATH else: dirname = "" if oper: if cluster...
0.401805
0.065995
from unittest.mock import AsyncMock import pytest from nano_magic.adapters.client_channel import ClientChannel from nano_magic.adapters.messages import END_DECK from nano_magic.adapters.messages import POSITIVES @pytest.fixture def cards(): return [str(i) for i in range(7)] @pytest.mark.asyncio async def test...
tests/unit/nano_tcg/adapters/test_client_channel.py
from unittest.mock import AsyncMock import pytest from nano_magic.adapters.client_channel import ClientChannel from nano_magic.adapters.messages import END_DECK from nano_magic.adapters.messages import POSITIVES @pytest.fixture def cards(): return [str(i) for i in range(7)] @pytest.mark.asyncio async def test...
0.744099
0.601067
import wx import time import analyse as m # Define the tab content as classes: class tabGather(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.text = wx.StaticText(self, -1, "Please enter a #hashtag to search on Twitter", (45,20)) self.hashtagTextBox=wx...
main.py
import wx import time import analyse as m # Define the tab content as classes: class tabGather(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.text = wx.StaticText(self, -1, "Please enter a #hashtag to search on Twitter", (45,20)) self.hashtagTextBox=wx...
0.251096
0.058588
import mxnet as mx import json import os import logging class MXNetVisionServiceBatching(object): def __init__(self): """ Initialization for MXNet Vision Service supporting batch inference """ self.mxnet_ctx = None self.mx_model = None self.labels = None se...
samples/mnist/inference/mxnet/mnist_cnn_inference.py
import mxnet as mx import json import os import logging class MXNetVisionServiceBatching(object): def __init__(self): """ Initialization for MXNet Vision Service supporting batch inference """ self.mxnet_ctx = None self.mx_model = None self.labels = None se...
0.705379
0.211335
import sys import time import sunspec2.modbus.client as client import sunspec2.file.client as file_client from optparse import OptionParser """ Original suns options: -o: output mode for data (text, xml) -x: export model description (slang, xml) -t: transport type: tcp or rtu (default: tcp) ...
scripts/suns.py
import sys import time import sunspec2.modbus.client as client import sunspec2.file.client as file_client from optparse import OptionParser """ Original suns options: -o: output mode for data (text, xml) -x: export model description (slang, xml) -t: transport type: tcp or rtu (default: tcp) ...
0.282196
0.125172
from typing import Any, List, Optional, Union import ee def getTimeSeriesByRegion( x: ee.ImageCollection, reducer: Any, bands: Optional[Union[str, List[str]]] = None, geometry: Optional[Union[ee.Geometry, ee.Feature, ee.FeatureCollection]] = None, scale: Optional[Union[int, float]] = None, cr...
ee_extra/TimeSeries/core.py
from typing import Any, List, Optional, Union import ee def getTimeSeriesByRegion( x: ee.ImageCollection, reducer: Any, bands: Optional[Union[str, List[str]]] = None, geometry: Optional[Union[ee.Geometry, ee.Feature, ee.FeatureCollection]] = None, scale: Optional[Union[int, float]] = None, cr...
0.968827
0.632786
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
python/pb/xds/core/v3/authority_pb2.py
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
0.317744
0.10683
from abc import ABC, abstractmethod from wsqluse.wsqluse import Wsqluse from gc_qdk.main import GCoreQDK class WTAS(ABC, GCoreQDK): """ WServer To AR Sender. Абстрактный, основной класс, с которого наследуют иные классы, занимающиеся отправкой данных на AR. """ def __init__(self, polygon_ip, ...
wtas/main.py
from abc import ABC, abstractmethod from wsqluse.wsqluse import Wsqluse from gc_qdk.main import GCoreQDK class WTAS(ABC, GCoreQDK): """ WServer To AR Sender. Абстрактный, основной класс, с которого наследуют иные классы, занимающиеся отправкой данных на AR. """ def __init__(self, polygon_ip, ...
0.605916
0.253145
import sqlalchemy from sqlalchemy.orm import sessionmaker from pathlib import Path from typing import Optional from sqlalchemy.orm import Session from sqlalchemy.future.engine import Engine from models.model_base import ModelBase __engine: Optional[Engine] = None def create_engine(sqlite: bool = False) -> Engine: ...
src/sqlalchemy/03sqla_sync/conf/db_session.py
import sqlalchemy from sqlalchemy.orm import sessionmaker from pathlib import Path from typing import Optional from sqlalchemy.orm import Session from sqlalchemy.future.engine import Engine from models.model_base import ModelBase __engine: Optional[Engine] = None def create_engine(sqlite: bool = False) -> Engine: ...
0.781997
0.197444
import sys import time from django.db.backends.base.creation import BaseDatabaseCreation TEST_DATABASE_PREFIX = 'test_' PASSWORD = '<PASSWORD>' class DatabaseCreation(BaseDatabaseCreation): def _create_test_db(self, verbosity=1, autoclobber=False): TEST_NAME = self._test_database_name() ...
django_dmPython/src/django_dmPython/creation.py
import sys import time from django.db.backends.base.creation import BaseDatabaseCreation TEST_DATABASE_PREFIX = 'test_' PASSWORD = '<PASSWORD>' class DatabaseCreation(BaseDatabaseCreation): def _create_test_db(self, verbosity=1, autoclobber=False): TEST_NAME = self._test_database_name() ...
0.239705
0.111169
import asyncio from datetime import datetime import logging from OSMPythonTools.nominatim import Nominatim from googlemaps import Client TIMEOUT = 10 _LOGGER: logging.Logger = logging.getLogger(__package__) Coordinates = tuple[float, float] class JourneyApiClient: """API client for the OSM Nominatim and Goog...
custom_components/journey/api.py
import asyncio from datetime import datetime import logging from OSMPythonTools.nominatim import Nominatim from googlemaps import Client TIMEOUT = 10 _LOGGER: logging.Logger = logging.getLogger(__package__) Coordinates = tuple[float, float] class JourneyApiClient: """API client for the OSM Nominatim and Goog...
0.620277
0.208945
import json from pathlib import Path import bids from bids import BIDSLayout bids.config.set_option("extension_initial_dot", True) pattern = ( "sub-{subject}[/ses-{session}]/{datatype<anat|dwi>}/sub-{subject}" "[_ses-{session}][_acq-{acquisition}][_dir-{direction}][_run-{run}]" "_{suffix<T[12]w|dwi>}{ext...
hcp2bids/convert.py
import json from pathlib import Path import bids from bids import BIDSLayout bids.config.set_option("extension_initial_dot", True) pattern = ( "sub-{subject}[/ses-{session}]/{datatype<anat|dwi>}/sub-{subject}" "[_ses-{session}][_acq-{acquisition}][_dir-{direction}][_run-{run}]" "_{suffix<T[12]w|dwi>}{ext...
0.348423
0.202226
import sys import pprint import smtplib import time import uuid from email.mime.text import MIMEText from threading import Thread, Event DEBUG = True class Sender(): # TODO: Private, underscore args = None db = {} dur = 10 emails = 10 def __init__(self, host, port): self.init_db() ...
sender.py
import sys import pprint import smtplib import time import uuid from email.mime.text import MIMEText from threading import Thread, Event DEBUG = True class Sender(): # TODO: Private, underscore args = None db = {} dur = 10 emails = 10 def __init__(self, host, port): self.init_db() ...
0.128676
0.109825
import unittest import os import tensorflow as tf import gpflow from testing.gpflow_testcase import GPflowTestCase class TestConfigParsing(GPflowTestCase): def setUp(self): directory = os.path.dirname(os.path.realpath(__file__)) f = os.path.join(directory, 'gpflowrc_test.txt') self.conf = ...
GPflow/testing/test_config.py
import unittest import os import tensorflow as tf import gpflow from testing.gpflow_testcase import GPflowTestCase class TestConfigParsing(GPflowTestCase): def setUp(self): directory = os.path.dirname(os.path.realpath(__file__)) f = os.path.join(directory, 'gpflowrc_test.txt') self.conf = ...
0.627267
0.539711
import sys from PyQt5 import QtGui, QtCore, QtWidgets import pyqtgraph as pg from mainWindow import Ui_MainWindow from UDP.UDP_Server import UDP_ServerThread from UDP.UDP_Client import UDP_ClientThread from worker import Worker from TriDisplay import TriModel from plot import Plot from Utils.traces.trace import * from...
GUI/WifiMonitor/UI.py
import sys from PyQt5 import QtGui, QtCore, QtWidgets import pyqtgraph as pg from mainWindow import Ui_MainWindow from UDP.UDP_Server import UDP_ServerThread from UDP.UDP_Client import UDP_ClientThread from worker import Worker from TriDisplay import TriModel from plot import Plot from Utils.traces.trace import * from...
0.227298
0.047914
from typing import List from pandas import read_excel, DataFrame, Series, notnull, concat, isnull, \ ExcelFile from stringcase import snakecase from survey.constants import CATEGORY_SPLITTER from survey.surveys.metadata import QuestionMetadata, AttributeMetadata from survey.surveys.survey_creators import SurveyCr...
survey/surveys/survey_creators/pollfish_creator.py
from typing import List from pandas import read_excel, DataFrame, Series, notnull, concat, isnull, \ ExcelFile from stringcase import snakecase from survey.constants import CATEGORY_SPLITTER from survey.surveys.metadata import QuestionMetadata, AttributeMetadata from survey.surveys.survey_creators import SurveyCr...
0.679179
0.277387
from FeatureCloud.app.engine.app import AppState, app_state, Role, LogLevel from federated_dca.utils import load_params, trainInstince, average_model_params import bios @app_state('initial', Role.BOTH) class InitialState(AppState): def register(self): self.register_transition('train', Role.BOTH) def ...
federated_dca/app.py
from FeatureCloud.app.engine.app import AppState, app_state, Role, LogLevel from federated_dca.utils import load_params, trainInstince, average_model_params import bios @app_state('initial', Role.BOTH) class InitialState(AppState): def register(self): self.register_transition('train', Role.BOTH) def ...
0.564219
0.099558
import sys import numpy as np import xgboost as xgb from sklearn.datasets import load_svmlight_file import scipy.sparse import math import pandas as pd from sklearn.feature_extraction import DictVectorizer from seldon.pipeline.pandas_pipelines import BasePandasEstimator from collections import OrderedDict import io fr...
python/seldon/xgb.py
import sys import numpy as np import xgboost as xgb from sklearn.datasets import load_svmlight_file import scipy.sparse import math import pandas as pd from sklearn.feature_extraction import DictVectorizer from seldon.pipeline.pandas_pipelines import BasePandasEstimator from collections import OrderedDict import io fr...
0.685002
0.445409
from __future__ import print_function import argparse import sys import os import subprocess import time import xml.etree.ElementTree as ET from datetime import datetime # helpers def get_substring(s, leader, trailer): end_of_leader = s.index(leader) + len(leader) start_of_trailer = s.index(trailer, end_of_le...
breakbyseverity.py
from __future__ import print_function import argparse import sys import os import subprocess import time import xml.etree.ElementTree as ET from datetime import datetime # helpers def get_substring(s, leader, trailer): end_of_leader = s.index(leader) + len(leader) start_of_trailer = s.index(trailer, end_of_le...
0.132234
0.094093
import os import re import numpy as np import torch def calc_t_emb(ts, t_emb_dim): """ Embed time steps into a higher dimension space """ assert t_emb_dim % 2 == 0 half_dim = t_emb_dim // 2 t_emb = np.log(10000) / (half_dim - 1) t_emb = torch.exp(torch.arange(half_dim) * -t_emb) t_emb...
util.py
import os import re import numpy as np import torch def calc_t_emb(ts, t_emb_dim): """ Embed time steps into a higher dimension space """ assert t_emb_dim % 2 == 0 half_dim = t_emb_dim // 2 t_emb = np.log(10000) / (half_dim - 1) t_emb = torch.exp(torch.arange(half_dim) * -t_emb) t_emb...
0.786008
0.561996