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 ctypes, ctypes.util from OpenGL.platform import baseplatform, ctypesloader class EGLPlatform( baseplatform.BasePlatform ): """EGL platform for opengl-es only platforms""" @baseplatform.lazy_property def GLES1(self): try: return ctypesloader.loadLibrary( ctypes.cdl...
env/Lib/site-packages/OpenGL/platform/egl.py
import ctypes, ctypes.util from OpenGL.platform import baseplatform, ctypesloader class EGLPlatform( baseplatform.BasePlatform ): """EGL platform for opengl-es only platforms""" @baseplatform.lazy_property def GLES1(self): try: return ctypesloader.loadLibrary( ctypes.cdl...
0.166947
0.087408
from typing import Dict, Optional, Tuple, Union import torch from torch.distributions import Bernoulli, Beta, Uniform from kornia.augmentation.random_generator._2d.probability import random_prob_generator from kornia.augmentation.random_generator.base import RandomGeneratorBase from kornia.augmentation.utils import (...
kornia/augmentation/random_generator/_2d/cutmix.py
from typing import Dict, Optional, Tuple, Union import torch from torch.distributions import Bernoulli, Beta, Uniform from kornia.augmentation.random_generator._2d.probability import random_prob_generator from kornia.augmentation.random_generator.base import RandomGeneratorBase from kornia.augmentation.utils import (...
0.971293
0.534916
import numpy as np __all__ = ['MolFiniteDifference'] class MolFiniteDifference: """Helper to calculate derivatives of some value as a function of Cartesian displacements in a molecule.""" weights_der1 = {'3': np.array([-1 / 2, 0, 1 / 2]), '5': np.array([1 / 12, -2 / 3, 0, 2 / 3, -1 / 12])...
pyvibdmc/simulation_utilities/initial_conditioner/finite_difference.py
import numpy as np __all__ = ['MolFiniteDifference'] class MolFiniteDifference: """Helper to calculate derivatives of some value as a function of Cartesian displacements in a molecule.""" weights_der1 = {'3': np.array([-1 / 2, 0, 1 / 2]), '5': np.array([1 / 12, -2 / 3, 0, 2 / 3, -1 / 12])...
0.879742
0.76882
load("//tools:defaults.bzl", "rollup_bundle", "ts_library") load("@npm_bazel_karma//:index.bzl", "karma_web_test_suite") def karma_test_prepare(name, env_srcs, env_deps, env_entry_point, test_srcs, test_deps, test_entry_point): ts_library( name = name + "_env", testonly = True, srcs = env_s...
packages/zone.js/test/karma_test.bzl
load("//tools:defaults.bzl", "rollup_bundle", "ts_library") load("@npm_bazel_karma//:index.bzl", "karma_web_test_suite") def karma_test_prepare(name, env_srcs, env_deps, env_entry_point, test_srcs, test_deps, test_entry_point): ts_library( name = name + "_env", testonly = True, srcs = env_s...
0.251096
0.19619
import unittest from pygorithm.math import ( lcm, lcm_using_gcd, sieve_of_eratosthenes, factorial, conversion, matrix_operations, ) class TestLCM(unittest.TestCase): def test_lcm(self): self.assertEqual(lcm.lcm([3, 12, 16]), 48) def test_lcm_using_gcd(self): self.asse...
WEEKS/CD_Sata-Structures/_RESOURCES/pygorithm/tests/test_math.py
import unittest from pygorithm.math import ( lcm, lcm_using_gcd, sieve_of_eratosthenes, factorial, conversion, matrix_operations, ) class TestLCM(unittest.TestCase): def test_lcm(self): self.assertEqual(lcm.lcm([3, 12, 16]), 48) def test_lcm_using_gcd(self): self.asse...
0.58522
0.660487
import copy import json import click from maxrect import get_maximal_rectangle, rect2poly, get_intersection @click.command('max-rect') @click.argument('polygon', default='-', required=False, nargs=1) @click.option('--compare', is_flag=True, help='Leaves the original polygon in the feature collection') @click.pass_con...
maxrect/scripts/cli.py
import copy import json import click from maxrect import get_maximal_rectangle, rect2poly, get_intersection @click.command('max-rect') @click.argument('polygon', default='-', required=False, nargs=1) @click.option('--compare', is_flag=True, help='Leaves the original polygon in the feature collection') @click.pass_con...
0.372163
0.304688
from ostorlab.runtimes.local.models import models def testModels_whenDatabaseDoesNotExist_DatabaseAndScanCreated(mocker, db_engine_path): """Test when database does not exists, scan is populated in a newly created database.""" mocker.patch.object(models, 'ENGINE_URL', db_engine_path) models.Database().cre...
tests/runtimes/local/models/models_test.py
from ostorlab.runtimes.local.models import models def testModels_whenDatabaseDoesNotExist_DatabaseAndScanCreated(mocker, db_engine_path): """Test when database does not exists, scan is populated in a newly created database.""" mocker.patch.object(models, 'ENGINE_URL', db_engine_path) models.Database().cre...
0.704465
0.421254
import numpy as np from pyNastran.converters.stl.stl import read_stl from scipy.spatial import cKDTree import scipy.interpolate def projected_barycentric_coord(p, q, u, v): r""" points p, q vector u, v 3 *v / \ <----p q*----*u 1 2 u = p2 - p1 v = p3 - p1 ...
pyNastran/converters/stl/dev/stl_mesh.py
import numpy as np from pyNastran.converters.stl.stl import read_stl from scipy.spatial import cKDTree import scipy.interpolate def projected_barycentric_coord(p, q, u, v): r""" points p, q vector u, v 3 *v / \ <----p q*----*u 1 2 u = p2 - p1 v = p3 - p1 ...
0.611614
0.49823
from torch.testing._internal.common_utils import ( TestCase, run_tests, ) from datetime import timedelta, datetime import tempfile import time from torch.monitor import ( Aggregation, Event, log_event, register_event_handler, unregister_event_handler, Stat, TensorboardEventHandler, ) ...
test/test_monitor.py
from torch.testing._internal.common_utils import ( TestCase, run_tests, ) from datetime import timedelta, datetime import tempfile import time from torch.monitor import ( Aggregation, Event, log_event, register_event_handler, unregister_event_handler, Stat, TensorboardEventHandler, ) ...
0.698124
0.454714
import sys import tensorflow as tf sys.path.append("..") from model_utils import bi_rnn_encoder class Content_Enc_Model(object): """ content encoder model (pretrained as a character recognizer), input format-3 """ def __init__(self, init_lr = 0.001, batch_size=1024...
pretrain_content_enc/content_enc_model.py
import sys import tensorflow as tf sys.path.append("..") from model_utils import bi_rnn_encoder class Content_Enc_Model(object): """ content encoder model (pretrained as a character recognizer), input format-3 """ def __init__(self, init_lr = 0.001, batch_size=1024...
0.682679
0.206014
import psycopg2 import metautils from dbsettings import settings metautils.setsettings(settings) print '\nMarking all Bonn Google data as rejected (needs to be changed if Google searches are ever resumed!' cur = metautils.getDBCursor(settings, dictCursor = True) cur.execute('update data set accepted = %s where city...
utils/consistentDb.py
import psycopg2 import metautils from dbsettings import settings metautils.setsettings(settings) print '\nMarking all Bonn Google data as rejected (needs to be changed if Google searches are ever resumed!' cur = metautils.getDBCursor(settings, dictCursor = True) cur.execute('update data set accepted = %s where city...
0.128006
0.122392
import random from rest_framework import serializers from .payments import flutter_wave from django.contrib.auth.models import update_last_login from .models import Wallet, TransactionHistory from django.contrib.auth import get_user_model, authenticate from rest_framework_jwt.settings import api_settings from django.sh...
Wallets/serializers.py
import random from rest_framework import serializers from .payments import flutter_wave from django.contrib.auth.models import update_last_login from .models import Wallet, TransactionHistory from django.contrib.auth import get_user_model, authenticate from rest_framework_jwt.settings import api_settings from django.sh...
0.357231
0.190366
import torch import torch.nn as nn import torch.nn.functional as F class RCAN(nn.Module): """ RCAN: Image Super-Resolution Using Very Deep Residual Channel Attention Networks, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> """ def __init__(self, upscale_factor, input_channels, channel_mas...
SuperresolutionNetwork/models/rcan.py
import torch import torch.nn as nn import torch.nn.functional as F class RCAN(nn.Module): """ RCAN: Image Super-Resolution Using Very Deep Residual Channel Attention Networks, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> """ def __init__(self, upscale_factor, input_channels, channel_mas...
0.885322
0.497376
# pylint: disable=broad-except, bad-continuation, no-member import pathlib import json import os import tempfile import zipfile from integrationhelper import Validate, Logger from aiogithubapi import AIOGitHubException from .manifest import HacsManifest from ..helpers.misc import get_repository_name from ..hacsbase imp...
config/custom_components/hacs/repositories/repository.py
# pylint: disable=broad-except, bad-continuation, no-member import pathlib import json import os import tempfile import zipfile from integrationhelper import Validate, Logger from aiogithubapi import AIOGitHubException from .manifest import HacsManifest from ..helpers.misc import get_repository_name from ..hacsbase imp...
0.615319
0.091058
from datetime import timedelta from .securitas_direct_new_api.dataTypes import ( AirQuality, Sentinel, Service, ) from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.const import PERCENTAGE, TEMP_CELSIUS from . import CONF_ALARM, HUB as hub SCAN_INTERVAL = timed...
custom_components/securitas/sensor.py
from datetime import timedelta from .securitas_direct_new_api.dataTypes import ( AirQuality, Sentinel, Service, ) from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.const import PERCENTAGE, TEMP_CELSIUS from . import CONF_ALARM, HUB as hub SCAN_INTERVAL = timed...
0.866232
0.189427
"""Tests for tensorflow.kernels.edit_distance_op.""" import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.platform import test def Co...
tensorflow/python/kernel_tests/array_ops/edit_distance_op_test.py
"""Tests for tensorflow.kernels.edit_distance_op.""" import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import array_ops from tensorflow.python.platform import test def Co...
0.859914
0.736211
def test_map(): # apply an operation to each member of a sequence items = [1, 2, 3, 4, 5] squared = [] for x in items: squared.append(x ** 2) assert squared == [1, 4, 9, 16, 25] # ------------------------------------------------------------------------- # OR: items = [1, 2...
app/language_features/map_red_filt/ex.py
def test_map(): # apply an operation to each member of a sequence items = [1, 2, 3, 4, 5] squared = [] for x in items: squared.append(x ** 2) assert squared == [1, 4, 9, 16, 25] # ------------------------------------------------------------------------- # OR: items = [1, 2...
0.820793
0.938011
import torch import torch.nn as nn import torch.nn.functional as F from .blocks import * __all__ = [ "XceptionNet", ] class XceptionNet(nn.Module): def __init__( self, image_channels: int, num_classes: int, ): super().__init__() # Entry Flow self.conv1 = C...
models/Xception/models.py
import torch import torch.nn as nn import torch.nn.functional as F from .blocks import * __all__ = [ "XceptionNet", ] class XceptionNet(nn.Module): def __init__( self, image_channels: int, num_classes: int, ): super().__init__() # Entry Flow self.conv1 = C...
0.931463
0.343163
import autodisc as ad import goalrepresent as gr def get_system_config(): system_config = ad.systems.Lenia.default_config() system_config.version = "pytorch_fft" system_config.use_gpu = True return system_config def get_system_parameters(): system_parameters = ad.systems.Lenia.default_system_param...
experiments/IMGEP-HOLMES (SLP)/repetition_000009/experiment_config.py
import autodisc as ad import goalrepresent as gr def get_system_config(): system_config = ad.systems.Lenia.default_config() system_config.version = "pytorch_fft" system_config.use_gpu = True return system_config def get_system_parameters(): system_parameters = ad.systems.Lenia.default_system_param...
0.481941
0.216726
import pytest from django.contrib import auth from django.urls import reverse from webdev.users.models import User from pytest_django.asserts import assertContains # Registro @pytest.fixture def resposta_registro(client): resp = client.get(reverse('registro')) return resp def test_registro_status_code(respost...
webdev/users/tests/test_users_get.py
import pytest from django.contrib import auth from django.urls import reverse from webdev.users.models import User from pytest_django.asserts import assertContains # Registro @pytest.fixture def resposta_registro(client): resp = client.get(reverse('registro')) return resp def test_registro_status_code(respost...
0.31785
0.315551
from __future__ import annotations from ssl import create_default_context from typing import TYPE_CHECKING from urllib.parse import urlparse from weakref import WeakValueDictionary from anyio import BrokenResourceError, EndOfStream, Event, Lock, connect_tcp, sleep from anyio.streams.tls import TLSStream from certifi ...
discpyth/backends/_anyio/http.py
from __future__ import annotations from ssl import create_default_context from typing import TYPE_CHECKING from urllib.parse import urlparse from weakref import WeakValueDictionary from anyio import BrokenResourceError, EndOfStream, Event, Lock, connect_tcp, sleep from anyio.streams.tls import TLSStream from certifi ...
0.812682
0.084682
from object_library import all_lorentz, Lorentz from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot try: import form_factors as ForFac except ImportError: pass UUS1 = Lorentz(name = 'UUS1', spins = [ -1, -1, 1 ], structure = '1') UUV1 = Lorentz(nam...
examples/example4_systematics_DY/data/mg_processes/DY_sys/bin/internal/ufomodel/lorentz.py
from object_library import all_lorentz, Lorentz from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot try: import form_factors as ForFac except ImportError: pass UUS1 = Lorentz(name = 'UUS1', spins = [ -1, -1, 1 ], structure = '1') UUV1 = Lorentz(nam...
0.397588
0.462534
import os import sys import imp import os.path import linecache import re from . import callbacks, conf, log, registry installDir = os.path.dirname(sys.modules[__name__].__file__) _pluginsDir = os.path.join(installDir, 'plugins') class Deprecated(ImportError): pass def loadPluginModule(name, ignoreDeprecation=...
src/plugin.py
import os import sys import imp import os.path import linecache import re from . import callbacks, conf, log, registry installDir = os.path.dirname(sys.modules[__name__].__file__) _pluginsDir = os.path.join(installDir, 'plugins') class Deprecated(ImportError): pass def loadPluginModule(name, ignoreDeprecation=...
0.391871
0.066691
import os from copy import deepcopy import torch from torch import nn from torch.optim import SGD from torch.utils.data import DataLoader from torchvision import models, transforms from torchvision.datasets import CIFAR10 from pytorch_lightning import LightningModule, LightningDataModule, Trainer from pytorch_lightn...
pl_logger.py
import os from copy import deepcopy import torch from torch import nn from torch.optim import SGD from torch.utils.data import DataLoader from torchvision import models, transforms from torchvision.datasets import CIFAR10 from pytorch_lightning import LightningModule, LightningDataModule, Trainer from pytorch_lightn...
0.921794
0.503723
import asyncio from typing import Dict from pyzeebe import ( Job, ZeebeWorker, create_camunda_cloud_channel, create_insecure_channel, create_secure_channel, ) from pyzeebe.errors import BusinessError # Use decorators to add functionality before and after tasks. These will not fail the task async ...
examples/worker.py
import asyncio from typing import Dict from pyzeebe import ( Job, ZeebeWorker, create_camunda_cloud_channel, create_insecure_channel, create_secure_channel, ) from pyzeebe.errors import BusinessError # Use decorators to add functionality before and after tasks. These will not fail the task async ...
0.692642
0.139133
from django.conf import settings as django_settings from django.utils.translation import gettext_lazy as _ from django.test.signals import setting_changed from mapwidgets.constants import TIMEZONE_COORDINATES DEFAULTS = { "GooglePointFieldWidget": ( ("mapCenterLocationName", None), ("mapCenterLoc...
mapwidgets/settings.py
from django.conf import settings as django_settings from django.utils.translation import gettext_lazy as _ from django.test.signals import setting_changed from mapwidgets.constants import TIMEZONE_COORDINATES DEFAULTS = { "GooglePointFieldWidget": ( ("mapCenterLocationName", None), ("mapCenterLoc...
0.512449
0.167457
import dataclasses import functools import typing from datetime import datetime from time import sleep from openstack import connect import glci class OpenstackImageUploader: '''OpenstackImageUploader is a client to upload images to Openstack Glance.''' def __init__(self, environment: glci.model.OpenstackEn...
ci/glci/openstack_image.py
import dataclasses import functools import typing from datetime import datetime from time import sleep from openstack import connect import glci class OpenstackImageUploader: '''OpenstackImageUploader is a client to upload images to Openstack Glance.''' def __init__(self, environment: glci.model.OpenstackEn...
0.588416
0.135089
import os import sys import subprocess import re from setuptools import setup, find_packages, Extension # this should only be run with python3 import sys if sys.version_info[0] < 3: print('ERROR: must run with python3') sys.exit(1) tcf_root_dir = os.environ.get('TCF_HOME', '../..') version = subprocess.ch...
common/python/setup.py
import os import sys import subprocess import re from setuptools import setup, find_packages, Extension # this should only be run with python3 import sys if sys.version_info[0] < 3: print('ERROR: must run with python3') sys.exit(1) tcf_root_dir = os.environ.get('TCF_HOME', '../..') version = subprocess.ch...
0.213295
0.073397
from tempest.api.compute import base from tempest.lib.common.utils import data_utils from tempest.lib import decorators from tempest import test class SecurityGroupsTestAdminJSON(base.BaseV2ComputeAdminTest): @classmethod def setup_clients(cls): super(SecurityGroupsTestAdminJSON, cls).setup_clients(...
tempest/api/compute/admin/test_security_groups.py
from tempest.api.compute import base from tempest.lib.common.utils import data_utils from tempest.lib import decorators from tempest import test class SecurityGroupsTestAdminJSON(base.BaseV2ComputeAdminTest): @classmethod def setup_clients(cls): super(SecurityGroupsTestAdminJSON, cls).setup_clients(...
0.382603
0.167015
from mininet.net import Mininet from mininet.node import Switch, Host from mininet.log import setLogLevel, info, error, debug from mininet.moduledeps import pathCheck from sys import exit from time import sleep import os import tempfile import socket class P4Host(Host): def config(self, **params): r = sup...
SIGCOMM_2017/utils/mininet/p4_mininet.py
from mininet.net import Mininet from mininet.node import Switch, Host from mininet.log import setLogLevel, info, error, debug from mininet.moduledeps import pathCheck from sys import exit from time import sleep import os import tempfile import socket class P4Host(Host): def config(self, **params): r = sup...
0.367157
0.093719
from __future__ import unicode_literals from indico.core.settings import AttributeProxyProperty from indico.modules.events.models.reviews import ProposalMixin from indico.modules.events.papers.models.revisions import PaperRevisionState from indico.util.locators import locator_property from indico.util.string import r...
indico/modules/events/papers/models/papers.py
from __future__ import unicode_literals from indico.core.settings import AttributeProxyProperty from indico.modules.events.models.reviews import ProposalMixin from indico.modules.events.papers.models.revisions import PaperRevisionState from indico.util.locators import locator_property from indico.util.string import r...
0.836555
0.141281
class Value: def __init__(self, n): self.n = int(n) def __repr__(self): return str(self.n) class PC: def __init__(self): self._n = 0 self.allow_step = True @property def n(self): return self._n @n.setter def n(self, value): self.allow_st...
9/1.py
class Value: def __init__(self, n): self.n = int(n) def __repr__(self): return str(self.n) class PC: def __init__(self): self._n = 0 self.allow_step = True @property def n(self): return self._n @n.setter def n(self, value): self.allow_st...
0.50952
0.293867
import re from random import randrange from model.contact import Contact def test_random_contact_on_home_page(app): if app.contact.count_contact() == 0: contact = Contact(first_name="Trick", middle_name="", last_name="Truck", nickname="", title="", company_name="Big MO", ...
test/TestContact.py
import re from random import randrange from model.contact import Contact def test_random_contact_on_home_page(app): if app.contact.count_contact() == 0: contact = Contact(first_name="Trick", middle_name="", last_name="Truck", nickname="", title="", company_name="Big MO", ...
0.354433
0.245967
__metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ali_eni_facts short_description: Gather facts about ENI interfaces in Alibaba Cloud description: - Gather facts about EN...
lib/ansible/modules/cloud/alicloud/_ali_eni_facts.py
__metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ali_eni_facts short_description: Gather facts about ENI interfaces in Alibaba Cloud description: - Gather facts about EN...
0.724188
0.357624
from __future__ import absolute_import, unicode_literals import io import os import sys import warnings import functools from collections import defaultdict from functools import partial from functools import wraps from importlib import import_module from distutils.errors import DistutilsOptionError, DistutilsFileEr...
venv/lib/python3.8/site-packages/setuptools/config.py
from __future__ import absolute_import, unicode_literals import io import os import sys import warnings import functools from collections import defaultdict from functools import partial from functools import wraps from importlib import import_module from distutils.errors import DistutilsOptionError, DistutilsFileEr...
0.667473
0.119845
from bson import ObjectId from app.api.data.command.ExerciseEvaluationMongoCommandRepository import ExerciseEvaluationMongoCommandRepository from app.api.domain.models.ExerciseEvaluation import ExerciseEvaluation from app.api.domain.services.data.command.errors.CommandError import CommandError from tests.integration.P...
app/tests/integration/ExerciseEvaluationMongoCommandRepositoryIntegrationTest.py
from bson import ObjectId from app.api.data.command.ExerciseEvaluationMongoCommandRepository import ExerciseEvaluationMongoCommandRepository from app.api.domain.models.ExerciseEvaluation import ExerciseEvaluation from app.api.domain.services.data.command.errors.CommandError import CommandError from tests.integration.P...
0.614047
0.332581
import os import sys import MySQLdb from picker_tuner import picker_tuner from icecream import ic ic.configureOutput(prefix='debug| ') def main(): """Read parmas, choose in wich modules will be tuned, and run it """ # default parameters params = {'debug': False, 'max_picks': 50, 'n_trials': 100} ...
sc3autotuner.py
import os import sys import MySQLdb from picker_tuner import picker_tuner from icecream import ic ic.configureOutput(prefix='debug| ') def main(): """Read parmas, choose in wich modules will be tuned, and run it """ # default parameters params = {'debug': False, 'max_picks': 50, 'n_trials': 100} ...
0.192615
0.075585
import importlib import pathlib import os import os.path import sys import re import subprocess from dexbot.whiptail import get_whiptail from dexbot.strategies.base import StrategyBase import dexbot.helper STRATEGIES = [ {'tag': 'relative', 'class': 'dexbot.strategies.relative_orders', 'name': 'Relative...
dexbot/cli_conf.py
import importlib import pathlib import os import os.path import sys import re import subprocess from dexbot.whiptail import get_whiptail from dexbot.strategies.base import StrategyBase import dexbot.helper STRATEGIES = [ {'tag': 'relative', 'class': 'dexbot.strategies.relative_orders', 'name': 'Relative...
0.299105
0.085099
import io import json import contextlib try: from types import TypeType as type except ImportError: pass import semver from . import util class PackageStub(object): keys = ['name', 'version', 'description', 'license', 'compatibility'] def __init__(self, defaults=None): defaults = defaults o...
venv/Lib/site-packages/sputnik/package_stub.py
import io import json import contextlib try: from types import TypeType as type except ImportError: pass import semver from . import util class PackageStub(object): keys = ['name', 'version', 'description', 'license', 'compatibility'] def __init__(self, defaults=None): defaults = defaults o...
0.569254
0.093637
from contextlib import contextmanager import tensorflow as tf from ..tfutils.common import get_tf_version_tuple from ..compat import tfv1 from ..utils.develop import HIDE_DOC from .gradproc import FilterNoneGrad, GradientProcessor __all__ = ['apply_grad_processors', 'ProxyOptimizer', 'PostProcessOptimize...
tensorpack/tfutils/optimizer.py
from contextlib import contextmanager import tensorflow as tf from ..tfutils.common import get_tf_version_tuple from ..compat import tfv1 from ..utils.develop import HIDE_DOC from .gradproc import FilterNoneGrad, GradientProcessor __all__ = ['apply_grad_processors', 'ProxyOptimizer', 'PostProcessOptimize...
0.864725
0.280598
def __format(msg, pos): if len(msg) < 28: offset = 0 else: offset = len(msg) - 28 if pos - offset > 0: # at least 1 '-' before '$' return '{0:<28}{1:->{2}}${1:->{3}} <-ERROR'.format(msg, '-', pos - offset, 71 - pos) else: # start with '$' retu...
zPE/base/pgm/assist_err_code_rc.py
def __format(msg, pos): if len(msg) < 28: offset = 0 else: offset = len(msg) - 28 if pos - offset > 0: # at least 1 '-' before '$' return '{0:<28}{1:->{2}}${1:->{3}} <-ERROR'.format(msg, '-', pos - offset, 71 - pos) else: # start with '$' retu...
0.260954
0.201361
import joblib from ad_model.processing import PREPROCESS from sklearn.metrics import f1_score from sklearn.ensemble import IsolationForest from database import DATABASE, DUMMY import numpy as np class modelling(object): r""" The modelling class takes input as dataframe or array and train Isolation Forest model ...
ad/ad_train.py
import joblib from ad_model.processing import PREPROCESS from sklearn.metrics import f1_score from sklearn.ensemble import IsolationForest from database import DATABASE, DUMMY import numpy as np class modelling(object): r""" The modelling class takes input as dataframe or array and train Isolation Forest model ...
0.832509
0.495606
import os import sys sys.path.append(os.getcwd()) import torch import comet.data.conceptnet as cdata import comet.data.data as data from comet.utils.utils import DD from comet.utils import utils as utils from comet.data.utils import TextEncoder opt = DD() opt.dataset = "conceptnet" opt.exp = "generation" opt.data ...
scripts/data/make_conceptnet_data_loader.py
import os import sys sys.path.append(os.getcwd()) import torch import comet.data.conceptnet as cdata import comet.data.data as data from comet.utils.utils import DD from comet.utils import utils as utils from comet.data.utils import TextEncoder opt = DD() opt.dataset = "conceptnet" opt.exp = "generation" opt.data ...
0.454956
0.199152
# based on: # https://github.com/zhunzhong07/person-re-ranking __all__ = ['re_ranking'] import numpy as np def re_ranking(q_g_dist, q_q_dist, g_g_dist, k1: int = 20, k2: int = 6, lambda_value: float = 0.3): original_dist = np.concatenate( [np.concatenate([q_q_dist, q_g_dist], axis=1), np.conca...
fastreid/evaluation/rerank.py
# based on: # https://github.com/zhunzhong07/person-re-ranking __all__ = ['re_ranking'] import numpy as np def re_ranking(q_g_dist, q_q_dist, g_g_dist, k1: int = 20, k2: int = 6, lambda_value: float = 0.3): original_dist = np.concatenate( [np.concatenate([q_q_dist, q_g_dist], axis=1), np.conca...
0.496338
0.449513
from __future__ import absolute_import import json import warnings try: import yaml yaml_available = True except ImportError: yaml_available = False from albumentations import __version__ __all__ = ["to_dict", "from_dict", "save", "load"] SERIALIZABLE_REGISTRY = {} class SerializableMeta(type): ...
albumentations/core/serialization.py
from __future__ import absolute_import import json import warnings try: import yaml yaml_available = True except ImportError: yaml_available = False from albumentations import __version__ __all__ = ["to_dict", "from_dict", "save", "load"] SERIALIZABLE_REGISTRY = {} class SerializableMeta(type): ...
0.894784
0.289353
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from . import outputs __all__ = [ 'GetConnectedClusterResult', 'AwaitableGetConnectedClusterResult', 'get_connected_cluster', ] @pulumi.output_type class GetCo...
sdk/python/pulumi_azure_native/kubernetes/get_connected_cluster.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from . import outputs __all__ = [ 'GetConnectedClusterResult', 'AwaitableGetConnectedClusterResult', 'get_connected_cluster', ] @pulumi.output_type class GetCo...
0.860604
0.095645
from keras.layers import Dense, LSTM from keras.models import Sequential from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint from typing import List import matplotlib.pyplot as plt import shap import numpy as np import pandas as pd import config def create_model(learn_rate, activation, neuro...
lstm.py
from keras.layers import Dense, LSTM from keras.models import Sequential from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint from typing import List import matplotlib.pyplot as plt import shap import numpy as np import pandas as pd import config def create_model(learn_rate, activation, neuro...
0.914734
0.416441
from __future__ import division from __future__ import print_function import os import sys # dirty hack: include top level folder to path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) ) import itertools from torch_geometric.data import Data import ...
models/baselines.py
from __future__ import division from __future__ import print_function import os import sys # dirty hack: include top level folder to path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) ) import itertools from torch_geometric.data import Data import ...
0.673514
0.235988
from __future__ import division from collections import OrderedDict from functools import partial import empyrical as ep import numpy as np import pandas as pd import scipy as sp import scipy.stats as stats from sklearn import linear_model from .deprecate import deprecated from .interesting_periods import PERIODS fr...
pyfolio/timeseries.py
from __future__ import division from collections import OrderedDict from functools import partial import empyrical as ep import numpy as np import pandas as pd import scipy as sp import scipy.stats as stats from sklearn import linear_model from .deprecate import deprecated from .interesting_periods import PERIODS fr...
0.921988
0.536859
import datetime def get_spreadsheet_element(key="test_key", title="title"): d = datetime.datetime(2015, 7, 18) data = ( '<ns0:entry xmlns:ns0="http://www.w3.org/2005/Atom">' '<ns0:id>https://spreadsheets.google.com/feeds/spreadsheets/' 'private/full/{key}</ns0:id>' '<ns0:updat...
test/api_content.py
import datetime def get_spreadsheet_element(key="test_key", title="title"): d = datetime.datetime(2015, 7, 18) data = ( '<ns0:entry xmlns:ns0="http://www.w3.org/2005/Atom">' '<ns0:id>https://spreadsheets.google.com/feeds/spreadsheets/' 'private/full/{key}</ns0:id>' '<ns0:updat...
0.461988
0.23535
import logging from multiprocessing.pool import ThreadPool import click import dask import pandas as pd from dask.diagnostics import ProgressBar from kartothek.cli._cleanup import cleanup from kartothek.cli._copy import copy from kartothek.cli._delete import delete from kartothek.cli._index import index from kartothe...
kartothek/cli/__init__.py
import logging from multiprocessing.pool import ThreadPool import click import dask import pandas as pd from dask.diagnostics import ProgressBar from kartothek.cli._cleanup import cleanup from kartothek.cli._copy import copy from kartothek.cli._delete import delete from kartothek.cli._index import index from kartothe...
0.566978
0.138987
from shutil import rmtree from tempfile import mkdtemp from unittest import TestCase from opwen_email_server.services.auth import AzureAuth from opwen_email_server.services.auth import BasicAuth from opwen_email_server.services.storage import AzureTextStorage class BasicAuthTests(TestCase): def setUp(self): ...
tests/opwen_email_server/services/test_auth.py
from shutil import rmtree from tempfile import mkdtemp from unittest import TestCase from opwen_email_server.services.auth import AzureAuth from opwen_email_server.services.auth import BasicAuth from opwen_email_server.services.storage import AzureTextStorage class BasicAuthTests(TestCase): def setUp(self): ...
0.421195
0.314366
import logging from openpnm import topotools from openpnm.network import DelaunayVoronoiDual logger = logging.getLogger(__name__) __all__ = ['Delaunay'] class Delaunay(DelaunayVoronoiDual): r""" Random network formed by Delaunay tessellation of arbitrary base points Parameters ---------- points...
openpnm/network/_delaunay.py
import logging from openpnm import topotools from openpnm.network import DelaunayVoronoiDual logger = logging.getLogger(__name__) __all__ = ['Delaunay'] class Delaunay(DelaunayVoronoiDual): r""" Random network formed by Delaunay tessellation of arbitrary base points Parameters ---------- points...
0.919254
0.563138
from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from django.core.exceptions import FieldDoesNotExist from moneyed import CURRENCIES import common.models import re def validate_currency_code(code): """ Check that a gi...
InvenTree/InvenTree/validators.py
from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from django.core.exceptions import FieldDoesNotExist from moneyed import CURRENCIES import common.models import re def validate_currency_code(code): """ Check that a gi...
0.625667
0.321833
import tvm from tvm import tir from tvm.ir import Range from tvm.script import ty, from_source from tvm.ir.diagnostics import override_renderer @tvm.script.tir def matmul(a: ty.handle, b: ty.handle, c: ty.handle) -> None: A = tir.match_buffer(a, [128, 128]) B = tir.match_buffer(b, [128, 128]) C = tir.mat...
tests/python/unittest/test_tvmscript_complete.py
import tvm from tvm import tir from tvm.ir import Range from tvm.script import ty, from_source from tvm.ir.diagnostics import override_renderer @tvm.script.tir def matmul(a: ty.handle, b: ty.handle, c: ty.handle) -> None: A = tir.match_buffer(a, [128, 128]) B = tir.match_buffer(b, [128, 128]) C = tir.mat...
0.564579
0.457197
from pprint import pformat from six import iteritems import re class Layer(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, directive=None, arguments=None): """ Layer - a model defined in S...
v1alpha1/swagger_client/models/layer.py
from pprint import pformat from six import iteritems import re class Layer(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, directive=None, arguments=None): """ Layer - a model defined in S...
0.784236
0.299515
import re class Container: def __init__(self): self.mappings = {} self.registrations = {} self.strategies = [] @staticmethod def constructor_args(t): return t.__init__.__code__.co_varnames[1:] @staticmethod def type_to_parameter_name(t): return re.sub('[a-...
app/src/container.py
import re class Container: def __init__(self): self.mappings = {} self.registrations = {} self.strategies = [] @staticmethod def constructor_args(t): return t.__init__.__code__.co_varnames[1:] @staticmethod def type_to_parameter_name(t): return re.sub('[a-...
0.622804
0.336345
from abc import abstractmethod, ABCMeta import entrypoints import warnings from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE from mlflow.utils.uri import get_uri_scheme class UnsupportedModelRegistryStoreURIException(MlflowException): """Exception thro...
mlflow/tracking/registry.py
from abc import abstractmethod, ABCMeta import entrypoints import warnings from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE from mlflow.utils.uri import get_uri_scheme class UnsupportedModelRegistryStoreURIException(MlflowException): """Exception thro...
0.880771
0.216177
import re import json import ipaddress class IfConfig(object): """ ifconfig parser class """ def __init__(self, output): """ :param output: ifconfig text output """ self.interfaces = [] # loop over blocks for block in output.split('\n\n'): if block....
src/PI/ifconfig.py
import re import json import ipaddress class IfConfig(object): """ ifconfig parser class """ def __init__(self, output): """ :param output: ifconfig text output """ self.interfaces = [] # loop over blocks for block in output.split('\n\n'): if block....
0.430866
0.149687
class Student: def __init__(self, student_id, fname, lname, enroll_date): self.student_id = student_id self.fname = fname self.lname = lname self.enroll_date = enroll_date class Course: def __init__(self, course_id, title, cred_hr): self.course_id = course_id ...
Homework10Source (1).py
class Student: def __init__(self, student_id, fname, lname, enroll_date): self.student_id = student_id self.fname = fname self.lname = lname self.enroll_date = enroll_date class Course: def __init__(self, course_id, title, cred_hr): self.course_id = course_id ...
0.278159
0.175256
import json import os import torch class TimeDistributed(torch.nn.Module): """ Time distributed wrapper compatible with linear/dense pytorch layer modules""" def __init__(self, module, batch_first=True): super(TimeDistributed, self).__init__() self.module = module self.batch_first = ...
traja/models/utils.py
import json import os import torch class TimeDistributed(torch.nn.Module): """ Time distributed wrapper compatible with linear/dense pytorch layer modules""" def __init__(self, module, batch_first=True): super(TimeDistributed, self).__init__() self.module = module self.batch_first = ...
0.883538
0.407687
import csv, os, io, re from flask import Flask, render_template,escape, request, Response import pandas as pd import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as pl...
app.py
import csv, os, io, re from flask import Flask, render_template,escape, request, Response import pandas as pd import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as pl...
0.217836
0.081886
import math import re import numpy as np from pyfr.nputil import npeval, fuzzysort from pyfr.util import lazyprop, memoize class BaseElements(object): privarmap = None convarmap = None def __init__(self, basiscls, eles, cfg): self._be = None self.eles = eles self.cfg = cfg ...
pyfr/solvers/base/elements.py
import math import re import numpy as np from pyfr.nputil import npeval, fuzzysort from pyfr.util import lazyprop, memoize class BaseElements(object): privarmap = None convarmap = None def __init__(self, basiscls, eles, cfg): self._be = None self.eles = eles self.cfg = cfg ...
0.747524
0.392919
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, parse_iso8601, ) class ABCOTVSIE(InfoExtractor): IE_NAME = 'abcotvs' IE_DESC = 'ABC Owned Television Stations' _VALID_URL = r'https?://(?:abc(?:7(?:news|ny|chicago)?|11|13|30)|6...
youtube_dl/extractor/abcotvs.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, parse_iso8601, ) class ABCOTVSIE(InfoExtractor): IE_NAME = 'abcotvs' IE_DESC = 'ABC Owned Television Stations' _VALID_URL = r'https?://(?:abc(?:7(?:news|ny|chicago)?|11|13|30)|6...
0.548674
0.143487
from PyQt5 import QtCore, QtGui, QtWidgets import pandas as pd import numpy as np def window_execute(self, DB, TB): self.DB = DB self.TB = TB self.setObjectName("MainWindow") self.resize(500, 300) self.setMinimumSize(QtCore.QSize(500, 300)) self.setMaximumSize(QtCore.QSize(500, 300)...
NCW_win.py
from PyQt5 import QtCore, QtGui, QtWidgets import pandas as pd import numpy as np def window_execute(self, DB, TB): self.DB = DB self.TB = TB self.setObjectName("MainWindow") self.resize(500, 300) self.setMinimumSize(QtCore.QSize(500, 300)) self.setMaximumSize(QtCore.QSize(500, 300)...
0.322206
0.060004
from oslo_utils import uuidutils from nova import context from nova import exception from nova.objects import cell_mapping from nova.objects import instance_mapping from nova import test from nova.tests import fixtures from nova.tests import uuidsentinel sample_mapping = {'instance_uuid': '', 'cel...
nova/tests/functional/db/test_instance_mapping.py
from oslo_utils import uuidutils from nova import context from nova import exception from nova.objects import cell_mapping from nova.objects import instance_mapping from nova import test from nova.tests import fixtures from nova.tests import uuidsentinel sample_mapping = {'instance_uuid': '', 'cel...
0.577376
0.155335
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import paddle.fluid as fluid import distutils.util import numpy as np import six import argparse import functools import collections import datetime from collections import deque from paddle.fluid imp...
PaddleCV/rrpn/utility.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import paddle.fluid as fluid import distutils.util import numpy as np import six import argparse import functools import collections import datetime from collections import deque from paddle.fluid imp...
0.604049
0.146606
import datetime import sqlalchemy from keystone.common import driver_hints from keystone.common import sql from keystone.common import utils import keystone.conf from keystone import exception from keystone.i18n import _ from keystone.identity.backends import base from keystone.identity.backends import sql_model as ...
keystone/identity/backends/sql.py
import datetime import sqlalchemy from keystone.common import driver_hints from keystone.common import sql from keystone.common import utils import keystone.conf from keystone import exception from keystone.i18n import _ from keystone.identity.backends import base from keystone.identity.backends import sql_model as ...
0.536799
0.12749
import unittest import os from qubell.api.private.platform import QubellPlatform from qubell.api.private.manifest import Manifest from qubell.api.private.testing.setup_once import SetupOnce from qubell.api.private.service import COBALT_SECURE_STORE_TYPE, WORKFLOW_SERVICE_TYPE, SHARED_INSTANCE_CATALOG_TYPE from qubell...
integration_tests/base.py
import unittest import os from qubell.api.private.platform import QubellPlatform from qubell.api.private.manifest import Manifest from qubell.api.private.testing.setup_once import SetupOnce from qubell.api.private.service import COBALT_SECURE_STORE_TYPE, WORKFLOW_SERVICE_TYPE, SHARED_INSTANCE_CATALOG_TYPE from qubell...
0.253676
0.105257
import json from logging import ERROR import os from equit_ease.parser.parse import ChartParser import unittest def read_quote_fixture(fpath: str): fixture_file_path = os.path.join(os.path.dirname(__file__), fpath) with open(fixture_file_path, "r") as quote_fixture: data = json.loads(quote_fixture.re...
tests/test_chart_parser.py
import json from logging import ERROR import os from equit_ease.parser.parse import ChartParser import unittest def read_quote_fixture(fpath: str): fixture_file_path = os.path.join(os.path.dirname(__file__), fpath) with open(fixture_file_path, "r") as quote_fixture: data = json.loads(quote_fixture.re...
0.642657
0.441432
import json from flask_restful import Resource from bson.json_util import dumps from flask import request from mongoengine import DoesNotExist, ValidationError from bson import ObjectId from models.event import Event as Event_model from models.user import User as User_model from models.sport import Sport as Sport_model...
resources/events.py
import json from flask_restful import Resource from bson.json_util import dumps from flask import request from mongoengine import DoesNotExist, ValidationError from bson import ObjectId from models.event import Event as Event_model from models.user import User as User_model from models.sport import Sport as Sport_model...
0.110747
0.062674
import math import jittor as jt import jittor.nn as nn class WNLinear(nn.Module): def __init__(self, in_features, out_features, bias=True): super(WNLinear, self).__init__() self.in_features = in_features self.out_features = out_features self.weight_v = nn.init.invariant_uniform((ou...
network.py
import math import jittor as jt import jittor.nn as nn class WNLinear(nn.Module): def __init__(self, in_features, out_features, bias=True): super(WNLinear, self).__init__() self.in_features = in_features self.out_features = out_features self.weight_v = nn.init.invariant_uniform((ou...
0.901019
0.510435
import optparse import dns.resolver import console import urllib3 from socket import * from multiprocessing import Pool import re import time def portsscan(host,port): try: connect = socket(AF_INET,SOCK_STREAM) connect.settimeout(0.3) connect.connect((host,port)) banner = get...
lib/utils/portscan.py
import optparse import dns.resolver import console import urllib3 from socket import * from multiprocessing import Pool import re import time def portsscan(host,port): try: connect = socket(AF_INET,SOCK_STREAM) connect.settimeout(0.3) connect.connect((host,port)) banner = get...
0.182644
0.097648
"""Infer api.""" import time import numpy as np import mindspore.nn as nn import mindspore.common.dtype as mstype from mindspore.common.tensor import Tensor from mindspore.ops import operations as P from mindspore import context, Parameter from mindspore.train.model import Model from src.dataset import load_dataset ...
research/nlp/seq2seq/src/seq2seq_model/seq2seq_for_infer.py
"""Infer api.""" import time import numpy as np import mindspore.nn as nn import mindspore.common.dtype as mstype from mindspore.common.tensor import Tensor from mindspore.ops import operations as P from mindspore import context, Parameter from mindspore.train.model import Model from src.dataset import load_dataset ...
0.912126
0.514705
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.conf import settings from django.db import models class Migration(DataMigration): def forwards(self, orm): for currency in orm.Currency.objects.all(): orm['currency_history...
account_keeping/south_migrations/0005_move_rates_to_history_app.py
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.conf import settings from django.db import models class Migration(DataMigration): def forwards(self, orm): for currency in orm.Currency.objects.all(): orm['currency_history...
0.555315
0.145419
"""Utlity to convert FunctionDef to GraphDef and Graph.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import function_pb2 from tensorflow.core.framework import graph_pb2 from tensorflow.core.framework import tensor_shape_...
tensorflow/python/framework/function_def_to_graph.py
"""Utlity to convert FunctionDef to GraphDef and Graph.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import function_pb2 from tensorflow.core.framework import graph_pb2 from tensorflow.core.framework import tensor_shape_...
0.931843
0.429788
import os import time from subprocess import PIPE, CalledProcessError import yaml from conjureup.utils import run from .writer import fail, log, success JUJU_CONTROLLER = os.environ['JUJU_CONTROLLER'] JUJU_MODEL = os.environ['JUJU_MODEL'] JUJU_CM_STR = "{}:{}".format(JUJU_CONTROLLER, JUJU_MODEL) def status(): ...
conjureup/hooklib/juju.py
import os import time from subprocess import PIPE, CalledProcessError import yaml from conjureup.utils import run from .writer import fail, log, success JUJU_CONTROLLER = os.environ['JUJU_CONTROLLER'] JUJU_MODEL = os.environ['JUJU_MODEL'] JUJU_CM_STR = "{}:{}".format(JUJU_CONTROLLER, JUJU_MODEL) def status(): ...
0.338296
0.157525
from django.shortcuts import redirect, render from django.http import HttpResponse from .models import * import numpy as np import pickle as p #-------------------------------Home--------------------------------- def Index(request): recent_recommend = crop_recommed.objects.filter().order_by('-cr_id')[:4] ...
CropRecommendation/CropRecommendationApp/views.py
from django.shortcuts import redirect, render from django.http import HttpResponse from .models import * import numpy as np import pickle as p #-------------------------------Home--------------------------------- def Index(request): recent_recommend = crop_recommed.objects.filter().order_by('-cr_id')[:4] ...
0.435661
0.132599
import datetime from ..core.processor import ( processor, process_node, InstanceAttributeFactory, Storage, ) from ..core.utils import get_xml_root from .fritzbase import AbstractLibraryBase __all__ = ['FritzCall', 'Call'] ALL_CALL_TYPES = 0 RECEIVED_CALL_TYPE = 1 MISSED_CALL_TYPE = 2 OUT_CALL_TYP...
fritzconnection/lib/fritzcall.py
import datetime from ..core.processor import ( processor, process_node, InstanceAttributeFactory, Storage, ) from ..core.utils import get_xml_root from .fritzbase import AbstractLibraryBase __all__ = ['FritzCall', 'Call'] ALL_CALL_TYPES = 0 RECEIVED_CALL_TYPE = 1 MISSED_CALL_TYPE = 2 OUT_CALL_TYP...
0.700997
0.206834
from enum import IntEnum import numpy as np from numba import int64, float64, njit, objmode from numba.experimental import jitclass from tardis.montecarlo.montecarlo_numba import ( njit_dict_no_parallel, ) from tardis.montecarlo.montecarlo_numba.frame_transformations import ( get_doppler_factor, ) from tardis...
tardis/montecarlo/montecarlo_numba/r_packet.py
from enum import IntEnum import numpy as np from numba import int64, float64, njit, objmode from numba.experimental import jitclass from tardis.montecarlo.montecarlo_numba import ( njit_dict_no_parallel, ) from tardis.montecarlo.montecarlo_numba.frame_transformations import ( get_doppler_factor, ) from tardis...
0.609524
0.227995
import hmac import hashlib import base64 import time from Crypto.Cipher import AES import json #C:/Users/User/Anaconda3_7/python.exe macaroons_benchmark_37.py """This is a library file for creating macaroons. The functions defined are only those necessary to duplicate the results in Table 2 of Birgisson et al.'s "Maca...
Ali/macaroons_temp/macaroons_lib2_37.py
import hmac import hashlib import base64 import time from Crypto.Cipher import AES import json #C:/Users/User/Anaconda3_7/python.exe macaroons_benchmark_37.py """This is a library file for creating macaroons. The functions defined are only those necessary to duplicate the results in Table 2 of Birgisson et al.'s "Maca...
0.510985
0.313157
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities __all__ = ['UserArgs', 'User'] @pulumi.input_type class UserArgs: def __init__(__self__, *, user_name: pulumi.Input[str], active: Opt...
sdk/python/pulumi_databricks/user.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities __all__ = ['UserArgs', 'User'] @pulumi.input_type class UserArgs: def __init__(__self__, *, user_name: pulumi.Input[str], active: Opt...
0.825414
0.119588
import pandas as pd import json import requests from pathlib import Path from pr_reporter.models.pr_models import PrInfo from jinja2 import Template from tabulate import tabulate import yagmail import logging import os logger = logging.getLogger(__name__) class PR(object): API_ENDPOINT = "https://api.github.com/rep...
pr_reporter/pr.py
import pandas as pd import json import requests from pathlib import Path from pr_reporter.models.pr_models import PrInfo from jinja2 import Template from tabulate import tabulate import yagmail import logging import os logger = logging.getLogger(__name__) class PR(object): API_ENDPOINT = "https://api.github.com/rep...
0.250271
0.075721
import sys import os import numpy as np import matplotlib.pyplot as plt import pickle import glob from obspy import UTCDateTime, read, Trace, Stream from scipy import signal import pandas as pd from haversine import haversine sta_data = pd.read_excel("/sdd1/sta_list.xlsx", sheet_name="Data") sta_num = len(sta_data['l...
generate_data/24h_Data_2018.py
import sys import os import numpy as np import matplotlib.pyplot as plt import pickle import glob from obspy import UTCDateTime, read, Trace, Stream from scipy import signal import pandas as pd from haversine import haversine sta_data = pd.read_excel("/sdd1/sta_list.xlsx", sheet_name="Data") sta_num = len(sta_data['l...
0.201853
0.253234
# pylint: disable=wrong-import-order from test.common import payload, pub_keys, priv_keys, algs, generated_keys, \ clock_tick, clock_load from test import python_jwt as jwt from datetime import timedelta, datetime from pyvows import Vows, expect from jwcrypto.common import base64url_decode impor...
test/jwt_spec.py
# pylint: disable=wrong-import-order from test.common import payload, pub_keys, priv_keys, algs, generated_keys, \ clock_tick, clock_load from test import python_jwt as jwt from datetime import timedelta, datetime from pyvows import Vows, expect from jwcrypto.common import base64url_decode impor...
0.538741
0.258303
# stdlib imports import os.path import matplotlib import tempfile import shutil # third party imports from gmprocess.io.read import read_data from gmprocess.utils.plot import (plot_arias, plot_durations, plot_moveout, plot_regression) import pandas as pd from gmprocess.utils.test_uti...
tests/gmprocess/utils/plot_test.py
# stdlib imports import os.path import matplotlib import tempfile import shutil # third party imports from gmprocess.io.read import read_data from gmprocess.utils.plot import (plot_arias, plot_durations, plot_moveout, plot_regression) import pandas as pd from gmprocess.utils.test_uti...
0.482185
0.441131
from algs4.binarystdin import BinaryStdin from algs4.binarystdout import BinaryStdout from algs4.min_pq import MinPQ class Node: def __init__(self, ch, freq, left, right): self.ch = ch self.freq = freq self.left = left self.right = right def __str__(self): return "%s %...
algs4/huffman.py
from algs4.binarystdin import BinaryStdin from algs4.binarystdout import BinaryStdout from algs4.min_pq import MinPQ class Node: def __init__(self, ch, freq, left, right): self.ch = ch self.freq = freq self.left = left self.right = right def __str__(self): return "%s %...
0.439507
0.301195
import time from scipy import fftpack import book_format book_format.set_style() import kf_book.kf_internal as kf_internal from kf_book.kf_internal import DogSimulation from kf_book import book_plots as book_plots import numpy as np from matplotlib import pyplot import scipy.io import pandas as pd import pandas_datarea...
code/id26.py
import time from scipy import fftpack import book_format book_format.set_style() import kf_book.kf_internal as kf_internal from kf_book.kf_internal import DogSimulation from kf_book import book_plots as book_plots import numpy as np from matplotlib import pyplot import scipy.io import pandas as pd import pandas_datarea...
0.161353
0.386069
import numpy as np from ...reactions import GenericReactionFactory from ..topology_graph import Edge, NullOptimizer from .cof import Cof from .vertices import LinearVertex, NonLinearVertex class PeriodicHexagonal(Cof): """ Represents a periodic hexagonal COF topology graph. Unoptimzed construction ...
src/stk/molecular/topology_graphs/cof/periodic_hexagonal.py
import numpy as np from ...reactions import GenericReactionFactory from ..topology_graph import Edge, NullOptimizer from .cof import Cof from .vertices import LinearVertex, NonLinearVertex class PeriodicHexagonal(Cof): """ Represents a periodic hexagonal COF topology graph. Unoptimzed construction ...
0.885415
0.490785
import json import logging from datetime import datetime from typing import Any, Dict, List, Optional, Union from sqlalchemy.exc import SQLAlchemyError from superset import security_manager from superset.dao.base import BaseDAO from superset.dashboards.commands.exceptions import DashboardNotFoundError from superset.d...
superset/dashboards/dao.py
import json import logging from datetime import datetime from typing import Any, Dict, List, Optional, Union from sqlalchemy.exc import SQLAlchemyError from superset import security_manager from superset.dao.base import BaseDAO from superset.dashboards.commands.exceptions import DashboardNotFoundError from superset.d...
0.820541
0.23316
from ..models import Catalog, Question, QuestionSet, Section def test_catalog_str(db): instances = Catalog.objects.all() for instance in instances: assert str(instance) def test_catalog_clean(db): instances = Catalog.objects.all() for instance in instances: instance.clean() def tes...
rdmo/questions/tests/test_models.py
from ..models import Catalog, Question, QuestionSet, Section def test_catalog_str(db): instances = Catalog.objects.all() for instance in instances: assert str(instance) def test_catalog_clean(db): instances = Catalog.objects.all() for instance in instances: instance.clean() def tes...
0.564819
0.441191
from . import _tm_main def error_handler(error_code): if error_code in _tm_main.error_codes(): return _tm_main.error_echo(error_code) else: return 'Unknown Error. ERROR_CODE: %s' %error_code def assert_inputs(db_type,ref_path,target_path,output_path): error = False error = _tm_main.che...
taxamatcher/tm_handler.py
from . import _tm_main def error_handler(error_code): if error_code in _tm_main.error_codes(): return _tm_main.error_echo(error_code) else: return 'Unknown Error. ERROR_CODE: %s' %error_code def assert_inputs(db_type,ref_path,target_path,output_path): error = False error = _tm_main.che...
0.262653
0.102979
import json from navigation_analytics.navigation_data import * import os from datetime import datetime import pandas as pd import pickle import pytest def parse_dtypes(dtypes_dict: dict): result = dict() for col, col_type in dtypes_dict.items(): result[col] = eval(col_type) return result def loa...
tests/unit/test_navigation_data.py
import json from navigation_analytics.navigation_data import * import os from datetime import datetime import pandas as pd import pickle import pytest def parse_dtypes(dtypes_dict: dict): result = dict() for col, col_type in dtypes_dict.items(): result[col] = eval(col_type) return result def loa...
0.416678
0.271445
from __future__ import absolute_import, print_function, division __authors__ = ["<NAME>", "<NAME>"] __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" __date__ = "03/02/2019" __status__ = "production" __docformat__ = 'restructuredtext' __all__ = ["date", "version_info", "str...
version.py
from __future__ import absolute_import, print_function, division __authors__ = ["<NAME>", "<NAME>"] __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" __date__ = "03/02/2019" __status__ = "production" __docformat__ = 'restructuredtext' __all__ = ["date", "version_info", "str...
0.521471
0.098425
from verto.processors.GenericContainerBlockProcessor import GenericContainerBlockProcessor from verto.errors.InteractiveTextContainsInteractiveError import InteractiveTextContainsInteractiveError from verto.errors.InteractiveMissingTextError import InteractiveMissingTextError import re DEFAULT_THUMBNAIL = 'default' C...
verto/processors/InteractiveContainerBlockProcessor.py
from verto.processors.GenericContainerBlockProcessor import GenericContainerBlockProcessor from verto.errors.InteractiveTextContainsInteractiveError import InteractiveTextContainsInteractiveError from verto.errors.InteractiveMissingTextError import InteractiveMissingTextError import re DEFAULT_THUMBNAIL = 'default' C...
0.765243
0.226944
import logging from drf_yasg.utils import swagger_auto_schema from rest_framework import status from rest_framework.generics import CreateAPIView, DestroyAPIView from rest_framework.response import Response from safe_transaction_service.history.models import SafeContract from . import serializers from .models import...
safe_transaction_service/notifications/views.py
import logging from drf_yasg.utils import swagger_auto_schema from rest_framework import status from rest_framework.generics import CreateAPIView, DestroyAPIView from rest_framework.response import Response from safe_transaction_service.history.models import SafeContract from . import serializers from .models import...
0.769037
0.112065
import os, sys import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, RadioButtons import matplotlib.ticker import xspec # https://stackoverflow.com/questions/39960791/logarithmic-slider-with-matplotlib class Sliderlog(Slider): """Logarithmic slider. Takes in every metho...
main.py
import os, sys import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, RadioButtons import matplotlib.ticker import xspec # https://stackoverflow.com/questions/39960791/logarithmic-slider-with-matplotlib class Sliderlog(Slider): """Logarithmic slider. Takes in every metho...
0.409575
0.539165
import os import requests from requests.utils import requote_uri from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton API = "https://api.abirhasan.wtf/pypi?query=" START_TEXT = """ Hello {}, I am a pypi package search telegram bot. - Send a pypi package name. -...
main.py
import os import requests from requests.utils import requote_uri from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton API = "https://api.abirhasan.wtf/pypi?query=" START_TEXT = """ Hello {}, I am a pypi package search telegram bot. - Send a pypi package name. -...
0.402627
0.126299
import re import csv import time from random import choice from nltk.data import load from collections import defaultdict TWEET_FILE = 'data/tweets.csv' START_TOKEN = '<START>' END_TOKEN = '<END>' def sanitize_tweet_word(word): # Remove leading and trailing apostrophes word = word[1:] if (word[0] is '\'') else wo...
twitter/code/propaganda_generator.py
import re import csv import time from random import choice from nltk.data import load from collections import defaultdict TWEET_FILE = 'data/tweets.csv' START_TOKEN = '<START>' END_TOKEN = '<END>' def sanitize_tweet_word(word): # Remove leading and trailing apostrophes word = word[1:] if (word[0] is '\'') else wo...
0.407216
0.248375
from typing import Tuple, Union import numpy as np import torch from monai.transforms.croppad.array import SpatialCrop from monai.transforms.utils import generate_spatial_bounding_box from monai.utils import MetricReduction, optional_import binary_erosion, _ = optional_import("scipy.ndimage.morphology", name="binar...
monai/metrics/utils.py
from typing import Tuple, Union import numpy as np import torch from monai.transforms.croppad.array import SpatialCrop from monai.transforms.utils import generate_spatial_bounding_box from monai.utils import MetricReduction, optional_import binary_erosion, _ = optional_import("scipy.ndimage.morphology", name="binar...
0.975184
0.609611