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
from __future__ import with_statement import sys try: from setuptools import setup, Extension, Command except ImportError: from distutils.core import setup, Extension, Command from distutils.command.build_ext import build_ext from distutils.errors import CCompilerError, DistutilsExecError, \ DistutilsPlatf...
setup.py
from __future__ import with_statement import sys try: from setuptools import setup, Extension, Command except ImportError: from distutils.core import setup, Extension, Command from distutils.command.build_ext import build_ext from distutils.errors import CCompilerError, DistutilsExecError, \ DistutilsPlatf...
0.300438
0.102574
import tkinter as Tkinter from datetime import datetime import time import http.server import threading from urllib.parse import urlsplit class StopwatchServer(http.server.BaseHTTPRequestHandler): def do_POST(self): global label global running print(self.path) url = urlsplit(self.p...
stopwatch.py
import tkinter as Tkinter from datetime import datetime import time import http.server import threading from urllib.parse import urlsplit class StopwatchServer(http.server.BaseHTTPRequestHandler): def do_POST(self): global label global running print(self.path) url = urlsplit(self.p...
0.373762
0.098686
import click from parsec.commands.histories.create_dataset_collection import cli as func0 from parsec.commands.histories.create_history import cli as func1 from parsec.commands.histories.create_history_tag import cli as func2 from parsec.commands.histories.delete_dataset import cli as func3 from parsec.commands.histori...
parsec/commands/cmd_histories.py
import click from parsec.commands.histories.create_dataset_collection import cli as func0 from parsec.commands.histories.create_history import cli as func1 from parsec.commands.histories.create_history_tag import cli as func2 from parsec.commands.histories.delete_dataset import cli as func3 from parsec.commands.histori...
0.228156
0.10466
import json import time from pathlib import Path from tempfile import TemporaryDirectory from typing import Any, Dict, List import click from kaggle import KaggleApi from kaggle.models.kaggle_models_extended import KernelPushResponse from .. import kernel_proc from ..builders.packaging_system import get_dependencies ...
kkt/commands/install.py
import json import time from pathlib import Path from tempfile import TemporaryDirectory from typing import Any, Dict, List import click from kaggle import KaggleApi from kaggle.models.kaggle_models_extended import KernelPushResponse from .. import kernel_proc from ..builders.packaging_system import get_dependencies ...
0.388502
0.121999
from argparse import ArgumentParser, Namespace import codecs import sys import pickle import os import time import lysfastparse.utils import lysfastparse.bcovington.utils_bcovington import tempfile import yaml import subprocess import lysfastparse.bcovington.covington parser = ArgumentParser() parser.add_argument("-p...
run_model.py
from argparse import ArgumentParser, Namespace import codecs import sys import pickle import os import time import lysfastparse.utils import lysfastparse.bcovington.utils_bcovington import tempfile import yaml import subprocess import lysfastparse.bcovington.covington parser = ArgumentParser() parser.add_argument("-p...
0.234757
0.086709
from __future__ import unicode_literals from PIL import Image from subprocess import check_call from concurrent import futures import subprocess i...
pipelines/casia/sched.py
from __future__ import unicode_literals from PIL import Image from subprocess import check_call from concurrent import futures import subprocess i...
0.335133
0.087564
from __future__ import unicode_literals from django.db import models, migrations import django_extensions.db.fields.json class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Instance', fields=[ ('id', mode...
aws_admin/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations import django_extensions.db.fields.json class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Instance', fields=[ ('id', mode...
0.596551
0.140307
import unittest import FizzBuzz class TestFizzBuzz(unittest.TestCase): def test_normal(self): #tests that input >= 0 not evenly divisible #by 3,5, or 7 returns the same self.assertEqual(FizzBuzz.fizzbuzz(2), 2) self.assertEqual(FizzBuzz.fizzbuzz(67), 67) self.assertEqual(Fi...
projects/fizzbuzz/python/Lightner/test-FizzBuzz.py
import unittest import FizzBuzz class TestFizzBuzz(unittest.TestCase): def test_normal(self): #tests that input >= 0 not evenly divisible #by 3,5, or 7 returns the same self.assertEqual(FizzBuzz.fizzbuzz(2), 2) self.assertEqual(FizzBuzz.fizzbuzz(67), 67) self.assertEqual(Fi...
0.544075
0.660419
from rpython.rlib.rarithmetic import ovfcheck from rpython.rlib.rbigint import rbigint, _divrem from rpython.rtyper.lltypesystem import lltype, rffi from rpython.rtyper.lltypesystem.lloperation import llop from som.vmobjects.abstract_object import AbstractObject from som.vm.globals import trueObject, falseObject cla...
src/som/vmobjects/integer.py
from rpython.rlib.rarithmetic import ovfcheck from rpython.rlib.rbigint import rbigint, _divrem from rpython.rtyper.lltypesystem import lltype, rffi from rpython.rtyper.lltypesystem.lloperation import llop from som.vmobjects.abstract_object import AbstractObject from som.vm.globals import trueObject, falseObject cla...
0.692642
0.351395
import os import sys import re import numpy as np import pandas as pd level = sys.argv[1] kankyo_fpath = sys.argv[2] spname_fpath = sys.argv[3] class_fpath = sys.argv[4] output_fpath = sys.argv[5] def mesh2gps(mesh_code): mesh_code = str(mesh_code) lat = int(mesh_code[0:2]) * 2 / 3 lng = int(mesh_code[2...
10.3389/fevo.2021.762173/scripts/generate_meshdataset.py
import os import sys import re import numpy as np import pandas as pd level = sys.argv[1] kankyo_fpath = sys.argv[2] spname_fpath = sys.argv[3] class_fpath = sys.argv[4] output_fpath = sys.argv[5] def mesh2gps(mesh_code): mesh_code = str(mesh_code) lat = int(mesh_code[0:2]) * 2 / 3 lng = int(mesh_code[2...
0.128963
0.189634
import sys import matplotlib.pyplot as plt import numpy PLOT1 = { 'labels': [], 'uncompressed': [], 'gzip': [], 'lz4': [], 'lzma': [], } PLOT2 = { 'labels': [], 'uncompressed': [], 'gzip': [], 'lz4': [], 'lzma': [], } PLOT3 = { 'labels': [], 'uncompressed': [], 'gz...
plot.py
import sys import matplotlib.pyplot as plt import numpy PLOT1 = { 'labels': [], 'uncompressed': [], 'gzip': [], 'lz4': [], 'lzma': [], } PLOT2 = { 'labels': [], 'uncompressed': [], 'gzip': [], 'lz4': [], 'lzma': [], } PLOT3 = { 'labels': [], 'uncompressed': [], 'gz...
0.231006
0.459015
import web3 import util import client import pytest import json # --- test values --- hdr = "020000007ef055e1674d2e6551dba41cd214debbee34aeb544c7ec670000000000000000d3998963f80c5bab43fe8c26228e98d030edf4dcbe48a666f5c39e2d7a885c9102c86d536c890019593a470d" hdr_hex = int(hdr,16) hdr_bytes = hdr_hex.to_bytes(80,"big") h...
code/client/test_BtcBlk.py
import web3 import util import client import pytest import json # --- test values --- hdr = "020000007ef055e1674d2e6551dba41cd214debbee34aeb544c7ec670000000000000000d3998963f80c5bab43fe8c26228e98d030edf4dcbe48a666f5c39e2d7a885c9102c86d536c890019593a470d" hdr_hex = int(hdr,16) hdr_bytes = hdr_hex.to_bytes(80,"big") h...
0.423458
0.381709
import os import click import logging import h5py import keras import sklearn import numpy as np import keras_applications from tqdm import tqdm from sklearn.model_selection import train_test_split resolution = 256 def preprocess_image(image): x = keras.preprocessing.image.img_to_array(image) x = np.expand_...
prepro.py
import os import click import logging import h5py import keras import sklearn import numpy as np import keras_applications from tqdm import tqdm from sklearn.model_selection import train_test_split resolution = 256 def preprocess_image(image): x = keras.preprocessing.image.img_to_array(image) x = np.expand_...
0.378804
0.318406
import csv import datetime import re def main(): with open("data.csv", "r") as f: reader = csv.DictReader(f) first = True print("""insert into donations (donor, donee, amount, donation_date, donation_date_precision, donation_date_basis, cause_area, url, donor_cause_area_url...
proc.py
import csv import datetime import re def main(): with open("data.csv", "r") as f: reader = csv.DictReader(f) first = True print("""insert into donations (donor, donee, amount, donation_date, donation_date_precision, donation_date_basis, cause_area, url, donor_cause_area_url...
0.380529
0.265998
from typing import Set, Dict, Any from ... import Batch, LocalBackend, ServiceBackend, Backend from ...resource import Resource import os from os.path import exists import sys import shlex from argparse import Namespace, ArgumentParser, SUPPRESS import google.oauth2.service_account from google.cloud import storage from...
hail/python/hailtop/batch/genetics/regenie/regenie.py
from typing import Set, Dict, Any from ... import Batch, LocalBackend, ServiceBackend, Backend from ...resource import Resource import os from os.path import exists import sys import shlex from argparse import Namespace, ArgumentParser, SUPPRESS import google.oauth2.service_account from google.cloud import storage from...
0.45423
0.093471
from unittest.mock import patch import shaystack from shaystack import Ref from shaystack.ops import HaystackHttpRequest from shaystack.providers import ping @patch.object(ping.Provider, 'invoke_action') def test_invoke_action_with_zinc(mock) -> None: # GIVEN """ Args: mock: """ envs = {'...
tests/test_haystack_invoke_action.py
from unittest.mock import patch import shaystack from shaystack import Ref from shaystack.ops import HaystackHttpRequest from shaystack.providers import ping @patch.object(ping.Provider, 'invoke_action') def test_invoke_action_with_zinc(mock) -> None: # GIVEN """ Args: mock: """ envs = {'...
0.491944
0.483709
print('Значения вводятся через запятую') x1, y1 = map(float, input('Введите координаты 1 точки: ').split(',')) #A x2, y2 = map(float, input('Введите координаты 2 точки: ').split(',')) #B x3, y3 = map(float, input('Введите координаты 3 точки: ').split(',')) #C from math import sqrt AB = sqrt((x2 - x1) ** 2 + ...
1_semester/triangle.py
print('Значения вводятся через запятую') x1, y1 = map(float, input('Введите координаты 1 точки: ').split(',')) #A x2, y2 = map(float, input('Введите координаты 2 точки: ').split(',')) #B x3, y3 = map(float, input('Введите координаты 3 точки: ').split(',')) #C from math import sqrt AB = sqrt((x2 - x1) ** 2 + ...
0.088885
0.566258
import pytest from mitmproxy.test import tflow from mitmproxy.test import taddons from mitmproxy.addons import modifyheaders class TestModifyHeaders: def test_parse_modifyheaders(self): x = modifyheaders.parse_modify_headers("/foo/bar/voing") assert x == ("foo", "bar", "voing") x = modif...
test/mitmproxy/addons/test_modifyheaders.py
import pytest from mitmproxy.test import tflow from mitmproxy.test import taddons from mitmproxy.addons import modifyheaders class TestModifyHeaders: def test_parse_modifyheaders(self): x = modifyheaders.parse_modify_headers("/foo/bar/voing") assert x == ("foo", "bar", "voing") x = modif...
0.580352
0.421373
from django.db import models from rest_framework import serializers from django.contrib.postgres.fields import JSONField # Create your models here. class Account(models.Model): zone = models.CharField(default='+86', max_length=10) mobile = models.CharField(max_length=50) twitter = models.CharField(max_le...
apps/accounts/models.py
from django.db import models from rest_framework import serializers from django.contrib.postgres.fields import JSONField # Create your models here. class Account(models.Model): zone = models.CharField(default='+86', max_length=10) mobile = models.CharField(max_length=50) twitter = models.CharField(max_le...
0.59561
0.107578
from django.urls import re_path from . import views group_re = r'(?P<group>' + '|'.join(views.SERIES_GROUPS) + ')' group_date_re = r'(?P<group>' + '|'.join(views.SERIES_GROUPS_DATE) + ')' range_re = r'(?P<start>\d{8})-(?P<end>\d{8})' format_re = r'(?P<format>' + '|'.join(views.SERIES_FORMATS) + ')' series_re = r'%s-...
src/olympia/stats/urls.py
from django.urls import re_path from . import views group_re = r'(?P<group>' + '|'.join(views.SERIES_GROUPS) + ')' group_date_re = r'(?P<group>' + '|'.join(views.SERIES_GROUPS_DATE) + ')' range_re = r'(?P<start>\d{8})-(?P<end>\d{8})' format_re = r'(?P<format>' + '|'.join(views.SERIES_FORMATS) + ')' series_re = r'%s-...
0.535341
0.150122
import pytest import pandas as pd import datetime from aggregate_transactions import ( Strategy, process_file, calculate_proceeds, CoinbaseTransaction, TransactionType, ) @pytest.fixture(scope="session") def test_start_time(): return datetime.datetime.now() @pytest.fixture def simple_buy_df(...
test_aggregator.py
import pytest import pandas as pd import datetime from aggregate_transactions import ( Strategy, process_file, calculate_proceeds, CoinbaseTransaction, TransactionType, ) @pytest.fixture(scope="session") def test_start_time(): return datetime.datetime.now() @pytest.fixture def simple_buy_df(...
0.534612
0.453988
import argparse import configparser import os import shutil from jinja2 import Template from typing import Callable, Union, List from functools import reduce def parse_args(): """Return parsed args when this file is executed rather than imported.""" parser = argparse.ArgumentParser( description="Rend...
jinjawalk.py
import argparse import configparser import os import shutil from jinja2 import Template from typing import Callable, Union, List from functools import reduce def parse_args(): """Return parsed args when this file is executed rather than imported.""" parser = argparse.ArgumentParser( description="Rend...
0.833291
0.163579
from django import forms from haystack.forms import SearchForm from .fields import CustomField from apps.category.models import Category from apps.global_category.models import GlobalCategory from apps.shop.models import Shop from .models import Product, ProductImage class ProductForm(forms.ModelForm): class Met...
apps/product/forms.py
from django import forms from haystack.forms import SearchForm from .fields import CustomField from apps.category.models import Category from apps.global_category.models import GlobalCategory from apps.shop.models import Shop from .models import Product, ProductImage class ProductForm(forms.ModelForm): class Met...
0.480966
0.134208
import logging import socket import errno from io import BytesIO import msgpack import select _log = logging.getLogger(__name__) MSG_KEY_TYPE = "type" # Init message Felix -> Driver. MSG_TYPE_INIT = "init" MSG_KEY_ETCD_URLS = "etcd_urls" MSG_KEY_HOSTNAME = "hostname" MSG_KEY_KEY_FILE = "etcd_key_file" MSG_KEY_CERT_F...
calico/etcddriver/protocol.py
import logging import socket import errno from io import BytesIO import msgpack import select _log = logging.getLogger(__name__) MSG_KEY_TYPE = "type" # Init message Felix -> Driver. MSG_TYPE_INIT = "init" MSG_KEY_ETCD_URLS = "etcd_urls" MSG_KEY_HOSTNAME = "hostname" MSG_KEY_KEY_FILE = "etcd_key_file" MSG_KEY_CERT_F...
0.417509
0.053825
import mandelbrot.mandelbrot_alg as mb from numba import jit, njit, prange, vectorize, guvectorize, float64, int64 # Took the following from Thomas' example to avoid errors when trying to run files # No-op for use with profiling and test try: @profile def f(x): return x except: def profile(func): ...
mandelbrot/optimisation_methods.py
import mandelbrot.mandelbrot_alg as mb from numba import jit, njit, prange, vectorize, guvectorize, float64, int64 # Took the following from Thomas' example to avoid errors when trying to run files # No-op for use with profiling and test try: @profile def f(x): return x except: def profile(func): ...
0.724481
0.797754
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.ht...
config/urls.py
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='pages/home.ht...
0.356447
0.089216
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) 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 from google.p...
src/walker/edgelist_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) 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 from google.p...
0.263694
0.172033
import tensorflow.keras.applications as keras_models from codesign.config import supported_models from benchmark.benchmark import Workload from benchmark.computations import conv2d_compute, mm_compute, dwconv_compute def get_model(model_name, input_shape): if model_name not in supported_models: raise NotIm...
src/benchmark/keras_extend.py
import tensorflow.keras.applications as keras_models from codesign.config import supported_models from benchmark.benchmark import Workload from benchmark.computations import conv2d_compute, mm_compute, dwconv_compute def get_model(model_name, input_shape): if model_name not in supported_models: raise NotIm...
0.564459
0.282134
from time import sleep from typing import Tuple, Optional from urllib.parse import quote_plus import logging import requests import shelve from ..common import progress_bar from ..types import Document, Author, DocumentSet, DocumentIdentifier def extract_id(item): if item is None or not item.get('title'): ...
litstudy/sources/semanticscholar.py
from time import sleep from typing import Tuple, Optional from urllib.parse import quote_plus import logging import requests import shelve from ..common import progress_bar from ..types import Document, Author, DocumentSet, DocumentIdentifier def extract_id(item): if item is None or not item.get('title'): ...
0.787278
0.195633
import sys, os, subprocess, re, tempfile, getopt, signal def ex(cmd): return subprocess.Popen([ 'bash', '-c', cmd ], stdout = subprocess.PIPE).communicate()[0] def get_section_offsets(fn): obj_out = ex('objdump -h "%s"' % fn) ret = {} for line in obj_out.split('\n'): try: if line and re.match(".", ...
sniper/tools/attachgdb.py
import sys, os, subprocess, re, tempfile, getopt, signal def ex(cmd): return subprocess.Popen([ 'bash', '-c', cmd ], stdout = subprocess.PIPE).communicate()[0] def get_section_offsets(fn): obj_out = ex('objdump -h "%s"' % fn) ret = {} for line in obj_out.split('\n'): try: if line and re.match(".", ...
0.17172
0.14137
import binascii import pprint import sys from hmac_drbg import * def parse_entry(line): key, val = line.split('=') key = key.strip() val = val.strip() if val == 'True': val = True elif val == 'False': val = False elif val.isdigit(): val = int(val) return key, val d...
hmac_drbg_tests.py
import binascii import pprint import sys from hmac_drbg import * def parse_entry(line): key, val = line.split('=') key = key.strip() val = val.strip() if val == 'True': val = True elif val == 'False': val = False elif val.isdigit(): val = int(val) return key, val d...
0.208743
0.182171
import random from maze import Direction def binary_tree(grid): for cell in grid.each_cell(): neighbors = [] if cell.get_neighbor(Direction.NORTH): neighbors.append(cell.get_neighbor(Direction.NORTH)) if cell.get_neighbor(Direction.EAST): neighbors.append(cell.get_n...
maze/algorithm.py
import random from maze import Direction def binary_tree(grid): for cell in grid.each_cell(): neighbors = [] if cell.get_neighbor(Direction.NORTH): neighbors.append(cell.get_neighbor(Direction.NORTH)) if cell.get_neighbor(Direction.EAST): neighbors.append(cell.get_n...
0.374104
0.412471
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CheckResultList import CheckResultList class KoubeiQualityTestShieldResultSyncModel(object): def __init__(self): self._batch_no = None self._check_result_list = None self._order_id = None ...
alipay/aop/api/domain/KoubeiQualityTestShieldResultSyncModel.py
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CheckResultList import CheckResultList class KoubeiQualityTestShieldResultSyncModel(object): def __init__(self): self._batch_no = None self._check_result_list = None self._order_id = None ...
0.457864
0.063424
import unittest import os import glob import researcher as rs import numpy as np from tests.tools import TEST_EXPERIMENT_PATH class TestSavingExperiment(unittest.TestCase): def setUp(self): files = glob.glob(TEST_EXPERIMENT_PATH + "*") for f in files: os.remove(f) def test_reco...
tests/test_record.py
import unittest import os import glob import researcher as rs import numpy as np from tests.tools import TEST_EXPERIMENT_PATH class TestSavingExperiment(unittest.TestCase): def setUp(self): files = glob.glob(TEST_EXPERIMENT_PATH + "*") for f in files: os.remove(f) def test_reco...
0.562657
0.52342
import pytest import sys from ray._private.test_utils import run_string_as_driver @pytest.mark.parametrize("use_ray_client", [False, True]) @pytest.mark.skipif(sys.platform == "win32", reason="Fail to create temp dir.") def test_working_dir_deploy_new_version(ray_start, tmp_dir, use_ray_client): with open("hello...
python/ray/serve/tests/test_runtime_env_2.py
import pytest import sys from ray._private.test_utils import run_string_as_driver @pytest.mark.parametrize("use_ray_client", [False, True]) @pytest.mark.skipif(sys.platform == "win32", reason="Fail to create temp dir.") def test_working_dir_deploy_new_version(ray_start, tmp_dir, use_ray_client): with open("hello...
0.368406
0.306034
import datetime import dateutil.parser import pytest from openprocurement.auction.insider.constants import DUTCH def test_end_stage(auction, logger, mocker): auction.audit = { 'timeline': { DUTCH: { 'timeline': {} } } } ...
openprocurement/auction/insider/tests/unit/test_dutch_phase.py
import datetime import dateutil.parser import pytest from openprocurement.auction.insider.constants import DUTCH def test_end_stage(auction, logger, mocker): auction.audit = { 'timeline': { DUTCH: { 'timeline': {} } } } ...
0.616705
0.453746
import logging import sys import traceback import warnings from pathlib import Path class UltranestFilter(logging.Filter): def filter(self, record): return not record.getMessage().startswith("iteration=") class StreamToLogger(object): """ Fake file-like stream object that redirects writes to a ...
logs.py
import logging import sys import traceback import warnings from pathlib import Path class UltranestFilter(logging.Filter): def filter(self, record): return not record.getMessage().startswith("iteration=") class StreamToLogger(object): """ Fake file-like stream object that redirects writes to a ...
0.380759
0.101902
import unittest from mock import MagicMock, patch from state_model.put_state_model import put_state_model def get_mock_event(): return { 'session_id': '12345', 'state_model': { 'session_id': '12345', 'get_preference_result': 'success', 'existing_...
unit_tests/state_model/test_put_state_model.py
import unittest from mock import MagicMock, patch from state_model.put_state_model import put_state_model def get_mock_event(): return { 'session_id': '12345', 'state_model': { 'session_id': '12345', 'get_preference_result': 'success', 'existing_...
0.696887
0.247646
import os import shutil import subprocess DEST="/home/ubuntu/cleverhans/examples/nips17_adversarial_competition" META_DIR = "/home/ubuntu/adversarial_attack/metafiles" CONFIG_DIR = "config.csv" class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m'...
copy_files.py
import os import shutil import subprocess DEST="/home/ubuntu/cleverhans/examples/nips17_adversarial_competition" META_DIR = "/home/ubuntu/adversarial_attack/metafiles" CONFIG_DIR = "config.csv" class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m'...
0.052838
0.072341
import utilities import rasterio import numpy as np import datetime from scipy import stats import sys sys.path.append('../') import constants_and_names as cn import universal_util as uu def create_continent_ecozone_tiles(tile_id): print "Processing:", tile_id # Start time start = datetime.datetime.now(...
gain/continent_ecozone_tiles.py
import utilities import rasterio import numpy as np import datetime from scipy import stats import sys sys.path.append('../') import constants_and_names as cn import universal_util as uu def create_continent_ecozone_tiles(tile_id): print "Processing:", tile_id # Start time start = datetime.datetime.now(...
0.396769
0.340102
import pathlib as path import numpy as np from tslearn.metrics import dtw, dtw_path from tqdm import tqdm from modules.barycenter import sdtw_barycenter from modules.barycenter import gfsdtw_barycenter from auxiliary.dataset import load_ucr import time import fsdtw import itertools TIMESTAMP = time.strftime('%Y%m%d-%H...
barycenter.py
import pathlib as path import numpy as np from tslearn.metrics import dtw, dtw_path from tqdm import tqdm from modules.barycenter import sdtw_barycenter from modules.barycenter import gfsdtw_barycenter from auxiliary.dataset import load_ucr import time import fsdtw import itertools TIMESTAMP = time.strftime('%Y%m%d-%H...
0.293101
0.29005
from typing import List from enum import Enum import operator class State(Enum): FLOOR = 1 EMPTY = 2 OCCUPIED = 3 def __repr__(self): if self.value == self.FLOOR.value: return '.' elif self.value == self.OCCUPIED.value: return '#' else: retur...
Chris/Day11/hodges_day11.py
from typing import List from enum import Enum import operator class State(Enum): FLOOR = 1 EMPTY = 2 OCCUPIED = 3 def __repr__(self): if self.value == self.FLOOR.value: return '.' elif self.value == self.OCCUPIED.value: return '#' else: retur...
0.577019
0.460471
import re import shlex from subprocess import PIPE, Popen, TimeoutExpired class PlayerException(Exception): pass class PlayerCmdException(PlayerException): pass class Player(object): """ Player is a simple interface to a game playing process which is communicated with using the GTP protocol. ...
old/tournament/player.py
import re import shlex from subprocess import PIPE, Popen, TimeoutExpired class PlayerException(Exception): pass class PlayerCmdException(PlayerException): pass class Player(object): """ Player is a simple interface to a game playing process which is communicated with using the GTP protocol. ...
0.563498
0.14253
import uuid import six from datetime import timedelta, datetime import json import adal import dateutil.parser import requests from Kqlmagic.my_aad_helper import _MyAadHelper, ConnKeysKCSB from Kqlmagic.kql_client import KqlQueryResponse, KqlError from Kqlmagic.constants import Constants, ConnStrKeys from Kqlmagic.v...
azure/Kqlmagic/kusto_client.py
import uuid import six from datetime import timedelta, datetime import json import adal import dateutil.parser import requests from Kqlmagic.my_aad_helper import _MyAadHelper, ConnKeysKCSB from Kqlmagic.kql_client import KqlQueryResponse, KqlError from Kqlmagic.constants import Constants, ConnStrKeys from Kqlmagic.v...
0.72331
0.145844
import requests, phue, time, asyncio, bottom, rgbxy from config import config, load from unpack import rfc2812_handler def get_ip(): print('Looking for the Hue Bridge') r = requests.get('https://discovery.meethue.com') if r.status_code == 200: data = r.json() if not data: return...
twitchhue/app.py
import requests, phue, time, asyncio, bottom, rgbxy from config import config, load from unpack import rfc2812_handler def get_ip(): print('Looking for the Hue Bridge') r = requests.get('https://discovery.meethue.com') if r.status_code == 200: data = r.json() if not data: return...
0.277473
0.101411
import logging from typing import Dict from inspect import iscoroutine from thrift.protocol.TBinaryProtocol import TBinaryProtocol from aiohttp.web import Application, Request, Response, run_app from aiohttp.web_exceptions import HTTPNotFound, HTTPInternalServerError from .platform.thrift import serialize, deseriali...
nexus/server.py
import logging from typing import Dict from inspect import iscoroutine from thrift.protocol.TBinaryProtocol import TBinaryProtocol from aiohttp.web import Application, Request, Response, run_app from aiohttp.web_exceptions import HTTPNotFound, HTTPInternalServerError from .platform.thrift import serialize, deseriali...
0.827026
0.05199
import unittest import time import json from decimal import Decimal import context from arithmetictrainer.core import get_number from arithmetictrainer.core import get_number_array from arithmetictrainer.core import Arithmetictrainer from arithmetictrainer.core import arithmetictrainerFromJson class GetNumberTest(u...
tests/test_core.py
import unittest import time import json from decimal import Decimal import context from arithmetictrainer.core import get_number from arithmetictrainer.core import get_number_array from arithmetictrainer.core import Arithmetictrainer from arithmetictrainer.core import arithmetictrainerFromJson class GetNumberTest(u...
0.457379
0.492554
from dotenv import load_dotenv # pip install python-dotenv from geopy import distance from googleplaces import GooglePlaces, types, lang import json import os import pgeocode import requests as req load_dotenv() GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY') google_places = GooglePlaces(GOOGLE_API_KEY) d...
Hospital_Finder_V1.py
from dotenv import load_dotenv # pip install python-dotenv from geopy import distance from googleplaces import GooglePlaces, types, lang import json import os import pgeocode import requests as req load_dotenv() GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY') google_places = GooglePlaces(GOOGLE_API_KEY) d...
0.480966
0.230833
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models import torchvision.ops as ops from models.resnet import resnet50_backbone from models.modules import Flatten, FeatureBranch, CNNEncoder, FeatureBranch2, CNNEncoderGroupNorm, CNNEncoderGroupNorm2, CNNEncoderGroupNo...
models/baseline.py
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models import torchvision.ops as ops from models.resnet import resnet50_backbone from models.modules import Flatten, FeatureBranch, CNNEncoder, FeatureBranch2, CNNEncoderGroupNorm, CNNEncoderGroupNorm2, CNNEncoderGroupNo...
0.956156
0.357848
from sklearn.metrics import classification_report, accuracy_score, precision_recall_fscore_support import math def eval_singlemodel(ReasonerObj,eval_d,method, K=1): if K==1: # eval top-1 of each ranking y_pred = ReasonerObj.predictions[:, 0, 0].astype('int').astype('str').tolist() y_true = ...
evalscript.py
from sklearn.metrics import classification_report, accuracy_score, precision_recall_fscore_support import math def eval_singlemodel(ReasonerObj,eval_d,method, K=1): if K==1: # eval top-1 of each ranking y_pred = ReasonerObj.predictions[:, 0, 0].astype('int').astype('str').tolist() y_true = ...
0.448426
0.297285
import functools import logging import numpy as np from django.conf import settings from django.db import models from django.utils import timezone logger = logging.getLogger(__name__) class AccessLogMixin(models.Model): """Base class which logs access of information.""" # The user which accessed the data. ...
server/auvsi_suas/models/access_log.py
import functools import logging import numpy as np from django.conf import settings from django.db import models from django.utils import timezone logger = logging.getLogger(__name__) class AccessLogMixin(models.Model): """Base class which logs access of information.""" # The user which accessed the data. ...
0.897201
0.315762
import torch import torch.nn as nn import pyro.distributions as dist from pyro.nn import PyroModule import tyxe def test_iid(): l = PyroModule[nn.Linear](3, 2, bias=False) prior = tyxe.priors.IIDPrior(dist.Normal(0, 1)) prior.apply_(l) p = l._pyro_samples["weight"] assert isinstance(p, dist.Ind...
tests/test_priors.py
import torch import torch.nn as nn import pyro.distributions as dist from pyro.nn import PyroModule import tyxe def test_iid(): l = PyroModule[nn.Linear](3, 2, bias=False) prior = tyxe.priors.IIDPrior(dist.Normal(0, 1)) prior.apply_(l) p = l._pyro_samples["weight"] assert isinstance(p, dist.Ind...
0.894099
0.685723
import csv ff_analytics_data = 'week_2_data/Sunday_Evening_Game/ffa_customrankings2018-2.csv' yahoo_analytics_data = 'week_2_data/Sunday_Evening_Game/Yahoo_DF_player_export.csv' positions_we_care_about = ['QB','TE','RB','WR','DST'] output_file_ffa = 'week_2_data/Sunday_Evening_Game/cleaned_ffa_customrankings2018-2.cs...
clean_ffa_data.py
import csv ff_analytics_data = 'week_2_data/Sunday_Evening_Game/ffa_customrankings2018-2.csv' yahoo_analytics_data = 'week_2_data/Sunday_Evening_Game/Yahoo_DF_player_export.csv' positions_we_care_about = ['QB','TE','RB','WR','DST'] output_file_ffa = 'week_2_data/Sunday_Evening_Game/cleaned_ffa_customrankings2018-2.cs...
0.080709
0.141875
import uuid from django.conf import settings from django.db import models from django.contrib.auth.models import User, AbstractUser from django.contrib.postgres.fields import ArrayField from django.utils.translation import gettext_lazy from django.dispatch import receiver from django.db.models.signals import pre_save f...
mysite/SocialApp/models.py
import uuid from django.conf import settings from django.db import models from django.contrib.auth.models import User, AbstractUser from django.contrib.postgres.fields import ArrayField from django.utils.translation import gettext_lazy from django.dispatch import receiver from django.db.models.signals import pre_save f...
0.560373
0.120775
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, BatchNormalization, Activation, add from tensorflow.keras.models import Model, model_from_json from tensorflow.keras.optimizers import Adam def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), activat...
archs/unet.py
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose, concatenate, BatchNormalization, Activation, add from tensorflow.keras.models import Model, model_from_json from tensorflow.keras.optimizers import Adam def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), activat...
0.929007
0.768972
from math import sqrt, pow from utils.nodefinder import node_finder import time # This is for simulating vehicle movement # Velocity in m/s CAR_VELOCITY = 13 # Whatever rate we choose TICK_RATE = 1 CONVERSION_FACTOR = 1.542 DISTANCE_PER_TICK = CAR_VELOCITY*CONVERSION_FACTOR/TICK_RATE RUNNING_STATE = False OUR_SMART_...
server/utils/simulator/car_mover.py
from math import sqrt, pow from utils.nodefinder import node_finder import time # This is for simulating vehicle movement # Velocity in m/s CAR_VELOCITY = 13 # Whatever rate we choose TICK_RATE = 1 CONVERSION_FACTOR = 1.542 DISTANCE_PER_TICK = CAR_VELOCITY*CONVERSION_FACTOR/TICK_RATE RUNNING_STATE = False OUR_SMART_...
0.359589
0.289475
AUTH_HEADER = { "X-RH-IDENTITY": "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "X2VudGl0bGVkIjp0cnVlfX19Cg==" } AUTH_HEADER_NO_ENTITLEMENTS = { "X-RH-IDENTITY": "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY> } AUTH_HE...
tests/fixtures.py
AUTH_HEADER = { "X-RH-IDENTITY": "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "X2VudGl0bGVkIjp0cnVlfX19Cg==" } AUTH_HEADER_NO_ENTITLEMENTS = { "X-RH-IDENTITY": "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY>" "<KEY> } AUTH_HE...
0.329715
0.248831
from .helpers import * import random #DIRT = load_image("assets"+os.sep+"img"+os.sep+"tiles"+os.sep+"dirt.png") #ROCK = load_image("assets"+os.sep+"img"+os.sep+"tiles"+os.sep+"rock.png") #GRASS = load_image("assets"+os.sep+"img"+os.sep+"tiles"+os.sep+"grass.png") #WATER = load_image("assets"+os.sep+"img"+os.sep+"tiles...
src/tile.py
from .helpers import * import random #DIRT = load_image("assets"+os.sep+"img"+os.sep+"tiles"+os.sep+"dirt.png") #ROCK = load_image("assets"+os.sep+"img"+os.sep+"tiles"+os.sep+"rock.png") #GRASS = load_image("assets"+os.sep+"img"+os.sep+"tiles"+os.sep+"grass.png") #WATER = load_image("assets"+os.sep+"img"+os.sep+"tiles...
0.085013
0.097993
def root(context, missing=missing, environment=environment): resolve = context.resolve_or_missing undefined = environment.undefined if 0: yield None l_0_adquery = resolve("adquery") l_0_entity_def_id = resolve("entity_def_id") l_0_prj_prefix = resolve("prj_prefix") l_0_verb_name = re...
sql_gen/test/playground/rewire_verb_compiled.py
def root(context, missing=missing, environment=environment): resolve = context.resolve_or_missing undefined = environment.undefined if 0: yield None l_0_adquery = resolve("adquery") l_0_entity_def_id = resolve("entity_def_id") l_0_prj_prefix = resolve("prj_prefix") l_0_verb_name = re...
0.171512
0.151372
import matplotlib.pyplot as plt ''' Takes a list of lists, representing a (n x m) grayscale image, and flips it over the vertical axis n := rows m := columns ''' def flipImage(image): start = 0 start = 0 end = len(image) - 1 # Run loop to switch image[start] and image[end] rows unt...
Handwritten Digit Classification/compare1And5.py
import matplotlib.pyplot as plt ''' Takes a list of lists, representing a (n x m) grayscale image, and flips it over the vertical axis n := rows m := columns ''' def flipImage(image): start = 0 start = 0 end = len(image) - 1 # Run loop to switch image[start] and image[end] rows unt...
0.579757
0.74382
from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given...
backend/authentication/models.py
from django.db import models from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import PermissionsMixin class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given...
0.372505
0.075756
import shapely.geometry import shapely.geos import esridump GEO_URLS = { 'tracts': { 2000: 'https://tigerweb.geo.census.gov/arcgis/rest/services/Census2020/tigerWMS_Census2000/MapServer/8', 2010: 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/14', ...
census_area/core.py
import shapely.geometry import shapely.geos import esridump GEO_URLS = { 'tracts': { 2000: 'https://tigerweb.geo.census.gov/arcgis/rest/services/Census2020/tigerWMS_Census2000/MapServer/8', 2010: 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/14', ...
0.560974
0.362631
from __future__ import annotations from typing import Dict, Optional, Union # noqa: F401 import datetime from pathlib import Path from os import environ import dataclasses import myfitnesspal from pprint import pprint from dotenv import load_dotenv import json import more_itertools as mit from typing_exte...
fp/fit_pal.py
from __future__ import annotations from typing import Dict, Optional, Union # noqa: F401 import datetime from pathlib import Path from os import environ import dataclasses import myfitnesspal from pprint import pprint from dotenv import load_dotenv import json import more_itertools as mit from typing_exte...
0.668664
0.110976
import cv2 import logging import pytesseract import math import random import numpy as np from PIL import Image, ImageDraw from hanashi.model.rectangle import Rectangle from hanashi.model.ufarray import UFarray from hanashi.model.quadtree import Quadtree from hanashi.model.contour_tree import Tree, Node logger = logg...
hanashi/processor/page_processor.py
import cv2 import logging import pytesseract import math import random import numpy as np from PIL import Image, ImageDraw from hanashi.model.rectangle import Rectangle from hanashi.model.ufarray import UFarray from hanashi.model.quadtree import Quadtree from hanashi.model.contour_tree import Tree, Node logger = logg...
0.625324
0.470189
import logging from pyhap.const import CATEGORY_ALARM_SYSTEM from pyhap.loader import get_loader from openpeerpower.components.alarm_control_panel import DOMAIN from openpeerpower.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, SUP...
openpeerpower/components/homekit/type_security_systems.py
import logging from pyhap.const import CATEGORY_ALARM_SYSTEM from pyhap.loader import get_loader from openpeerpower.components.alarm_control_panel import DOMAIN from openpeerpower.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, SUP...
0.536556
0.097262
from typing import Any, List import networkx as nx from interface import Interface, implements from .builders.graph_builders import GraphBuilderInterface, TextGCNGraphBuilder from .model.document import Document from .model.graph_matrix import GraphMatrix from .nlp.pieplines import ProcessingPipeline, ProcessingPipel...
gbtr/gbtr.py
from typing import Any, List import networkx as nx from interface import Interface, implements from .builders.graph_builders import GraphBuilderInterface, TextGCNGraphBuilder from .model.document import Document from .model.graph_matrix import GraphMatrix from .nlp.pieplines import ProcessingPipeline, ProcessingPipel...
0.830903
0.202522
from __future__ import division from pyomo.environ import (ConcreteModel, Constraint, NonNegativeReals, Objective, Param, RangeSet, Set, Suffix, Var, minimize) from pyomo.gdp import Disjunct, Disjunction def build_model(): """Build the model.""" m = Concr...
instances/heat_exchangers/yee_gdp.py
from __future__ import division from pyomo.environ import (ConcreteModel, Constraint, NonNegativeReals, Objective, Param, RangeSet, Set, Suffix, Var, minimize) from pyomo.gdp import Disjunct, Disjunction def build_model(): """Build the model.""" m = Concr...
0.652906
0.27814
from flask import Response, request, jsonify from flask_restful import Resource from models.media import Song, Podcast, Audiobook #models created in media.py from api.errors import invalid_request #handling 400 error """This class creates a dictionary to map the oaudiFileType with their respec...
api/mediafile.py
from flask import Response, request, jsonify from flask_restful import Resource from models.media import Song, Podcast, Audiobook #models created in media.py from api.errors import invalid_request #handling 400 error """This class creates a dictionary to map the oaudiFileType with their respec...
0.405096
0.085633
import logging # external packages # local imports from mountcontrol.connection import Connection from mountcontrol.convert import valueToFloat from mountcontrol.convert import valueToInt class Setting(object): """ The class Setting inherits all information and handling of setting attributes of the conn...
mw4/mountcontrol/setting.py
import logging # external packages # local imports from mountcontrol.connection import Connection from mountcontrol.convert import valueToFloat from mountcontrol.convert import valueToInt class Setting(object): """ The class Setting inherits all information and handling of setting attributes of the conn...
0.818084
0.344526
import os import random import phonenumbers as pn from flask import Flask, Response, request from authy.api import AuthyApiClient from twilio.rest import Client from twilio.twiml.messaging_response import MessagingResponse authy_api = AuthyApiClient(os.environ["PUSH_DEMO_AUTHY_API_KEY"]) TWILIO_NUMBER = os.environ["...
push.py
import os import random import phonenumbers as pn from flask import Flask, Response, request from authy.api import AuthyApiClient from twilio.rest import Client from twilio.twiml.messaging_response import MessagingResponse authy_api = AuthyApiClient(os.environ["PUSH_DEMO_AUTHY_API_KEY"]) TWILIO_NUMBER = os.environ["...
0.478041
0.08196
# Copyright 2019 <NAME> # Copyright 2020 <NAME> # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Subsampling layer definition.""" import numpy as np import torch from espnet.nets.pytorch_backend.transformer.embedding import PositionalEncoding def _context_concat(seq, context_size=0): """ seq is of...
espnet/nets/pytorch_backend/transformer/subsampling.py
# Copyright 2019 <NAME> # Copyright 2020 <NAME> # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Subsampling layer definition.""" import numpy as np import torch from espnet.nets.pytorch_backend.transformer.embedding import PositionalEncoding def _context_concat(seq, context_size=0): """ seq is of...
0.815049
0.488771
import zipfile import shutil import os import sys #源apk source_release_apk = 'app-google-release.apk' #app名称 app_name = 'app' # 空文件 便于写入此空文件到apk包中作为channel文件 src_empty_file = 'channel/czt.txt' # 创建一个空文件(不存在则创建) f = open(src_empty_file, 'w') f.close() # python3 : os.listdir()即可,这里使用兼容Python2的os.listdir('.') for file...
app/python/build.py
import zipfile import shutil import os import sys #源apk source_release_apk = 'app-google-release.apk' #app名称 app_name = 'app' # 空文件 便于写入此空文件到apk包中作为channel文件 src_empty_file = 'channel/czt.txt' # 创建一个空文件(不存在则创建) f = open(src_empty_file, 'w') f.close() # python3 : os.listdir()即可,这里使用兼容Python2的os.listdir('.') for file...
0.073775
0.04778
from unittest import TestCase from unittest.mock import patch, MagicMock, Mock from ait.commons.util.command.download import CmdDownload def mock_transfer(_, fs): for f in fs: f.successful = True f.complete = True class TestDownload(TestCase): def setUp(self) -> None: self.aws_mock ...
ait/commons/util/tests/command/test_download.py
from unittest import TestCase from unittest.mock import patch, MagicMock, Mock from ait.commons.util.command.download import CmdDownload def mock_transfer(_, fs): for f in fs: f.successful = True f.complete = True class TestDownload(TestCase): def setUp(self) -> None: self.aws_mock ...
0.72952
0.341445
from . import api from flask import jsonify,g from datetime import datetime from flask_restful import Resource, abort, reqparse, Api from app.models import db, URLMapping,Permission,User from .authentication import auth from utils import transform from app.decorators import confirmed_required @auth.login_required @con...
app/api/urlmap.py
from . import api from flask import jsonify,g from datetime import datetime from flask_restful import Resource, abort, reqparse, Api from app.models import db, URLMapping,Permission,User from .authentication import auth from utils import transform from app.decorators import confirmed_required @auth.login_required @con...
0.208139
0.054349
from mpu import MPU import math import time # variables rad2deg = 57.2957786 # device address device_address = 0X68 mpu6050 = MPU(device_address) mpu6050.initialize(gyro_config=int('00001000',2), smplrt_div_value = 1, general_config=int('00000110', 2), accelerometer_config=int('00011000',2)) #gyro related variables...
inclinometer_alpha.py
from mpu import MPU import math import time # variables rad2deg = 57.2957786 # device address device_address = 0X68 mpu6050 = MPU(device_address) mpu6050.initialize(gyro_config=int('00001000',2), smplrt_div_value = 1, general_config=int('00000110', 2), accelerometer_config=int('00011000',2)) #gyro related variables...
0.122714
0.165998
from datetime import datetime from flask_restplus import Resource, reqparse from flask import current_app from ...permit.models.permit import Permit from ..models.permit_amendment import PermitAmendment from ..models.permit_amendment_document import PermitAmendmentDocument from app.extensions import api from ....utils....
python-backend/app/api/permits/permit_amendment/resources/permit_amendment.py
from datetime import datetime from flask_restplus import Resource, reqparse from flask import current_app from ...permit.models.permit import Permit from ..models.permit_amendment import PermitAmendment from ..models.permit_amendment_document import PermitAmendmentDocument from app.extensions import api from ....utils....
0.469763
0.082623
# modified script based on https://github.com/rmchurch/synthetic_blobs print('executing xgc blob synthesizer...') import os import h5py import numpy as np from scipy.integrate import odeint from scipy.interpolate import LinearNDInterpolator import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from ...
tests/synthesize_xgc_data.py
# modified script based on https://github.com/rmchurch/synthetic_blobs print('executing xgc blob synthesizer...') import os import h5py import numpy as np from scipy.integrate import odeint from scipy.interpolate import LinearNDInterpolator import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from ...
0.482429
0.568775
#!/usr/bin/env python # coding: utf-8 # In[51]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from scipy.stats import stats import matplotlib.backends.backend_pdf import math import random from matplotlib import pyplot as pl...
build/time-series_analysis.py
#!/usr/bin/env python # coding: utf-8 # In[51]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from scipy.stats import stats import matplotlib.backends.backend_pdf import math import random from matplotlib import pyplot as pl...
0.257018
0.184473
from django.contrib.auth.models import User from django.test import TestCase, Client from django.urls import reverse from django.utils import timezone from oauth.models import UserProfile class KonnektURLsTestCase(TestCase): @classmethod def setUp(cls): cls.client = Client() cls.user = User.ob...
src/konnekt/tests.py
from django.contrib.auth.models import User from django.test import TestCase, Client from django.urls import reverse from django.utils import timezone from oauth.models import UserProfile class KonnektURLsTestCase(TestCase): @classmethod def setUp(cls): cls.client = Client() cls.user = User.ob...
0.516839
0.273065
import numpy from .dc_motor import * class LineFollowerBot: def __init__(self, pb_client, model_file_name, config, starting_position): self.pb_client = pb_client orientation = self._to_quaternion(starting_position[1][0], 0.0, 0.0) self.bot_model = self.pb_client.loadURDF(model_file_n...
src/gym-line_follower/gym_line_follower/envs/LineFollowerBot.py
import numpy from .dc_motor import * class LineFollowerBot: def __init__(self, pb_client, model_file_name, config, starting_position): self.pb_client = pb_client orientation = self._to_quaternion(starting_position[1][0], 0.0, 0.0) self.bot_model = self.pb_client.loadURDF(model_file_n...
0.628635
0.263676
import logging import requests import pytest from app.auth import Authentication, _read_auth_info_from_file, _AuthInfo class MockedResponse: status_code = 600 def __repr__(self): return '<Response [%s]>' % self.status_code @pytest.fixture def auth_service(): yield Authentication() @pyte...
app/__tests__/test_auth.py
import logging import requests import pytest from app.auth import Authentication, _read_auth_info_from_file, _AuthInfo class MockedResponse: status_code = 600 def __repr__(self): return '<Response [%s]>' % self.status_code @pytest.fixture def auth_service(): yield Authentication() @pyte...
0.472197
0.216198
def test_login_process(test_client, login): """ Тест процесса авторизации: должен быть редирект на Index page, категория алерта - success """ response = login assert response.status_code == 200 assert b'Index page' in response.data assert b'success' in response.data def test_login_inva...
webapp/tests/test_login_register.py
def test_login_process(test_client, login): """ Тест процесса авторизации: должен быть редирект на Index page, категория алерта - success """ response = login assert response.status_code == 200 assert b'Index page' in response.data assert b'success' in response.data def test_login_inva...
0.351534
0.572902
import string import numpy as np import tensorflow as tf from official.nlp.modeling import layers _CHR_IDX = string.ascii_lowercase # This function is directly copied from the tf.keras.layers.MultiHeadAttention # implementation. def _build_attention_equation(rank, attn_axes): """Builds einsum equations for the a...
official/projects/edgetpu/nlp/modeling/edgetpu_layers.py
import string import numpy as np import tensorflow as tf from official.nlp.modeling import layers _CHR_IDX = string.ascii_lowercase # This function is directly copied from the tf.keras.layers.MultiHeadAttention # implementation. def _build_attention_equation(rank, attn_axes): """Builds einsum equations for the a...
0.941122
0.588475
import warnings import pandas as pd import numpy as np import matplotlib.pyplot as plt from gramdp_count import gramdp_count from gramdp_mean import gramdp_mean from gramdp_sum import gramdp_sum from gramdp_var import gramdp_var import matplotlib.gridspec as gs from matplotlib.lines import Line2D ''' query : string :...
GRAM_DP/gramdp_Analysis.py
import warnings import pandas as pd import numpy as np import matplotlib.pyplot as plt from gramdp_count import gramdp_count from gramdp_mean import gramdp_mean from gramdp_sum import gramdp_sum from gramdp_var import gramdp_var import matplotlib.gridspec as gs from matplotlib.lines import Line2D ''' query : string :...
0.318167
0.258985
# Author(s): <NAME> (hychen) <<EMAIL>> # 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 use, copy, modify, merge, publish, d...
test/test_cmdlib.py
# Author(s): <NAME> (hychen) <<EMAIL>> # 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 use, copy, modify, merge, publish, d...
0.55929
0.336168
# Main python libraries import sys import os # PIP3 imports try: import yaml from sqlalchemy import create_engine import pymysql except ImportError: import pip _PACKAGES = ['PyYAML', 'sqlalchemy', 'pymysql'] for _PACKAGE in _PACKAGES: pip.main(['install', '--user', _PACKAGE]) print(...
maintenance/database.py
# Main python libraries import sys import os # PIP3 imports try: import yaml from sqlalchemy import create_engine import pymysql except ImportError: import pip _PACKAGES = ['PyYAML', 'sqlalchemy', 'pymysql'] for _PACKAGE in _PACKAGES: pip.main(['install', '--user', _PACKAGE]) print(...
0.492432
0.070081
from datetime import timedelta, datetime import lcoreapi from django.conf import settings import logging cluster_messages = settings.LAMBDAINST_CLUSTER_MESSAGES lcore_settings = settings.LCORE LCORE_BASE_URL = lcore_settings.get('BASE_URL') LCORE_API_KEY = lcore_settings['API_KEY'] LCORE_API_SECRET = lcore_settings[...
lambdainst/core.py
from datetime import timedelta, datetime import lcoreapi from django.conf import settings import logging cluster_messages = settings.LAMBDAINST_CLUSTER_MESSAGES lcore_settings = settings.LCORE LCORE_BASE_URL = lcore_settings.get('BASE_URL') LCORE_API_KEY = lcore_settings['API_KEY'] LCORE_API_SECRET = lcore_settings[...
0.532182
0.090856
import simplejson as json from alipay.aop.api.constant.ParamConstants import * class PointTransInfo(object): def __init__(self): self._op_time = None self._point = None self._remark = None self._trans_no = None self._trans_type = None @property def op_time(self):...
alipay/aop/api/domain/PointTransInfo.py
import simplejson as json from alipay.aop.api.constant.ParamConstants import * class PointTransInfo(object): def __init__(self): self._op_time = None self._point = None self._remark = None self._trans_no = None self._trans_type = None @property def op_time(self):...
0.52683
0.176033
import os import time data_dir = "ic-data//extra" label_file = 'ic-data//extra.label' write_label = open(label_file, 'w+') def file_list(data_dir): filenames = [] for root, dirs, files in os.walk(data_dir): for file in files: if os.path.splitext(file)[1] == '.jpg': filename...
extra_label.py
import os import time data_dir = "ic-data//extra" label_file = 'ic-data//extra.label' write_label = open(label_file, 'w+') def file_list(data_dir): filenames = [] for root, dirs, files in os.walk(data_dir): for file in files: if os.path.splitext(file)[1] == '.jpg': filename...
0.094463
0.054727
import numpy as np import tensorflow as tf from .nes import NesModel tf.compat.v1.disable_v2_behavior() class NesRbModel(NesModel): """ Use forwardpass to determine random bases coordinates. There is the subtle difference with standard NES in that all offspring are evaluated on the same mini-batch ...
models/rbd_nes.py
import numpy as np import tensorflow as tf from .nes import NesModel tf.compat.v1.disable_v2_behavior() class NesRbModel(NesModel): """ Use forwardpass to determine random bases coordinates. There is the subtle difference with standard NES in that all offspring are evaluated on the same mini-batch ...
0.882896
0.332161
import tornado.httpserver import tornado.web from MysqlHelper import MysqlHelper from lib.CCPRestSDK import REST import json import os import glob import time from lib.sendMsg import Mail import random import hashlib import sys reload(sys) sys.setdefaultencoding( "utf-8" ) upload_path = os.path.join(os.path.dirname(_...
handlers/index.py
import tornado.httpserver import tornado.web from MysqlHelper import MysqlHelper from lib.CCPRestSDK import REST import json import os import glob import time from lib.sendMsg import Mail import random import hashlib import sys reload(sys) sys.setdefaultencoding( "utf-8" ) upload_path = os.path.join(os.path.dirname(_...
0.061565
0.070208
import enum from .available_cook_mode import AvailableCookMode from .erd_oven_cook_mode import ErdOvenCookMode @enum.unique class ErdAvailableCookMode(enum.Enum): """ Available cooking modes. In the XMPP API, they are represented as an index into an array of bytes and a bitmask. Thus these take the for...
gehomesdk/erd/values/oven/erd_available_cook_mode.py
import enum from .available_cook_mode import AvailableCookMode from .erd_oven_cook_mode import ErdOvenCookMode @enum.unique class ErdAvailableCookMode(enum.Enum): """ Available cooking modes. In the XMPP API, they are represented as an index into an array of bytes and a bitmask. Thus these take the for...
0.313945
0.223748
import json from abc import ABC from types import ModuleType from typing import Any, Dict, List, Optional, Tuple from sqlalchemy.engine import Connection, default from sqlalchemy.engine.url import URL from sqlalchemy.sql import compiler from sqlalchemy.types import DATE, TIMESTAMP, BigInteger, Boolean, Float, Integer,...
sqlalchemy_kusto/dialect_base.py
import json from abc import ABC from types import ModuleType from typing import Any, Dict, List, Optional, Tuple from sqlalchemy.engine import Connection, default from sqlalchemy.engine.url import URL from sqlalchemy.sql import compiler from sqlalchemy.types import DATE, TIMESTAMP, BigInteger, Boolean, Float, Integer,...
0.791096
0.231766
from functools import lru_cache from erica.erica_legacy.elster_xml import elster_xml_generator from erica.erica_legacy.elster_xml.xml_parsing.erica_xml_parsing import remove_declaration_and_namespace from erica.erica_legacy.pyeric.pyeric_controller import PermitListingPyericProcessController SPECIAL_TESTMERKER_IDNR =...
erica/erica_legacy/pyeric/check_elster_request_id.py
from functools import lru_cache from erica.erica_legacy.elster_xml import elster_xml_generator from erica.erica_legacy.elster_xml.xml_parsing.erica_xml_parsing import remove_declaration_and_namespace from erica.erica_legacy.pyeric.pyeric_controller import PermitListingPyericProcessController SPECIAL_TESTMERKER_IDNR =...
0.304248
0.103115
from netforce.model import Model, fields, get_model import time class Project(Model): _name = "project" _string = "Project" _audit_log = True _fields = { "name": fields.Char("Project Name", required=True, search=True), "number": fields.Char("Project Number", search=True), "con...
netforce_service/netforce_service/models/project.py
from netforce.model import Model, fields, get_model import time class Project(Model): _name = "project" _string = "Project" _audit_log = True _fields = { "name": fields.Char("Project Name", required=True, search=True), "number": fields.Char("Project Number", search=True), "con...
0.546254
0.307085
from datetime import datetime from json import loads from typing import List import requests as requests from interrail.data import StopLocation, Trip INTERRAIL_API_URI = "https://api.eurail.com" LANG = "en" def get_stop_locations(query: str) -> List[StopLocation]: """ Retrieves a list of StopLocations ma...
interrail/api.py
from datetime import datetime from json import loads from typing import List import requests as requests from interrail.data import StopLocation, Trip INTERRAIL_API_URI = "https://api.eurail.com" LANG = "en" def get_stop_locations(query: str) -> List[StopLocation]: """ Retrieves a list of StopLocations ma...
0.882833
0.342558
from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer from django.contrib.auth.models import User from django.core import serializers from django.utils.html import escape from chatchannels.models import ChatChannel, ChatMessage, chat_message_serialize class ChatChannelCon...
chatchannels/consumers.py
from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer from django.contrib.auth.models import User from django.core import serializers from django.utils.html import escape from chatchannels.models import ChatChannel, ChatMessage, chat_message_serialize class ChatChannelCon...
0.540681
0.074635
import sys import json import argparse import pytorch_pretrained_bert sys.path.append('.') from scripts.data_convert.text_proc import SpacyTextParser from scripts.data_convert.convert_common import STOPWORD_FILE, BERT_TOK_OPT_HELP, BERT_TOK_OPT, \ FileWrapper, read_stop_words, add_retokenized_field from scripts.c...
scripts/data_convert/msmarco/convert_queries.py
import sys import json import argparse import pytorch_pretrained_bert sys.path.append('.') from scripts.data_convert.text_proc import SpacyTextParser from scripts.data_convert.convert_common import STOPWORD_FILE, BERT_TOK_OPT_HELP, BERT_TOK_OPT, \ FileWrapper, read_stop_words, add_retokenized_field from scripts.c...
0.219923
0.077239
"""Test BIDS meta data parser """ from os.path import join as opj from simplejson import dumps from datalad.distribution.dataset import Dataset from datalad.metadata.parsers.datacite import MetadataParser from nose.tools import assert_true, assert_false, assert_equal from datalad.tests.utils import with_tree, with_tem...
datalad/metadata/parsers/tests/test_datacite_xml.py
"""Test BIDS meta data parser """ from os.path import join as opj from simplejson import dumps from datalad.distribution.dataset import Dataset from datalad.metadata.parsers.datacite import MetadataParser from nose.tools import assert_true, assert_false, assert_equal from datalad.tests.utils import with_tree, with_tem...
0.5144
0.460228
import unittest from problem_2 import find_files class Test_FindFiles(unittest.TestCase): def test_should_return_empty_list_when_path_given(self): """ Test find_files() should return an empty list when no path is given. """ self.assertListEqual([], find_files('', '')) sel...
tests_2.py
import unittest from problem_2 import find_files class Test_FindFiles(unittest.TestCase): def test_should_return_empty_list_when_path_given(self): """ Test find_files() should return an empty list when no path is given. """ self.assertListEqual([], find_files('', '')) sel...
0.659953
0.709651