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 jax import jax.numpy as jnp import chex from typing import Optional from functools import partial from .obs_norm import ObsNormalizer class BraxFitness(object): def __init__( self, env_name: str = "ant", num_env_steps: int = 1000, num_rollouts: int = 16, legacy_sprin...
evosax/problems/control_brax.py
import jax import jax.numpy as jnp import chex from typing import Optional from functools import partial from .obs_norm import ObsNormalizer class BraxFitness(object): def __init__( self, env_name: str = "ant", num_env_steps: int = 1000, num_rollouts: int = 16, legacy_sprin...
0.855293
0.398465
from __future__ import absolute_import, division, print_function, unicode_literals import struct import lldb # Various constants and masks used to decode the HermesValue. NUM_TAG_EXP_BITS = 17 NUM_DATA_BITS = 64 - NUM_TAG_EXP_BITS DATA_MASK = (1 << NUM_DATA_BITS) - 1 FIRST_TAG = 0xFFF88000 >> 15 LAST_TAG = 0xFFFF80...
lldb/HermesValueFormatter.py
from __future__ import absolute_import, division, print_function, unicode_literals import struct import lldb # Various constants and masks used to decode the HermesValue. NUM_TAG_EXP_BITS = 17 NUM_DATA_BITS = 64 - NUM_TAG_EXP_BITS DATA_MASK = (1 << NUM_DATA_BITS) - 1 FIRST_TAG = 0xFFF88000 >> 15 LAST_TAG = 0xFFFF80...
0.590189
0.140189
import re def rotate_list(steps, values): return values[-steps:] + values[:-steps] class Solver8: def __init__(self, grid_width, grid_height): self.grid_width = grid_width self.grid_height = grid_height self.pixels = [[False for i in range(self.grid_height)] for j in range(self.grid_w...
problems/8/Solver8.py
import re def rotate_list(steps, values): return values[-steps:] + values[:-steps] class Solver8: def __init__(self, grid_width, grid_height): self.grid_width = grid_width self.grid_height = grid_height self.pixels = [[False for i in range(self.grid_height)] for j in range(self.grid_w...
0.516108
0.363421
# 91 studies found. # Entries are (n, t) where n = Phylografter study id and t = tree id. # 'None' means not included in Asterales-only synthesis. # http://www.theoldnewinn.co.uk/village.htm asterales_studies = [ (9, 1), # Tank --> 1 Campanulidae (10, None), # Jansen (11, None), # Mag...
integration/asterales_studies.py
# 91 studies found. # Entries are (n, t) where n = Phylografter study id and t = tree id. # 'None' means not included in Asterales-only synthesis. # http://www.theoldnewinn.co.uk/village.htm asterales_studies = [ (9, 1), # Tank --> 1 Campanulidae (10, None), # Jansen (11, None), # Mag...
0.194865
0.222912
import numpy as np import numexpr as ne from astropy import constants as const class BlackBodySimpleSource(object): """ Simple packet source that generates packets for the Montecarlo part. This uses the algorithm described in Bjorkman & Wood 2001 (page 4) which references Carter & Cashwell 1975: ...
tardis/montecarlo/packet_source.py
import numpy as np import numexpr as ne from astropy import constants as const class BlackBodySimpleSource(object): """ Simple packet source that generates packets for the Montecarlo part. This uses the algorithm described in Bjorkman & Wood 2001 (page 4) which references Carter & Cashwell 1975: ...
0.832951
0.834002
from __future__ import annotations from passlib.hash import argon2 from pyramid.request import Request from pyramid_deferred_sqla import Base from pyramid_deferred_sqla import Model from pyramid_deferred_sqla import model_config from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Str...
src/conduit/auth/models.py
from __future__ import annotations from passlib.hash import argon2 from pyramid.request import Request from pyramid_deferred_sqla import Base from pyramid_deferred_sqla import Model from pyramid_deferred_sqla import model_config from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Str...
0.853699
0.187281
from auth.constants import FAILED, PROCESSING, SUCCEEDED from auth.core.ticket import TicketFactory from auth.core.ticket_notification import TicketNotice from auth.core.ticket_objects import BaseTicketSerializer from auth.core.ticket_serializer import TicketStateSerializer from auth.models import Ticket from auth.mode...
src/api/auth/views/ticket_views.py
from auth.constants import FAILED, PROCESSING, SUCCEEDED from auth.core.ticket import TicketFactory from auth.core.ticket_notification import TicketNotice from auth.core.ticket_objects import BaseTicketSerializer from auth.core.ticket_serializer import TicketStateSerializer from auth.models import Ticket from auth.mode...
0.427875
0.164483
class Customer: count_id = 0 # Initiator def __init__(self, firstname, lastname, username, email, gender, birth, password, phone_number, address, postal, payment_method, card_number, expiry, security_code, reset_pass): Customer.count_id += 1 self.__customer_id = Customer.count_id self._...
full_v3/Customer.py
class Customer: count_id = 0 # Initiator def __init__(self, firstname, lastname, username, email, gender, birth, password, phone_number, address, postal, payment_method, card_number, expiry, security_code, reset_pass): Customer.count_id += 1 self.__customer_id = Customer.count_id self._...
0.493409
0.117066
from __future__ import unicode_literals import json import time import django import django.utils.timezone as timezone from django.test import TestCase, TransactionTestCase from rest_framework import status import error.test.utils as error_test_utils import job.test.utils as job_test_utils import queue.test.utils as...
scale/queue/test/test_views.py
from __future__ import unicode_literals import json import time import django import django.utils.timezone as timezone from django.test import TestCase, TransactionTestCase from rest_framework import status import error.test.utils as error_test_utils import job.test.utils as job_test_utils import queue.test.utils as...
0.634543
0.286568
from os.path import join, normpath from pyutilib.misc import import_file from pysperf.model_library_tools import register_model from pyomo.common.fileutils import PYOMO_ROOT_DIR pyomo_gdp_examples_path = normpath(join(PYOMO_ROOT_DIR, 'examples', 'gdp')) def _build_from_gdp_examples(build_name, *path): model_...
pysperf/models/pyomo_examples.py
from os.path import join, normpath from pyutilib.misc import import_file from pysperf.model_library_tools import register_model from pyomo.common.fileutils import PYOMO_ROOT_DIR pyomo_gdp_examples_path = normpath(join(PYOMO_ROOT_DIR, 'examples', 'gdp')) def _build_from_gdp_examples(build_name, *path): model_...
0.459319
0.200538
# based on https://github.com/cair/pyTsetlinMachine/blob/dfaa7f36a5fa5cc852645277605358ae4d955898/examples/IMDbTextCategorizationDemo.py from scipy import sparse import numpy as np import keras from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from keras.datasets import imdb...
lib/examples/imdb-text-categorization/src/produce_dataset.py
# based on https://github.com/cair/pyTsetlinMachine/blob/dfaa7f36a5fa5cc852645277605358ae4d955898/examples/IMDbTextCategorizationDemo.py from scipy import sparse import numpy as np import keras from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from keras.datasets import imdb...
0.697094
0.514095
import pytest import time import subprocess from subprocess import run,Popen from seldon_utils import * from k8s_utils import * def wait_for_shutdown(deploymentName): ret = run("kubectl get deploy/"+deploymentName, shell=True) while ret.returncode == 0: time.sleep(1) ret = run("kubectl get depl...
testing/scripts/test_helm_charts_single_namespace.py
import pytest import time import subprocess from subprocess import run,Popen from seldon_utils import * from k8s_utils import * def wait_for_shutdown(deploymentName): ret = run("kubectl get deploy/"+deploymentName, shell=True) while ret.returncode == 0: time.sleep(1) ret = run("kubectl get depl...
0.245175
0.282046
import torch from npt.datasets.base import BaseDataset class CIFAR10Dataset(BaseDataset): def __init__(self, c): super().__init__( fixed_test_set_index=None) self.c = c def load(self): """ Classification dataset. Target in last column. 60 000 rows...
npt/datasets/cifar10.py
import torch from npt.datasets.base import BaseDataset class CIFAR10Dataset(BaseDataset): def __init__(self, c): super().__init__( fixed_test_set_index=None) self.c = c def load(self): """ Classification dataset. Target in last column. 60 000 rows...
0.690037
0.617152
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_countries.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
django_ecommerce-project/shop/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_countries.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
0.536556
0.160003
from __future__ import annotations from .geom import * import deepsvg.svglib.geom as geom import re import torch from typing import List, Union from xml.dom import minidom import math import shapely.geometry import numpy as np from .geom import union_bbox from .svg_command import SVGCommand, SVGCommandMove, SVGCommand...
deepsvg/svglib/svg_path.py
from __future__ import annotations from .geom import * import deepsvg.svglib.geom as geom import re import torch from typing import List, Union from xml.dom import minidom import math import shapely.geometry import numpy as np from .geom import union_bbox from .svg_command import SVGCommand, SVGCommandMove, SVGCommand...
0.690663
0.22762
import copy import logging import numpy as np import operator import torch import torch.utils.data import json from detectron2.utils.comm import get_world_size from detectron2.data import samplers from torch.utils.data.sampler import BatchSampler, Sampler from detectron2.data.common import DatasetFromList, MapDataset ...
projects/UniDet/unidet/data/custom_dataset_dataloader.py
import copy import logging import numpy as np import operator import torch import torch.utils.data import json from detectron2.utils.comm import get_world_size from detectron2.data import samplers from torch.utils.data.sampler import BatchSampler, Sampler from detectron2.data.common import DatasetFromList, MapDataset ...
0.535584
0.315894
from __future__ import absolute_import import unittest from datetime import datetime from pytz import UTC from bqdm.model.dataset import BigQueryAccessEntry, BigQueryDataset from bqdm.model.schema import BigQuerySchemaField from bqdm.model.table import BigQueryTable from bqdm.util import dump class TestUtil(unitte...
tests/test_util.py
from __future__ import absolute_import import unittest from datetime import datetime from pytz import UTC from bqdm.model.dataset import BigQueryAccessEntry, BigQueryDataset from bqdm.model.schema import BigQuerySchemaField from bqdm.model.table import BigQueryTable from bqdm.util import dump class TestUtil(unitte...
0.646125
0.272085
import logging log = logging.getLogger('moteConnector') log.setLevel(logging.ERROR) log.addHandler(logging.NullHandler()) import threading import socket import traceback import sys import binascii import openvisualizer.openvisualizer_utils as u from pydispatch import dispatcher from openvisualizer.eventBus impo...
software/openvisualizer/openvisualizer/moteConnector/moteConnector.py
import logging log = logging.getLogger('moteConnector') log.setLevel(logging.ERROR) log.addHandler(logging.NullHandler()) import threading import socket import traceback import sys import binascii import openvisualizer.openvisualizer_utils as u from pydispatch import dispatcher from openvisualizer.eventBus impo...
0.122484
0.098252
import random import discord import traceback from resources.config import ConfigLoader from resources.error_logger import ErrorLogging class JoinLeaveHandler: """ Functions for welcoming a user or sending a message if a user leaves """ def __init__(self, bot): self.bot = bot async d...
plugins/join_leave_handler.py
import random import discord import traceback from resources.config import ConfigLoader from resources.error_logger import ErrorLogging class JoinLeaveHandler: """ Functions for welcoming a user or sending a message if a user leaves """ def __init__(self, bot): self.bot = bot async d...
0.360264
0.11187
from __future__ import unicode_literals import django from django.test import TestCase from data.filter.filter import DataFilter from data.filter.exceptions import InvalidDataFilter from data.filter.json.filter_v6 import convert_filter_to_v6_json, DataFilterV6 class TestDataFilterV6(TestCase): def setUp(self):...
scale/data/test/filter/json/test_filter_v6.py
from __future__ import unicode_literals import django from django.test import TestCase from data.filter.filter import DataFilter from data.filter.exceptions import InvalidDataFilter from data.filter.json.filter_v6 import convert_filter_to_v6_json, DataFilterV6 class TestDataFilterV6(TestCase): def setUp(self):...
0.63409
0.589096
import re DELIMS = { 'section': '~', 'category': '`', 'keywords': '^', 'title': '@', 'body': '}' } def build_pattern(sections, start_token, end_token): # sections may not be in the correct order: fix it key_order = ['category', 'keywords', 'title', 'body'] sections = [section for sect...
keyword_decode.py
import re DELIMS = { 'section': '~', 'category': '`', 'keywords': '^', 'title': '@', 'body': '}' } def build_pattern(sections, start_token, end_token): # sections may not be in the correct order: fix it key_order = ['category', 'keywords', 'title', 'body'] sections = [section for sect...
0.472927
0.285764
import shutil import os import os.path import json import distutils.command.build_ext import subprocess import sys from setuptools import Extension, setup import platform import numpy try: import cython use_cython = True except ImportError: use_cython = False class ExtensionBuilder(distutils.command.bui...
setup.py
import shutil import os import os.path import json import distutils.command.build_ext import subprocess import sys from setuptools import Extension, setup import platform import numpy try: import cython use_cython = True except ImportError: use_cython = False class ExtensionBuilder(distutils.command.bui...
0.225758
0.058346
from __future__ import absolute_import from collections import defaultdict from flask_restful.reqparse import RequestParser from itertools import groupby from sqlalchemy.orm import contains_eager, joinedload, subqueryload_all from typing import List # NOQA from changes.api.base import APIView from changes.api.serial...
changes/api/build_details.py
from __future__ import absolute_import from collections import defaultdict from flask_restful.reqparse import RequestParser from itertools import groupby from sqlalchemy.orm import contains_eager, joinedload, subqueryload_all from typing import List # NOQA from changes.api.base import APIView from changes.api.serial...
0.771112
0.152347
import requests import requests_mock import tempfile import os from os import path from unittest import TestCase from vivotool.harvester.elements import Elements from vivotool.utils.file_utils import Utils from datetime import datetime, timedelta from unittest import mock class TestElements(TestCase): def setUp...
test/test_harvester.py
import requests import requests_mock import tempfile import os from os import path from unittest import TestCase from vivotool.harvester.elements import Elements from vivotool.utils.file_utils import Utils from datetime import datetime, timedelta from unittest import mock class TestElements(TestCase): def setUp...
0.540681
0.393735
import logging import datetime from schema import Schema, Optional from nni import ClassArgsValidator from nni.assessor import Assessor, AssessResult from nni.utils import extract_scalar_history from .model_factory import CurveModel logger = logging.getLogger('curvefitting_Assessor') class CurvefittingClassArgsVali...
nni/algorithms/hpo/curvefitting_assessor/curvefitting_assessor.py
import logging import datetime from schema import Schema, Optional from nni import ClassArgsValidator from nni.assessor import Assessor, AssessResult from nni.utils import extract_scalar_history from .model_factory import CurveModel logger = logging.getLogger('curvefitting_Assessor') class CurvefittingClassArgsVali...
0.920061
0.435061
import requests API_ROOT = 'http://api.nytimes.com/svc/search/v2/articlesearch.' API_SIGNUP_PAGE = 'http://developer.nytimes.com/docs/reference/keys' class NoAPIKeyException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class articleAPI(...
NYTimesArticleAPI/search_api.py
import requests API_ROOT = 'http://api.nytimes.com/svc/search/v2/articlesearch.' API_SIGNUP_PAGE = 'http://developer.nytimes.com/docs/reference/keys' class NoAPIKeyException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class articleAPI(...
0.68595
0.224406
import pygame width = 960 height = 540 fps = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) vec = pygame.Vector2 pygame.init() pygame.mixer.init() title = pygame.display.set_caption("ScrollLandia") screen = pygame.display.set_mode((width, heigh...
Game Files/MainGameFile.py
import pygame width = 960 height = 540 fps = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) vec = pygame.Vector2 pygame.init() pygame.mixer.init() title = pygame.display.set_caption("ScrollLandia") screen = pygame.display.set_mode((width, heigh...
0.32338
0.164014
from . import domainresource class ConceptMap(domainresource.DomainResource): """ A map from one set of concepts to one or more other concepts. A statement of relationships from one set of concepts to one or more other concepts - either concepts in code systems, or data element/data element ...
fhirclient/r4models/conceptmap.py
from . import domainresource class ConceptMap(domainresource.DomainResource): """ A map from one set of concepts to one or more other concepts. A statement of relationships from one set of concepts to one or more other concepts - either concepts in code systems, or data element/data element ...
0.828002
0.445771
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Admins', fields=[ ('window_username', models.CharField(db_column='WindowUsername', max_leng...
WebApps/FleetDataCollection/migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Admins', fields=[ ('window_username', models.CharField(db_column='WindowUsername', max_leng...
0.552057
0.15863
import pytest import os from profiler.adapters.aggregations_repository.local_aggregation_repository import ( LocalAggregationsRepository, ) from profiler.adapters.metrics_repository.local_metrics_repository import ( LocalMetricsRepository, ) from profiler.adapters.models_repository.local_model_reporsitory impo...
profiler/tests/conftest.py
import pytest import os from profiler.adapters.aggregations_repository.local_aggregation_repository import ( LocalAggregationsRepository, ) from profiler.adapters.metrics_repository.local_metrics_repository import ( LocalMetricsRepository, ) from profiler.adapters.models_repository.local_model_reporsitory impo...
0.499268
0.135175
import logging from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials log = logging.getLogger(__name__) DEFAULT_SCOPES = ['https://www.googleapis.com/auth/admin.directory.group' , 'https://www.googleapis.com/auth/admin.directory.group.member'] def _cre...
src/gsuitefy/gsuite.py
import logging from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials log = logging.getLogger(__name__) DEFAULT_SCOPES = ['https://www.googleapis.com/auth/admin.directory.group' , 'https://www.googleapis.com/auth/admin.directory.group.member'] def _cre...
0.725843
0.198375
# Disable protected access for testing. # pylint: disable=protected-access,no-member import copy import importlib from unittest import mock import pytest from sqlalchemy import schema as sql_schema from open_alchemy import exceptions from open_alchemy import model_factory from open_alchemy.facades import sqlalchemy ...
tests/open_alchemy/test_model_factory.py
# Disable protected access for testing. # pylint: disable=protected-access,no-member import copy import importlib from unittest import mock import pytest from sqlalchemy import schema as sql_schema from open_alchemy import exceptions from open_alchemy import model_factory from open_alchemy.facades import sqlalchemy ...
0.764979
0.426083
from __future__ import print_function import sys import os from JobInfo import * import subprocess from textwrap import dedent import time instructionFile = sys.argv[1] assert os.path.exists(instructionFile), '"%s" is not a valid instruction file.' % `instructionFile` # Initialize the JobInfo object, whi...
python/ChorusCustomActions/OpenInSameFrameByMacro.py
from __future__ import print_function import sys import os from JobInfo import * import subprocess from textwrap import dedent import time instructionFile = sys.argv[1] assert os.path.exists(instructionFile), '"%s" is not a valid instruction file.' % `instructionFile` # Initialize the JobInfo object, whi...
0.190197
0.062818
import numpy as np import os.path as op import pandas as pd import pytest import tempfile import torch import afqinsight as afqi from afqinsight.datasets import ( bundles2channels, load_afq_data, download_sarica, download_weston_havens, AFQDataset, ) data_path = op.join(afqi.__path__[0], "data") t...
afqinsight/tests/test_datasets.py
import numpy as np import os.path as op import pandas as pd import pytest import tempfile import torch import afqinsight as afqi from afqinsight.datasets import ( bundles2channels, load_afq_data, download_sarica, download_weston_havens, AFQDataset, ) data_path = op.join(afqi.__path__[0], "data") t...
0.652131
0.563138
from datetime import timedelta from airflow import DAG from airflow.operators.python_operator import PythonOperator from airflow.hooks.postgres_hook import PostgresHook from airflow.utils.dates import days_ago import pandas as pd import gcsfs from airflow.models import Variable pg_hook = PostgresHook("heroku_psql") d...
dags/assignment_processor/etl.py
from datetime import timedelta from airflow import DAG from airflow.operators.python_operator import PythonOperator from airflow.hooks.postgres_hook import PostgresHook from airflow.utils.dates import days_ago import pandas as pd import gcsfs from airflow.models import Variable pg_hook = PostgresHook("heroku_psql") d...
0.439747
0.215041
class Blob: """ Blob object """ def __init__(self, id=None, blob_status=None, content_type=None, created_at=None, last_read_access_ts=None, lifetime=None, name=None, public=None, ref_count=None, set_completed_at=None, size=None, uid=None, updated_at=...
QuickBlox/Blob.py
class Blob: """ Blob object """ def __init__(self, id=None, blob_status=None, content_type=None, created_at=None, last_read_access_ts=None, lifetime=None, name=None, public=None, ref_count=None, set_completed_at=None, size=None, uid=None, updated_at=...
0.701611
0.139455
from __future__ import absolute_import import random import re from oslo_log import log import tobiko from tobiko.openstack import topology from tobiko.shell import sh LOG = log.getLogger(__name__) def get_filtered_node_containers(node, containers_regex): """Search all containers are matched with containers_...
tobiko/tests/faults/containers/container_ops.py
from __future__ import absolute_import import random import re from oslo_log import log import tobiko from tobiko.openstack import topology from tobiko.shell import sh LOG = log.getLogger(__name__) def get_filtered_node_containers(node, containers_regex): """Search all containers are matched with containers_...
0.580828
0.272545
from __future__ import unicode_literals from jinja2 import Template from werkzeug.exceptions import BadRequest class RDSClientError(BadRequest): def __init__(self, code, message): super(RDSClientError, self).__init__() template = Template(""" <RDSClientError> <Error> ...
moto/rds2/exceptions.py
from __future__ import unicode_literals from jinja2 import Template from werkzeug.exceptions import BadRequest class RDSClientError(BadRequest): def __init__(self, code, message): super(RDSClientError, self).__init__() template = Template(""" <RDSClientError> <Error> ...
0.739705
0.05445
import urllib class CurieBackendException(Exception): pass class Backends(object): backends = {} @classmethod def register(cls, scheme): def do_reg(c): cls.backends[scheme] = c return c return do_reg @classmethod def get_backend(cls, app, url, *args, **k...
curiefense/curieconf/server/curieconf/confserver/backend/__init__.py
import urllib class CurieBackendException(Exception): pass class Backends(object): backends = {} @classmethod def register(cls, scheme): def do_reg(c): cls.backends[scheme] = c return c return do_reg @classmethod def get_backend(cls, app, url, *args, **k...
0.321673
0.058292
from datetime import datetime, timedelta, timezone from collections import deque from math import sqrt from time import monotonic, time from pkg_resources import resource_stream from tempfile import TemporaryFile from asyncio import gather, CancelledError, TimeoutError from aiohttp import ClientError, ClientResponseEr...
monocle/notification.py
from datetime import datetime, timedelta, timezone from collections import deque from math import sqrt from time import monotonic, time from pkg_resources import resource_stream from tempfile import TemporaryFile from asyncio import gather, CancelledError, TimeoutError from aiohttp import ClientError, ClientResponseEr...
0.539469
0.060418
from copy import deepcopy from typing import List import base58 from indy_common.auth import Authoriser from indy_common.constants import NYM, ROLE, ATTRIB, SCHEMA, CLAIM_DEF, REF, \ GET_NYM, GET_ATTR, GET_SCHEMA, GET_CLAIM_DEF, SIGNATURE_TYPE, REVOC_REG_DEF from indy_common.roles import Roles from indy_common.st...
indy_node/server/domain_req_handler.py
from copy import deepcopy from typing import List import base58 from indy_common.auth import Authoriser from indy_common.constants import NYM, ROLE, ATTRIB, SCHEMA, CLAIM_DEF, REF, \ GET_NYM, GET_ATTR, GET_SCHEMA, GET_CLAIM_DEF, SIGNATURE_TYPE, REVOC_REG_DEF from indy_common.roles import Roles from indy_common.st...
0.563018
0.132824
import logging import json from googleapiclient.discovery import build logger = logging.getLogger(__name__) class GoogleImageSearchService: DEFAULT_SEARCH_FIELDS = 'items(fileFormat,image(byteSize,height,width),labels,link,mime,snippet,title),queries,searchInformation(searchTime,totalResults)' DEFAULT_PAGE_...
google_image_search_service.py
import logging import json from googleapiclient.discovery import build logger = logging.getLogger(__name__) class GoogleImageSearchService: DEFAULT_SEARCH_FIELDS = 'items(fileFormat,image(byteSize,height,width),labels,link,mime,snippet,title),queries,searchInformation(searchTime,totalResults)' DEFAULT_PAGE_...
0.495361
0.148726
import os import re import time import requests from ..utils import removeImage, showImage, saveImage '''PC端登录去哪儿旅行''' class qunarPC(): is_callable = True def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) self.info = 'login in qunar in pc mode' s...
DecryptLogin/modules/core/qunar.py
import os import re import time import requests from ..utils import removeImage, showImage, saveImage '''PC端登录去哪儿旅行''' class qunarPC(): is_callable = True def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) self.info = 'login in qunar in pc mode' s...
0.204421
0.07343
from flask import Flask, jsonify, make_response,request from flask_cors import CORS from pymongo import MongoClient from bson import ObjectId import json import os import sys import pymongo class JSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, ObjectId): return str(o) ...
serverless/books/app.py
from flask import Flask, jsonify, make_response,request from flask_cors import CORS from pymongo import MongoClient from bson import ObjectId import json import os import sys import pymongo class JSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, ObjectId): return str(o) ...
0.244724
0.064801
import csv import os import json import subprocess import copy from collections import Counter import networkx as nx from graphviz import Source import tempfile from typing import Any, Dict, Set, Tuple from conda_forge_tick.utils import frozen_to_json_friendly, load_graph from conda_forge_tick.auto_tick import initi...
conda_forge_tick/status_report.py
import csv import os import json import subprocess import copy from collections import Counter import networkx as nx from graphviz import Source import tempfile from typing import Any, Dict, Set, Tuple from conda_forge_tick.utils import frozen_to_json_friendly, load_graph from conda_forge_tick.auto_tick import initi...
0.442034
0.173358
from django.contrib.auth.decorators import permission_required from django.shortcuts import render_to_response from BeautifulSoup import BeautifulSoup from wishlist.models import Item from wishlist.views import scrape_price import urllib2 @permission_required('wishlist.add_item') def wishlistr(request, username): ...
wishlist/importer.py
from django.contrib.auth.decorators import permission_required from django.shortcuts import render_to_response from BeautifulSoup import BeautifulSoup from wishlist.models import Item from wishlist.views import scrape_price import urllib2 @permission_required('wishlist.add_item') def wishlistr(request, username): ...
0.439266
0.105579
import logging import BaseHTTPServer import optparse import xml.etree.ElementTree as ET import xml.parsers.expat # enable debug level logging logging.basicConfig(level = logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') options = None # subclassed HTTPRequestHandler class Concierge...
OpenSim/Region/OptionalModules/Avatar/Concierge/ConciergeServer.py
import logging import BaseHTTPServer import optparse import xml.etree.ElementTree as ET import xml.parsers.expat # enable debug level logging logging.basicConfig(level = logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') options = None # subclassed HTTPRequestHandler class Concierge...
0.282592
0.062991
import numpy,tables,os,sys from scipy.signal import hilbert import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec #Check input is correct def getMagPhase(h5,xi,yi,component): zLoBounds=h5.root.globalLimits._v_attrs.vsLowerBounds[2] zUpBounds=h5.root.globalLimits._v_attrs.vsUpperBounds[2] ...
utilities/pyPlotting/plotPolarizationHilbert.py
import numpy,tables,os,sys from scipy.signal import hilbert import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec #Check input is correct def getMagPhase(h5,xi,yi,component): zLoBounds=h5.root.globalLimits._v_attrs.vsLowerBounds[2] zUpBounds=h5.root.globalLimits._v_attrs.vsUpperBounds[2] ...
0.156169
0.403861
from abc import ABC, abstractmethod import math import matplotlib import matplotlib.pyplot as plt import numpy as np from ..depth import ModifiedBandDepth from ..outliers import _envelopes from ._utils import (_figure_to_svg, _get_figure_and_axes, _set_figure_layout_for_fdata, _set_labels) __a...
skfda/exploratory/visualization/_boxplot.py
from abc import ABC, abstractmethod import math import matplotlib import matplotlib.pyplot as plt import numpy as np from ..depth import ModifiedBandDepth from ..outliers import _envelopes from ._utils import (_figure_to_svg, _get_figure_and_axes, _set_figure_layout_for_fdata, _set_labels) __a...
0.83025
0.696255
from . import util as test_util machinery = test_util.import_importlib('importlib.machinery') import os import re import sys import unittest from test import support from distutils.util import get_platform from contextlib import contextmanager from .util import temp_module support.import_module('winreg', required_on=...
Lib/test/test_importlib/test_windows.py
from . import util as test_util machinery = test_util.import_importlib('importlib.machinery') import os import re import sys import unittest from test import support from distutils.util import get_platform from contextlib import contextmanager from .util import temp_module support.import_module('winreg', required_on=...
0.281702
0.214938
import matplotlib.pyplot as plt import numpy as np import src.estimation.configuration as configs from src.datasets.bighand.dataset import BighandDataset from src.datasets.msra.dataset import MSRADataset from src.estimation.preprocessing import DatasetPreprocessor from src.estimation.architecture.jgrp2o import JGR_J2O...
src/estimation/evaluation.py
import matplotlib.pyplot as plt import numpy as np import src.estimation.configuration as configs from src.datasets.bighand.dataset import BighandDataset from src.datasets.msra.dataset import MSRADataset from src.estimation.preprocessing import DatasetPreprocessor from src.estimation.architecture.jgrp2o import JGR_J2O...
0.45641
0.770983
import re from datetime import date from datetime import datetime from decimal import Decimal from .erros import CampoFixoError from .erros import CampoObrigatorioError from .erros import FormatoInvalidoError class Campo(object): """ Classe base para definição de um campo de um registro do SPED. >>> ...
sped/campos.py
import re from datetime import date from datetime import datetime from decimal import Decimal from .erros import CampoFixoError from .erros import CampoObrigatorioError from .erros import FormatoInvalidoError class Campo(object): """ Classe base para definição de um campo de um registro do SPED. >>> ...
0.588653
0.194999
import argparse import curses import robot_interfaces import robot_fingers class CursesGUI: """Displays robot data using curses.""" def __init__(self, win): """Initialize. Args: win: Curses window. """ self.win = win self.win.nodelay(True) def updat...
scripts/position_control_on_off.py
import argparse import curses import robot_interfaces import robot_fingers class CursesGUI: """Displays robot data using curses.""" def __init__(self, win): """Initialize. Args: win: Curses window. """ self.win = win self.win.nodelay(True) def updat...
0.826502
0.391755
from categories_scraper.categories_scraper import CategoriesScraper from home_scraper import HomeScraper from categories_menu_scraper import CategoriesMenuScraper from single_product_scraper import SingleProductScraper from categories_scraper.single_product_category_scraper import SingleProductCategoryScraper fr...
main.py
from categories_scraper.categories_scraper import CategoriesScraper from home_scraper import HomeScraper from categories_menu_scraper import CategoriesMenuScraper from single_product_scraper import SingleProductScraper from categories_scraper.single_product_category_scraper import SingleProductCategoryScraper fr...
0.32146
0.132262
import frappe import re import uuid from frappe.utils import now import hashlib import hmac import hashlib import base64 from datetime import datetime import random import string @frappe.whitelist(allow_guest = True) def create_log(**kwargs): kwargs=frappe._dict(kwargs) doc = frappe.new_doc("Payment Log") ...
club_crm/api/app/pg.py
import frappe import re import uuid from frappe.utils import now import hashlib import hmac import hashlib import base64 from datetime import datetime import random import string @frappe.whitelist(allow_guest = True) def create_log(**kwargs): kwargs=frappe._dict(kwargs) doc = frappe.new_doc("Payment Log") ...
0.256459
0.093969
import numpy as np import pytest from sunkit_image import asda from sunkit_image.data.test import get_test_filepath def test_asda_artificial(): """ Generate an artificial vortex using the Lamb_Oseen class in asda, then perform the vortex detection. """ # Generate an artificial vortex vmax = 2...
sunkit_image/tests/test_asda.py
import numpy as np import pytest from sunkit_image import asda from sunkit_image.data.test import get_test_filepath def test_asda_artificial(): """ Generate an artificial vortex using the Lamb_Oseen class in asda, then perform the vortex detection. """ # Generate an artificial vortex vmax = 2...
0.726717
0.623778
from __future__ import division import roslib import rospy import tf from nav_msgs.msg import Odometry from nav_msgs.msg import Path from geometry_msgs.msg import PoseStamped import numpy as np class GT_cleaner: def __init__(self): self.last_time = rospy.Time.now() self.init = False self...
nodes/centered_mocap_rebroadcaster.py
from __future__ import division import roslib import rospy import tf from nav_msgs.msg import Odometry from nav_msgs.msg import Path from geometry_msgs.msg import PoseStamped import numpy as np class GT_cleaner: def __init__(self): self.last_time = rospy.Time.now() self.init = False self...
0.594316
0.33887
from spyder.widgets.sourcecode.codeeditor import CodeEditor from PyQt5.QtCore import pyqtSignal, QFileSystemWatcher, QTimer from PyQt5.QtWidgets import QAction, QFileDialog import sys from pyqtgraph.parametertree import Parameter from ..mixins import ComponentMixin from ..utils import get_save_filename, get_open_fi...
src/widgets/editor.py
from spyder.widgets.sourcecode.codeeditor import CodeEditor from PyQt5.QtCore import pyqtSignal, QFileSystemWatcher, QTimer from PyQt5.QtWidgets import QAction, QFileDialog import sys from pyqtgraph.parametertree import Parameter from ..mixins import ComponentMixin from ..utils import get_save_filename, get_open_fi...
0.36376
0.099777
import os import csv import cv2 import numpy as np from math import ceil from sklearn.model_selection import train_test_split from sklearn.utils import shuffle from keras.models import Sequential from keras.layers.core import Dense, Activation, Flatten, Dropout from keras.layers.convolutional import Conv2D from keras.l...
model.py
import os import csv import cv2 import numpy as np from math import ceil from sklearn.model_selection import train_test_split from sklearn.utils import shuffle from keras.models import Sequential from keras.layers.core import Dense, Activation, Flatten, Dropout from keras.layers.convolutional import Conv2D from keras.l...
0.660063
0.445168
import textwrap import pytest from pants.backend.python.util_rules.pex import rules as pex_rules from pants.backend.terraform import dependency_inference from pants.backend.terraform.dependency_inference import ( InferTerraformModuleDependenciesRequest, ParseTerraformModuleSources, TerraformHcl2Parser, ) ...
src/python/pants/backend/terraform/dependency_inference_test.py
import textwrap import pytest from pants.backend.python.util_rules.pex import rules as pex_rules from pants.backend.terraform import dependency_inference from pants.backend.terraform.dependency_inference import ( InferTerraformModuleDependenciesRequest, ParseTerraformModuleSources, TerraformHcl2Parser, ) ...
0.592313
0.155848
import testtools import mock from oslo_messaging import conffixture from stevedore import extension from cloudkitty import orchestrator from cloudkitty import tests from cloudkitty.tests.utils import is_functional_test class FakeKeystoneClient(object): class FakeTenants(object): def list(self): ...
cloudkitty/tests/test_orchestrator.py
import testtools import mock from oslo_messaging import conffixture from stevedore import extension from cloudkitty import orchestrator from cloudkitty import tests from cloudkitty.tests.utils import is_functional_test class FakeKeystoneClient(object): class FakeTenants(object): def list(self): ...
0.490968
0.121269
#package imports import detectionformats.beam #stdlib imports import unittest class TestBeam(unittest.TestCase): BACKAZIMUTH = 12.569 SLOWNESS = 2.5 POWERRATIO = 16.1 BACKAZIMUTHERROR = 2.59 SLOWNESSERROR = 5.56 POWERRATIOERROR = 0.12 JSONSTRING = '{"BackAzimuth": 12.569, "Slowness": 2.5,...
python/test/test_beam.py
#package imports import detectionformats.beam #stdlib imports import unittest class TestBeam(unittest.TestCase): BACKAZIMUTH = 12.569 SLOWNESS = 2.5 POWERRATIO = 16.1 BACKAZIMUTHERROR = 2.59 SLOWNESSERROR = 5.56 POWERRATIOERROR = 0.12 JSONSTRING = '{"BackAzimuth": 12.569, "Slowness": 2.5,...
0.53437
0.62065
from cached_property import cached_property from contextlib import contextmanager import logging import subparse import sys import yaml from . import commands class AbortCLI(Exception): def __init__(self, message, code): self.message = message self.code = code class App: stdin = sys.stdin ...
tweeter/cli.py
from cached_property import cached_property from contextlib import contextmanager import logging import subparse import sys import yaml from . import commands class AbortCLI(Exception): def __init__(self, message, code): self.message = message self.code = code class App: stdin = sys.stdin ...
0.261614
0.060975
class Solution: def strToInt(self, str: str) -> int: """常规思路:各种场景""" s = str.strip() if len(s) == 0: return 0 first = s[0] flag = 1 if first == '+': s = s[1:] if first == '-': flag = -1 s = s[1:] num...
lcof/67-ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof.py
class Solution: def strToInt(self, str: str) -> int: """常规思路:各种场景""" s = str.strip() if len(s) == 0: return 0 first = s[0] flag = 1 if first == '+': s = s[1:] if first == '-': flag = -1 s = s[1:] num...
0.530723
0.469155
# NOC modules from noc.sa.profiles.Generic.get_metrics import Script as GetMetricsScript, metrics class Script(GetMetricsScript): name = "Eltex.TAU.get_metrics" @metrics( ["CPU | Usage"], volatile=False, access="S", ) def get_cpu_usage(self, metrics): cpu_usage = self...
sa/profiles/Eltex/TAU/get_metrics.py
# NOC modules from noc.sa.profiles.Generic.get_metrics import Script as GetMetricsScript, metrics class Script(GetMetricsScript): name = "Eltex.TAU.get_metrics" @metrics( ["CPU | Usage"], volatile=False, access="S", ) def get_cpu_usage(self, metrics): cpu_usage = self...
0.523177
0.160135
import numpy as np import matplotlib.pyplot as plt import math # Choose the controller you want to plot: 1) flexran 2) 5gempower 3) altflexran controller = "flexran" # Location of the input folder according to the chosen controller input_folder = "data/{}_measurements".format(controller) # Location of the output fol...
plot_functions/mem_plot_heatmap.py
import numpy as np import matplotlib.pyplot as plt import math # Choose the controller you want to plot: 1) flexran 2) 5gempower 3) altflexran controller = "flexran" # Location of the input folder according to the chosen controller input_folder = "data/{}_measurements".format(controller) # Location of the output fol...
0.685423
0.641282
from .factories import HomePageFactory, ThemeFactory, ThemePageFactory, ArticlePageFactory, \ ThemeIndexPageFactory, ArticleIndexPageFactory from django.test import TestCase, RequestFactory from wagtail.core.models import Page, Site class TestPageModels(TestCase): @classmethod def setUpTestData(cls): ...
cms/tests/test_pages.py
from .factories import HomePageFactory, ThemeFactory, ThemePageFactory, ArticlePageFactory, \ ThemeIndexPageFactory, ArticleIndexPageFactory from django.test import TestCase, RequestFactory from wagtail.core.models import Page, Site class TestPageModels(TestCase): @classmethod def setUpTestData(cls): ...
0.448668
0.150528
import time import unittest from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer class AzureSignalRServiceScenarioTest(ScenarioTest): @ResourceGroupPreparer(random_name_length=20) def test_signalr_commands(self, resource_group): signalr_name = self.create_random_name('signalr', 16) ...
src/azure-cli/azure/cli/command_modules/signalr/tests/latest/test_signalr_commands.py
import time import unittest from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer class AzureSignalRServiceScenarioTest(ScenarioTest): @ResourceGroupPreparer(random_name_length=20) def test_signalr_commands(self, resource_group): signalr_name = self.create_random_name('signalr', 16) ...
0.549157
0.221224
import os import subprocess import time import sys sys.path.append("test/utils") import util apply_cmd = "kubectl apply -f {}" delete_cmd = "kubectl delete -f {}" def clean(chain_type): subprocess.getoutput(delete_cmd.format("test/reliability/chaos/network-chaos.yaml")) subprocess.getoutput(delete_cmd.forma...
test/reliability/scripts/chaos-test.py
import os import subprocess import time import sys sys.path.append("test/utils") import util apply_cmd = "kubectl apply -f {}" delete_cmd = "kubectl delete -f {}" def clean(chain_type): subprocess.getoutput(delete_cmd.format("test/reliability/chaos/network-chaos.yaml")) subprocess.getoutput(delete_cmd.forma...
0.117978
0.089455
import os import sys import tempfile from importlib import util as import_util from pathlib import Path from typing import Any, Dict, Union from .logging import get_logger _RULE_FOLDER = os.path.join(tempfile.gettempdir(), 'rules') # Rule with ID 'aws_globals' contains common Python logic used by other rules COMMON...
internal/log_analysis/rules_engine/src/rule.py
import os import sys import tempfile from importlib import util as import_util from pathlib import Path from typing import Any, Dict, Union from .logging import get_logger _RULE_FOLDER = os.path.join(tempfile.gettempdir(), 'rules') # Rule with ID 'aws_globals' contains common Python logic used by other rules COMMON...
0.611498
0.125065
import sys import time # please install numpy module (python-numpy on Arch Linux) import numpy as np import tools.timeutils as timeutils def fill_matrix(): """ Return a numpy matrix from the data in problem11-data.txt """ array = [] with open('problem11-data.txt', 'r') as f: for line in f:...
problem11.py
import sys import time # please install numpy module (python-numpy on Arch Linux) import numpy as np import tools.timeutils as timeutils def fill_matrix(): """ Return a numpy matrix from the data in problem11-data.txt """ array = [] with open('problem11-data.txt', 'r') as f: for line in f:...
0.513181
0.574096
import os import torch import torch.nn as nn import torch.utils import torch.backends.cudnn as cudnn import xnas.core.logging as logging import xnas.core.config as config import xnas.core.meters as meters import xnas.search_space.DrNAS.utils as utils from xnas.core.builders import build_loss_fun, DrNAS_builder from xn...
search/DrNAS/nb201space_progressive.py
import os import torch import torch.nn as nn import torch.utils import torch.backends.cudnn as cudnn import xnas.core.logging as logging import xnas.core.config as config import xnas.core.meters as meters import xnas.search_space.DrNAS.utils as utils from xnas.core.builders import build_loss_fun, DrNAS_builder from xn...
0.71423
0.296635
from math import sqrt import multiprocessing from functools import partial import numpy as np from scipy.special import erfinv from scipy import linalg from joblib import Parallel, delayed, Memory from mdct_tools import mdct_waveform, mdct, MDCT def check_random_state(seed): """Turn seed into a np.random.Rando...
bird/_bird.py
from math import sqrt import multiprocessing from functools import partial import numpy as np from scipy.special import erfinv from scipy import linalg from joblib import Parallel, delayed, Memory from mdct_tools import mdct_waveform, mdct, MDCT def check_random_state(seed): """Turn seed into a np.random.Rando...
0.762424
0.328637
from __future__ import unicode_literals from blinker import Namespace _signals = Namespace() registration_personal_data_modified = _signals.signal('registration-personal-data-modified', """ Called when the registration personal data is modified. The `sender` is the `Registration` object; the change is passed in th...
indico/core/signals/event/registration.py
from __future__ import unicode_literals from blinker import Namespace _signals = Namespace() registration_personal_data_modified = _signals.signal('registration-personal-data-modified', """ Called when the registration personal data is modified. The `sender` is the `Registration` object; the change is passed in th...
0.880116
0.607925
import pytest from tests.conftest import perform_once def test_changelog_and_version(accelize_drm): """ Checks if Version match with Git tag and if changelog is up to date. """ perform_once(__name__ + '.test_changelog_and_version') from os.path import join from subprocess import run, PIPE ...
tests/test_release_checks.py
import pytest from tests.conftest import perform_once def test_changelog_and_version(accelize_drm): """ Checks if Version match with Git tag and if changelog is up to date. """ perform_once(__name__ + '.test_changelog_and_version') from os.path import join from subprocess import run, PIPE ...
0.561455
0.355747
import pandas as pd from matplotlib import pyplot as plt import seaborn as sns # Read csv and store in dataframe df df = pd.read_csv("results.csv") df.drop(["index"], axis=1).reset_index(drop=True) # Separate fifth grade tests femte_trinn = df[ (df["statistikk"] == "Nasjonale prøver 5. trinn") & (pd.isna(df["ver...
script.py
import pandas as pd from matplotlib import pyplot as plt import seaborn as sns # Read csv and store in dataframe df df = pd.read_csv("results.csv") df.drop(["index"], axis=1).reset_index(drop=True) # Separate fifth grade tests femte_trinn = df[ (df["statistikk"] == "Nasjonale prøver 5. trinn") & (pd.isna(df["ver...
0.376509
0.434701
from hashlib import md5 from django.contrib.auth.models import User from django.core import validators from django.db import models from iommi import register_factory from unread.models import UnreadModel class Model(models.Model): def __repr__(self): return f'{type(self)} {self.pk}:{self}' class M...
forum/models.py
from hashlib import md5 from django.contrib.auth.models import User from django.core import validators from django.db import models from iommi import register_factory from unread.models import UnreadModel class Model(models.Model): def __repr__(self): return f'{type(self)} {self.pk}:{self}' class M...
0.706494
0.17172
"""Encoding Custermized NN Module""" import torch from torch.nn import Module, Sequential, Conv2d, ReLU, AdaptiveAvgPool2d from torch.nn import functional as F from .syncbn import BatchNorm2d __all__ = ['GramMatrix', 'View', 'Sum', 'Mean', 'Normalize', 'PyramidPooling'] class GramMatrix(Module): r""" Gram Matr...
encoding/nn/customize.py
"""Encoding Custermized NN Module""" import torch from torch.nn import Module, Sequential, Conv2d, ReLU, AdaptiveAvgPool2d from torch.nn import functional as F from .syncbn import BatchNorm2d __all__ = ['GramMatrix', 'View', 'Sum', 'Mean', 'Normalize', 'PyramidPooling'] class GramMatrix(Module): r""" Gram Matr...
0.965004
0.775222
import numpy as np import pandas as pd import pytest from featuretools.primitives import CityblockDistance, GeoMidpoint, IsInGeoBox def test_cityblock(): primitive_instance = CityblockDistance() latlong_1 = pd.Series([(i, i) for i in range(3)]) latlong_2 = pd.Series([(i, i) for i in range(3, 6)]) pri...
featuretools/tests/primitive_tests/test_latlong_primitives.py
import numpy as np import pandas as pd import pytest from featuretools.primitives import CityblockDistance, GeoMidpoint, IsInGeoBox def test_cityblock(): primitive_instance = CityblockDistance() latlong_1 = pd.Series([(i, i) for i in range(3)]) latlong_2 = pd.Series([(i, i) for i in range(3, 6)]) pri...
0.546738
0.57523
from __future__ import absolute_import, unicode_literals import fakeredis import pytest import redis import unittest import socket from array import array from case import ANY, ContextMock, Mock, call, mock, skip, patch from collections import defaultdict from contextlib import contextmanager from itertools import co...
t/unit/transport/test_redis.py
from __future__ import absolute_import, unicode_literals import fakeredis import pytest import redis import unittest import socket from array import array from case import ANY, ContextMock, Mock, call, mock, skip, patch from collections import defaultdict from contextlib import contextmanager from itertools import co...
0.644113
0.062646
from typing import Collection, Tuple, Union class BitString(int): """ Given a binary string or positive integer, store the value as an integer which can be sliced or concatenated based on the string representation. Useful for working with binary-coded decimal values where, for example, each 4-bit...
src/frico/bitstring.py
from typing import Collection, Tuple, Union class BitString(int): """ Given a binary string or positive integer, store the value as an integer which can be sliced or concatenated based on the string representation. Useful for working with binary-coded decimal values where, for example, each 4-bit...
0.962259
0.551091
from ...coresight.coresight_target import CoreSightTarget from ...core.memory_map import (FlashRegion, RamRegion, MemoryMap) from ...debug.svd.loader import SVDFile class DBGMCU: STPCTL = 0xE0042020 STPCTL_VALUE = 0x3FFB TRACECTL = 0xE0042024 TRACECTL_VALUE = 0x0 FLASH_ALGO = { 'load_address' : 0x...
pyocd/target/builtin/target_HC32M423.py
from ...coresight.coresight_target import CoreSightTarget from ...core.memory_map import (FlashRegion, RamRegion, MemoryMap) from ...debug.svd.loader import SVDFile class DBGMCU: STPCTL = 0xE0042020 STPCTL_VALUE = 0x3FFB TRACECTL = 0xE0042024 TRACECTL_VALUE = 0x0 FLASH_ALGO = { 'load_address' : 0x...
0.401453
0.270631
import pickle import pytest from tekdrive.exceptions import ClientException from tekdrive.models import File from ...base import UnitTest class TestFileModel(UnitTest): def test_unknown_attribute(self): with pytest.raises(AttributeError): File(self.tekdrive, _data=dict(id="ae80")).unknown_at...
tests/unit/models/drive/test_file.py
import pickle import pytest from tekdrive.exceptions import ClientException from tekdrive.models import File from ...base import UnitTest class TestFileModel(UnitTest): def test_unknown_attribute(self): with pytest.raises(AttributeError): File(self.tekdrive, _data=dict(id="ae80")).unknown_at...
0.583441
0.3863
import logging import re # Thanks to JGoutin @ https://github.com/JGoutin/movie_nfo_generator/blob/master/movie_nfo_generator/nfo.py from pathlib import Path from lxml.etree import Element, ElementTree, ParseError, SubElement from .utils import PathDetails logger = logging.getLogger(__name__) pd = PathDetails cla...
PinVidderer/nfo.py
import logging import re # Thanks to JGoutin @ https://github.com/JGoutin/movie_nfo_generator/blob/master/movie_nfo_generator/nfo.py from pathlib import Path from lxml.etree import Element, ElementTree, ParseError, SubElement from .utils import PathDetails logger = logging.getLogger(__name__) pd = PathDetails cla...
0.712932
0.238711
from __future__ import annotations from dataclasses import make_dataclass from warnings import warn import numpy as np import pandas as pd import statsmodels.api as sm from statsmodels.regression.rolling import RollingOLS from pqr.utils import align def extract_annualizer(df_or_series: pd.DataFrame | pd.Series) ->...
pqr/analytics/utils.py
from __future__ import annotations from dataclasses import make_dataclass from warnings import warn import numpy as np import pandas as pd import statsmodels.api as sm from statsmodels.regression.rolling import RollingOLS from pqr.utils import align def extract_annualizer(df_or_series: pd.DataFrame | pd.Series) ->...
0.880206
0.455501
import tensorflow as tf from network import Network layers = tf.keras.layers applications = tf.keras.applications class LargeVggNetwork(Network): """ Extension of LargeNetwork that uses a pretrained VGG network to process faces. """ def _build_custom(self): trainable = not self._fine_tune # Get pre...
itracker/common/network/large_vgg_network.py
import tensorflow as tf from network import Network layers = tf.keras.layers applications = tf.keras.applications class LargeVggNetwork(Network): """ Extension of LargeNetwork that uses a pretrained VGG network to process faces. """ def _build_custom(self): trainable = not self._fine_tune # Get pre...
0.869963
0.703371
import sys import os, platform import subprocess import socket import os.path as path from multiprocessing import Process class ngrok(object): def __init__(self, authtoken, port, nT, hash): if authtoken: self.token = authtoken else: print "Can't use Ngrok without a valid token" system_type = os.name sys...
core/ngrok.py
import sys import os, platform import subprocess import socket import os.path as path from multiprocessing import Process class ngrok(object): def __init__(self, authtoken, port, nT, hash): if authtoken: self.token = authtoken else: print "Can't use Ngrok without a valid token" system_type = os.name sys...
0.053372
0.088662
from django.core import mail as _mail from django.test import TestCase from gae2django.gaeapi.appengine.api import mail class MailFunctionsTest(TestCase): def test_send_mail(self): mail.send_mail('<EMAIL>', '<EMAIL>', 'Subject', 'Body') self.assertEqual(len(_mail.outbox),...
gae2django/tests/test_mail.py
from django.core import mail as _mail from django.test import TestCase from gae2django.gaeapi.appengine.api import mail class MailFunctionsTest(TestCase): def test_send_mail(self): mail.send_mail('<EMAIL>', '<EMAIL>', 'Subject', 'Body') self.assertEqual(len(_mail.outbox),...
0.368519
0.195844
import os ''' Plugin handler for the seismicpi plugin. ''' class SeedlinkPluginHandler: # Create defaults def __init__(self): pass def push(self, seedlink): # Check and set defaults try: seedlink.param('sources.seismicpi.port_path_hint') except: seedlink.setParam('sources.seismicpi.port_path_hint', ...
src/seedlink/templates/seismicpi/setup.py
import os ''' Plugin handler for the seismicpi plugin. ''' class SeedlinkPluginHandler: # Create defaults def __init__(self): pass def push(self, seedlink): # Check and set defaults try: seedlink.param('sources.seismicpi.port_path_hint') except: seedlink.setParam('sources.seismicpi.port_path_hint', ...
0.409575
0.108378
import requests from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from Crypto.PublicKey import RSA import base64 import random import string import json # 把原账号绑定微信 以防丢失 # 1. qq先登录 绑定手机 # 2. 解绑qq,重新用手机登录 # 3. 填写邀请码,并且注销账号 # 4. 反复循环前三步 # 随机名字 def rand_name(): name = '通友{}' return name.format(random.ra...
invite_user.py
import requests from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from Crypto.PublicKey import RSA import base64 import random import string import json # 把原账号绑定微信 以防丢失 # 1. qq先登录 绑定手机 # 2. 解绑qq,重新用手机登录 # 3. 填写邀请码,并且注销账号 # 4. 反复循环前三步 # 随机名字 def rand_name(): name = '通友{}' return name.format(random.ra...
0.130743
0.095434
from typing import Any, Callable, List, Optional, TextIO, Type, TypeVar, Union, overload from rich.console import Console from rich.prompt import InvalidResponse, PromptBase from rich.text import Text, TextType IndexType = TypeVar("IndexType") class IndexPrompt(PromptBase[IndexType]): response_type: Union[Type[...
scripts/style/prompt.py
from typing import Any, Callable, List, Optional, TextIO, Type, TypeVar, Union, overload from rich.console import Console from rich.prompt import InvalidResponse, PromptBase from rich.text import Text, TextType IndexType = TypeVar("IndexType") class IndexPrompt(PromptBase[IndexType]): response_type: Union[Type[...
0.734691
0.365032
import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split from sklearn import preprocessing from sklearn import metrics import hdnntools as hd...
datatools/obpred.py
import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split from sklearn import preprocessing from sklearn import metrics import hdnntools as hd...
0.506591
0.526586
import os.path as op import yaml from bakery_lint import run_set from bakery_lint.base import BakeryTestCase class FontLint(object): def __init__(self, bakery): self.project_root = bakery.project_root self.builddir = bakery.build_dir self.bakery = bakery def read_lint_testsresult(se...
bakery_cli/pipe/fontlint.py
import os.path as op import yaml from bakery_lint import run_set from bakery_lint.base import BakeryTestCase class FontLint(object): def __init__(self, bakery): self.project_root = bakery.project_root self.builddir = bakery.build_dir self.bakery = bakery def read_lint_testsresult(se...
0.235724
0.15511
import torch from autoencoder import Autoencoder import time import numpy as np # Begin of variables that can be edited by the user trained_models = [ (Autoencoder.Autoencoder1(), "trained_autoencoders/a1.pt"), (Autoencoder.Autoencoder2(), "trained_autoencoders/a2.pt"), (Autoencoder.Autoencoder3(), "traine...
autoencoder/test_performance.py
import torch from autoencoder import Autoencoder import time import numpy as np # Begin of variables that can be edited by the user trained_models = [ (Autoencoder.Autoencoder1(), "trained_autoencoders/a1.pt"), (Autoencoder.Autoencoder2(), "trained_autoencoders/a2.pt"), (Autoencoder.Autoencoder3(), "traine...
0.791942
0.28688
from __future__ import unicode_literals from django.db import migrations, models import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('theme', '0001_initial'), ] operations = [ migrations.AlterField( model_name='homepage', name='f...
theme/migrations/0002_auto_20171223_2332.py
from __future__ import unicode_literals from django.db import migrations, models import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('theme', '0001_initial'), ] operations = [ migrations.AlterField( model_name='homepage', name='f...
0.675229
0.181082
import asynctest import asynctest.mock as mock import asyncio import aiohttp.web from opsdroid.__main__ import configure_lang from opsdroid.core import OpsDroid from opsdroid.web import Web from opsdroid import matchers class TestMatchers(asynctest.TestCase): """Test the opsdroid matcher decorators.""" asy...
tests/test_matchers.py
import asynctest import asynctest.mock as mock import asyncio import aiohttp.web from opsdroid.__main__ import configure_lang from opsdroid.core import OpsDroid from opsdroid.web import Web from opsdroid import matchers class TestMatchers(asynctest.TestCase): """Test the opsdroid matcher decorators.""" asy...
0.546496
0.500366
from polyaxon.polyflow import V1RunKind from polyaxon.polyflow.matrix.kinds import V1MatrixKind def get_fxt_grid_with_inputs_outputs(): return { "version": 1.1, "kind": "operation", "name": "run", "tags": ["key1", "value1"], "params": {"image": {"value": "test"}, "lr": {"v...
platform/polycommon/polycommon/test_cases/fixtures/grid.py
from polyaxon.polyflow import V1RunKind from polyaxon.polyflow.matrix.kinds import V1MatrixKind def get_fxt_grid_with_inputs_outputs(): return { "version": 1.1, "kind": "operation", "name": "run", "tags": ["key1", "value1"], "params": {"image": {"value": "test"}, "lr": {"v...
0.678753
0.464112
COCO_EMBEDDINGS = { 0: "unlabeled", 1: "person", 2: "bicycle", 3: "car", 4: "motorcycle", 5: "airplane", 6: "bus", 7: "train", 8: "truck", 9: "boat", 10: "traffic light", 11: "fire hydrant", 12: "street sign", 13: "stop sign", 14: "parking meter", 15: "be...
fcos/model/embeddings.py
COCO_EMBEDDINGS = { 0: "unlabeled", 1: "person", 2: "bicycle", 3: "car", 4: "motorcycle", 5: "airplane", 6: "bus", 7: "train", 8: "truck", 9: "boat", 10: "traffic light", 11: "fire hydrant", 12: "street sign", 13: "stop sign", 14: "parking meter", 15: "be...
0.657098
0.452717
import torch import torch.nn as nn class InstanceNorm(nn.Module): def __init__(self, num_features, eps=1e-5, affine=True): super(InstanceNorm, self).__init__() self.num_features = num_features self.eps = eps self.affine = affine if self.affine: self.weight = nn...
fastgc/layers/norm.py
import torch import torch.nn as nn class InstanceNorm(nn.Module): def __init__(self, num_features, eps=1e-5, affine=True): super(InstanceNorm, self).__init__() self.num_features = num_features self.eps = eps self.affine = affine if self.affine: self.weight = nn...
0.944753
0.536434
import os import subprocess import re class VirtualEnvironment(object): """Changing the virtualenvironment.""" def __init__(self, path): self.path = path def create(self, python): subprocess.check_call(['virtualenv', "--python", python, self.path]) class PipInstaller(object): """Manag...
pbundle/installer.py
import os import subprocess import re class VirtualEnvironment(object): """Changing the virtualenvironment.""" def __init__(self, path): self.path = path def create(self, python): subprocess.check_call(['virtualenv', "--python", python, self.path]) class PipInstaller(object): """Manag...
0.562177
0.115212