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
class RestServer: def __init__(self, cluster_configuration, service_configuration, default_service_configuraiton): self.cluster_configuration = cluster_configuration self.service_configuration = dict(default_service_configuraiton, **service_configuration) ...
src/rest-server/config/rest_server.py
class RestServer: def __init__(self, cluster_configuration, service_configuration, default_service_configuraiton): self.cluster_configuration = cluster_configuration self.service_configuration = dict(default_service_configuraiton, **service_configuration) ...
0.604516
0.105671
import os import string import nltk # type: ignore import re from nltk import FreqDist from nltk.corpus import brown, stopwords # type: ignore from typing import List from langcreator.common import Generators, InputOutput, InputOutputGenerator, get_tags, choice, builtin_generators nltk.download('brown', quiet=True) ...
langcreator/generator.py
import os import string import nltk # type: ignore import re from nltk import FreqDist from nltk.corpus import brown, stopwords # type: ignore from typing import List from langcreator.common import Generators, InputOutput, InputOutputGenerator, get_tags, choice, builtin_generators nltk.download('brown', quiet=True) ...
0.486819
0.275288
import logging from owslib.etree import etree from owslib import crs, util from owslib.namespaces import Namespaces LOGGER = logging.getLogger(__name__) n = Namespaces() OWS_NAMESPACE_1_0_0 = n.get_namespace("ows") OWS_NAMESPACE_1_1_0 = n.get_namespace("ows110") OWS_NAMESPACE_2_0_0 = n.get_namespace("ows200") XSI_N...
owslib/ows.py
import logging from owslib.etree import etree from owslib import crs, util from owslib.namespaces import Namespaces LOGGER = logging.getLogger(__name__) n = Namespaces() OWS_NAMESPACE_1_0_0 = n.get_namespace("ows") OWS_NAMESPACE_1_1_0 = n.get_namespace("ows110") OWS_NAMESPACE_2_0_0 = n.get_namespace("ows200") XSI_N...
0.405802
0.080538
from nose.tools import eq_ import mkt import mkt.site.tests from mkt.site.utils import app_factory, version_factory from mkt.reviewers import helpers class TestGetPosition(mkt.site.tests.TestCase): def setUp(self): # Add a public, reviewed app for measure. It took 4 days for this app # to get re...
mkt/reviewers/tests/test_helpers.py
from nose.tools import eq_ import mkt import mkt.site.tests from mkt.site.utils import app_factory, version_factory from mkt.reviewers import helpers class TestGetPosition(mkt.site.tests.TestCase): def setUp(self): # Add a public, reviewed app for measure. It took 4 days for this app # to get re...
0.66072
0.247089
import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from ann import ANN # Read the data from the CSV file red_data_path = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv" white_data_path = "h...
DNN/wine_classification_ann.py
import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from ann import ANN # Read the data from the CSV file red_data_path = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv" white_data_path = "h...
0.907606
0.734346
import tensorflow as tf _R_MEAN = 123.68 _G_MEAN = 116.78 _B_MEAN = 103.94 _RESIZE_SIDE_MIN = 256 _RESIZE_SIDE_MAX = 512 def _crop(image, offset_height, offset_width, crop_height, crop_width): """Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input ima...
tftrt/examples/image_classification/preprocessing.py
import tensorflow as tf _R_MEAN = 123.68 _G_MEAN = 116.78 _B_MEAN = 103.94 _RESIZE_SIDE_MIN = 256 _RESIZE_SIDE_MAX = 512 def _crop(image, offset_height, offset_width, crop_height, crop_width): """Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input ima...
0.95321
0.623635
from __future__ import absolute_import # Copyright (c) 2010-2018 openpyxl # Python stdlib imports from datetime import ( time, datetime, date, timedelta, ) # 3rd party imports import pytest # package imports from openpyxl.comments import Comment from openpyxl.cell.cell import ERROR_CODES @pytest....
openpyxl/cell/tests/test_cell.py
from __future__ import absolute_import # Copyright (c) 2010-2018 openpyxl # Python stdlib imports from datetime import ( time, datetime, date, timedelta, ) # 3rd party imports import pytest # package imports from openpyxl.comments import Comment from openpyxl.cell.cell import ERROR_CODES @pytest....
0.564819
0.486514
from .tool.func import * import random def randomkeyy(): alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" password = "" for i in range(6): index = random.randrange(len(alphabet)) password = password + alphabet[index] return password def login_need_email_2(conn, tool): curs = conn...
route/login_need_email.py
from .tool.func import * import random def randomkeyy(): alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" password = "" for i in range(6): index = random.randrange(len(alphabet)) password = password + alphabet[index] return password def login_need_email_2(conn, tool): curs = conn...
0.176743
0.07521
# coding: utf-8 from elasticsearch import Elasticsearch class ElasticSearchClient(object): def __init__(self): self._es_client = None def init_app(self, app): if 'ES_HOST' in app.config and 'ES_PORT' in app.config: self._es_client = Elasticsearch([ { ...
web_console_v2/api/fedlearner_webconsole/utils/es.py
# coding: utf-8 from elasticsearch import Elasticsearch class ElasticSearchClient(object): def __init__(self): self._es_client = None def init_app(self, app): if 'ES_HOST' in app.config and 'ES_PORT' in app.config: self._es_client = Elasticsearch([ { ...
0.486088
0.257281
import collections import redis import numpy as np from representations import StateAction import random from textworld.core import EnvInfos GraphInfo = collections.namedtuple('GraphInfo', 'objs, ob_rep, act_rep, graph_state, graph_state_rep, admissible_actions, admissible_actions_rep') def load_vocab(env): with ...
kga2c/env.py
import collections import redis import numpy as np from representations import StateAction import random from textworld.core import EnvInfos GraphInfo = collections.namedtuple('GraphInfo', 'objs, ob_rep, act_rep, graph_state, graph_state_rep, admissible_actions, admissible_actions_rep') def load_vocab(env): with ...
0.628863
0.200969
import tmt class ProvisionLocal(tmt.steps.provision.ProvisionPlugin): """ Use local host for test execution In general it is not recommended to run tests on your local machine as there might be security risks. Run only those tests which you know are safe so that you don't destroy your laptop ;-) ...
tmt/steps/provision/local.py
import tmt class ProvisionLocal(tmt.steps.provision.ProvisionPlugin): """ Use local host for test execution In general it is not recommended to run tests on your local machine as there might be security risks. Run only those tests which you know are safe so that you don't destroy your laptop ;-) ...
0.555194
0.516535
from django.core.management.base import CommandError from django.contrib.auth import get_user_model from courses.api import deactivate_program_enrollment, deactivate_run_enrollment from courses.management.utils import EnrollmentChangeCommand, enrollment_summaries from courses.constants import ENROLL_CHANGE_STATUS_TRAN...
courses/management/commands/transfer_enrollment.py
from django.core.management.base import CommandError from django.contrib.auth import get_user_model from courses.api import deactivate_program_enrollment, deactivate_run_enrollment from courses.management.utils import EnrollmentChangeCommand, enrollment_summaries from courses.constants import ENROLL_CHANGE_STATUS_TRAN...
0.428592
0.179279
from tests.fields.subclass_models import RaceParticipant, RacePlacingEnum from tortoise.contrib import test class TestCustomFieldFilters(test.IsolatedTestCase): tortoise_test_modules = ["tests.fields.subclass_models"] async def asyncSetUp(self): await super().asyncSetUp() await RaceParticipan...
tests/fields/test_subclass_filters.py
from tests.fields.subclass_models import RaceParticipant, RacePlacingEnum from tortoise.contrib import test class TestCustomFieldFilters(test.IsolatedTestCase): tortoise_test_modules = ["tests.fields.subclass_models"] async def asyncSetUp(self): await super().asyncSetUp() await RaceParticipan...
0.68941
0.327225
import pytest import respx from httpx import Response from nonebug.app import App from .utils import get_file, get_json @pytest.fixture def mcbbsnews(app: App): from nonebot_bison.platform import platform_manager return platform_manager["mcbbsnews"] @pytest.fixture(scope="module") def raw_post_list(): ...
tests/platforms/test_mcbbsnews.py
import pytest import respx from httpx import Response from nonebug.app import App from .utils import get_file, get_json @pytest.fixture def mcbbsnews(app: App): from nonebot_bison.platform import platform_manager return platform_manager["mcbbsnews"] @pytest.fixture(scope="module") def raw_post_list(): ...
0.374676
0.161122
import tensorflow as tf from CONSTANT import AUDIO_SAMPLE_RATE, IS_CUT_AUDIO, MAX_AUDIO_DURATION from data_process import extract_mfcc_parallel, get_max_length, ohe2cat, pad_seq from models.attention import Attention from models.my_classifier import Classifier from tensorflow.python.keras import optimizers from tensorf...
examples/automl_freiburg/winner_speech/models/bilstm_attention.py
import tensorflow as tf from CONSTANT import AUDIO_SAMPLE_RATE, IS_CUT_AUDIO, MAX_AUDIO_DURATION from data_process import extract_mfcc_parallel, get_max_length, ohe2cat, pad_seq from models.attention import Attention from models.my_classifier import Classifier from tensorflow.python.keras import optimizers from tensorf...
0.864697
0.262552
#----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) #-------------...
bokeh/application/handlers/script.py
#----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) #-------------...
0.514644
0.048294
from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import tempfile from subprocess import PIPE import requests import six from io import open def tmpfile(*args, **kwargs): fd, path = tempfile.mkstemp(*args, **kwargs) return (os.fdopen(fd, 'w'), path) d...
corehq/ex-submodules/dimagi/utils/post.py
from __future__ import absolute_import from __future__ import unicode_literals import os import subprocess import tempfile from subprocess import PIPE import requests import six from io import open def tmpfile(*args, **kwargs): fd, path = tempfile.mkstemp(*args, **kwargs) return (os.fdopen(fd, 'w'), path) d...
0.435781
0.084417
import services import sims4.commands from server_commands.argument_helpers import SimInfoParam, TunableInstanceParam RELATIONSHIP_MAX_SCORE = 100 FRIEND_TYPE = 'LTR_Friendship_Main' ROMANCE_TYPE = 'LTR_Romance_Main' # become_friend <FirstName> <LastName> # the param HAS TO be : info1: SimInfoParam, info2: SimInfoPa...
src/relationship.py
import services import sims4.commands from server_commands.argument_helpers import SimInfoParam, TunableInstanceParam RELATIONSHIP_MAX_SCORE = 100 FRIEND_TYPE = 'LTR_Friendship_Main' ROMANCE_TYPE = 'LTR_Romance_Main' # become_friend <FirstName> <LastName> # the param HAS TO be : info1: SimInfoParam, info2: SimInfoPa...
0.32338
0.140513
from datetime import date, timedelta from django import forms from django.utils.translation import ugettext_lazy as _ from frozendict import frozendict from api.task.serializers import TASK_STATES, TASK_OBJECT_TYPES, TaskLogFilterSerializer class BaseTaskLogFilterForm(forms.Form): DEFAULT_DATE_FROM = frozendict(...
gui/tasklog/forms.py
from datetime import date, timedelta from django import forms from django.utils.translation import ugettext_lazy as _ from frozendict import frozendict from api.task.serializers import TASK_STATES, TASK_OBJECT_TYPES, TaskLogFilterSerializer class BaseTaskLogFilterForm(forms.Form): DEFAULT_DATE_FROM = frozendict(...
0.619011
0.064535
import asyncio import io import logging import time from asyncio import Lock, StreamReader, StreamWriter from typing import Dict, List, Optional, Tuple from lib.chiavdf.inkfish.classgroup import ClassGroup from lib.chiavdf.inkfish.create_discriminant import create_discriminant from lib.chiavdf.inkfish.proof_of_time i...
src/timelord.py
import asyncio import io import logging import time from asyncio import Lock, StreamReader, StreamWriter from typing import Dict, List, Optional, Tuple from lib.chiavdf.inkfish.classgroup import ClassGroup from lib.chiavdf.inkfish.create_discriminant import create_discriminant from lib.chiavdf.inkfish.proof_of_time i...
0.713332
0.184345
from __future__ import print_function, division, absolute_import from astropy.time import Time from .. import fetch import numpy as np from .. import cache __all__ = ['MNF_TIME', 'times_indexes', 'DerivedParameter'] MNF_TIME = 0.25625 # Minor Frame duration (seconds) def times_indexes(start, stop, dt...
jeta/archive/derived/base.py
from __future__ import print_function, division, absolute_import from astropy.time import Time from .. import fetch import numpy as np from .. import cache __all__ = ['MNF_TIME', 'times_indexes', 'DerivedParameter'] MNF_TIME = 0.25625 # Minor Frame duration (seconds) def times_indexes(start, stop, dt...
0.695752
0.338952
from surprise.model_selection import GridSearchCV def perform_grid_search(data, model_dict, param_grid, cv): """ Return list of trained models in GridSearch :param data: Trainset to use in model training :param model_dict: Dictionary with list of models(and their names) ...
grid_search.py
from surprise.model_selection import GridSearchCV def perform_grid_search(data, model_dict, param_grid, cv): """ Return list of trained models in GridSearch :param data: Trainset to use in model training :param model_dict: Dictionary with list of models(and their names) ...
0.821939
0.47859
import time import spdlog as spd from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from buzzblog.gen import TLikeService def instrumented(func): """ TODO : Method description """ def func_wrapper(self, request_metadata, *args, **kwargs): ...
app/uniquepair/service/tests/site-packages/buzzblog/like_client.py
import time import spdlog as spd from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from buzzblog.gen import TLikeService def instrumented(func): """ TODO : Method description """ def func_wrapper(self, request_metadata, *args, **kwargs): ...
0.28398
0.071235
from __future__ import absolute_import, division, unicode_literals from six import string_types import param import numpy as np from bokeh.models import CustomJS from bokeh.models.formatters import TickFormatter from bokeh.models.widgets import ( DateSlider as _BkDateSlider, DateRangeSlider as _BkDateRangeSlider...
panel/widgets/slider.py
from __future__ import absolute_import, division, unicode_literals from six import string_types import param import numpy as np from bokeh.models import CustomJS from bokeh.models.formatters import TickFormatter from bokeh.models.widgets import ( DateSlider as _BkDateSlider, DateRangeSlider as _BkDateRangeSlider...
0.706292
0.245209
from __future__ import annotations from collections.abc import Callable from typing import Any, cast from pytradfri.command import Command from homeassistant.components.cover import ATTR_POSITION, CoverEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homea...
homeassistant/components/tradfri/cover.py
from __future__ import annotations from collections.abc import Callable from typing import Any, cast from pytradfri.command import Command from homeassistant.components.cover import ATTR_POSITION, CoverEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homea...
0.908355
0.116011
import time from signal import signal, SIGSEGV from types import MethodType try: import mathsat from pysmt.solvers.msat import MathSAT5Solver except ImportError: class MathSAT5Solver: pass try: from pysmt.solvers.z3 import Z3Solver except ImportError: class Z3Solver: pass from pys...
src/multisolver.py
import time from signal import signal, SIGSEGV from types import MethodType try: import mathsat from pysmt.solvers.msat import MathSAT5Solver except ImportError: class MathSAT5Solver: pass try: from pysmt.solvers.z3 import Z3Solver except ImportError: class Z3Solver: pass from pys...
0.646906
0.35421
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_rosenbrock import spot_setup from sp...
spotpy/examples/tutorial_rosenbrock.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_rosenbrock import spot_setup from sp...
0.557364
0.092033
import logging from unittest.mock import patch import pandas as pd import pytest import awswrangler as wr from ._utils import ensure_athena_query_metadata logging.getLogger("awswrangler").setLevel(logging.DEBUG) def test_athena_cache(path, glue_database, glue_table, workgroup1): df = pd.DataFrame({"c0": [0, N...
tests/test_athena_cache.py
import logging from unittest.mock import patch import pandas as pd import pytest import awswrangler as wr from ._utils import ensure_athena_query_metadata logging.getLogger("awswrangler").setLevel(logging.DEBUG) def test_athena_cache(path, glue_database, glue_table, workgroup1): df = pd.DataFrame({"c0": [0, N...
0.587707
0.434041
from typing import List, NamedTuple from genyrator import Entity import genyrator.entities.Template as Template from genyrator.entities.Template import create_template from genyrator.types import TypeOption TemplateConfig = NamedTuple('TemplateConfig', [ ('root_files', List[Template.Template]), ('core', ...
genyrator/template_config.py
from typing import List, NamedTuple from genyrator import Entity import genyrator.entities.Template as Template from genyrator.entities.Template import create_template from genyrator.types import TypeOption TemplateConfig = NamedTuple('TemplateConfig', [ ('root_files', List[Template.Template]), ('core', ...
0.536313
0.123207
from flask import Flask, render_template, request, redirect, url_for, session from azure.storage.blob import BlockBlobService from azure.storage.blob import PublicAccess from azure.storage.blob import ContentSettings import mysql.connector from mysql.connector import errorcode import os import csv import random from da...
main.py
from flask import Flask, render_template, request, redirect, url_for, session from azure.storage.blob import BlockBlobService from azure.storage.blob import PublicAccess from azure.storage.blob import ContentSettings import mysql.connector from mysql.connector import errorcode import os import csv import random from da...
0.269902
0.076822
from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework import generics from rest_framework.permissions import IsAuthenticated from rest_framework.test import APITestCase from menus_project import constants as c from menus_project import factories as f from . import serialize...
api/test_views.py
from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework import generics from rest_framework.permissions import IsAuthenticated from rest_framework.test import APITestCase from menus_project import constants as c from menus_project import factories as f from . import serialize...
0.622
0.317109
import argparse import pytorch_lightning as pl from wheat.config import load_config from wheat.data_module import WheatDataModule from wheat.dataset import WheatDataset from wheat.model import WheatModel def predict(config, args_dict: dict, ckpt_path: str): """Run inference on the test set and save predictions....
wheat/scripts/predict.py
import argparse import pytorch_lightning as pl from wheat.config import load_config from wheat.data_module import WheatDataModule from wheat.dataset import WheatDataset from wheat.model import WheatModel def predict(config, args_dict: dict, ckpt_path: str): """Run inference on the test set and save predictions....
0.721351
0.395835
import pulp import random import time import matplotlib.pyplot as plt ''' ้›†ๅˆ่ฆ†็›–้—ฎ้ข˜๏ผš โ€ข ่พ“ๅ…ฅ: ๆœ‰้™้›† X, X ็š„ๅญ้›†ๅˆๆ— F, X=โˆช๐‘†โˆˆ๐น S โ€ข ่พ“ๅ‡บ: CโІF, ๆปก่ถณ ๏ผˆ1๏ผ‰X=โˆช๐‘†โˆˆ๐ถ S ๏ผˆ2๏ผ‰C ๆ˜ฏๆปก่ถณๆกไปถ(1)็š„ๆœ€ๅฐ้›†ๆ—, ๅณ|C|ๆœ€ๅฐ. ''' # ็”Ÿๆˆๅฎž้ชŒๆ•ฐๆฎ class generate(): def __init__(self): self.X = [] # ๆœ‰้™้›† self.F = [] # ๅญ้›†ๅˆๆ— def generateData(self, size): ...
src/ApproximateAlgorithm/SetCoverage.py
import pulp import random import time import matplotlib.pyplot as plt ''' ้›†ๅˆ่ฆ†็›–้—ฎ้ข˜๏ผš โ€ข ่พ“ๅ…ฅ: ๆœ‰้™้›† X, X ็š„ๅญ้›†ๅˆๆ— F, X=โˆช๐‘†โˆˆ๐น S โ€ข ่พ“ๅ‡บ: CโІF, ๆปก่ถณ ๏ผˆ1๏ผ‰X=โˆช๐‘†โˆˆ๐ถ S ๏ผˆ2๏ผ‰C ๆ˜ฏๆปก่ถณๆกไปถ(1)็š„ๆœ€ๅฐ้›†ๆ—, ๅณ|C|ๆœ€ๅฐ. ''' # ็”Ÿๆˆๅฎž้ชŒๆ•ฐๆฎ class generate(): def __init__(self): self.X = [] # ๆœ‰้™้›† self.F = [] # ๅญ้›†ๅˆๆ— def generateData(self, size): ...
0.0956
0.230432
import ctypes import math inputFilePath = "Input_Cases/Individual/sudoku_input_difficult.txt" algoChoice = 1 # defaults to backtrack algo SudokuSolverLib = ctypes.CDLL('./lib/SudokuSolverLib.so') def readSudInput(filepath): # helper function ,reads in .txt sud_sizes = [el ** 2 for el in range(1, 17)] # s...
SudokuSolver.py
import ctypes import math inputFilePath = "Input_Cases/Individual/sudoku_input_difficult.txt" algoChoice = 1 # defaults to backtrack algo SudokuSolverLib = ctypes.CDLL('./lib/SudokuSolverLib.so') def readSudInput(filepath): # helper function ,reads in .txt sud_sizes = [el ** 2 for el in range(1, 17)] # s...
0.398524
0.387314
from jcourse_api.models import * def create_test_env() -> None: dept_seiee = Department.objects.create(name='SEIEE') dept_phy = Department.objects.create(name='PHYSICS') teacher_gao = Teacher.objects.create(tid=1, name='้ซ˜ๅฅณๅฃซ', department=dept_seiee, title='ๆ•™ๆŽˆ', pinyin='gaoxiaofeng', ...
jcourse_api/tests/__init__.py
from jcourse_api.models import * def create_test_env() -> None: dept_seiee = Department.objects.create(name='SEIEE') dept_phy = Department.objects.create(name='PHYSICS') teacher_gao = Teacher.objects.create(tid=1, name='้ซ˜ๅฅณๅฃซ', department=dept_seiee, title='ๆ•™ๆŽˆ', pinyin='gaoxiaofeng', ...
0.287968
0.190178
_base_ = [ '../_base_/datasets/scannet-3d-18class.py', '../_base_/models/votenet.py', '../_base_/default_runtime.py' ] data = dict( samples_per_gpu=2, workers_per_gpu=2 ) model = dict( backbone=dict( _delete_=True, type='Pointformer', num_points=(2048, 1024, 512, 256), ra...
configs/pointformer/votenet_ptr_scannet-3d-18class.py
_base_ = [ '../_base_/datasets/scannet-3d-18class.py', '../_base_/models/votenet.py', '../_base_/default_runtime.py' ] data = dict( samples_per_gpu=2, workers_per_gpu=2 ) model = dict( backbone=dict( _delete_=True, type='Pointformer', num_points=(2048, 1024, 512, 256), ra...
0.395601
0.244352
import csv import re import dateutil.parser import scrape_util from urllib.request import Request, urlopen from sys import argv from bs4 import BeautifulSoup default_sale, base_url, prefix = scrape_util.get_market(argv) strip_char = ';,. \n\t' def get_sale_date(date_head): """Return the date of the livestock sa...
_307_scrape.py
import csv import re import dateutil.parser import scrape_util from urllib.request import Request, urlopen from sys import argv from bs4 import BeautifulSoup default_sale, base_url, prefix = scrape_util.get_market(argv) strip_char = ';,. \n\t' def get_sale_date(date_head): """Return the date of the livestock sa...
0.414899
0.117851
from abc import ABC, abstractmethod class Environment(ABC): """ A reinforcement learning Environment. In reinforcement learning, an Agent learns by interacting with an Environment. An Environment defines the dynamics of a particular problem: the states, the actions, the transitions between states,...
all/environments/abstract.py
from abc import ABC, abstractmethod class Environment(ABC): """ A reinforcement learning Environment. In reinforcement learning, an Agent learns by interacting with an Environment. An Environment defines the dynamics of a particular problem: the states, the actions, the transitions between states,...
0.949867
0.887984
from coremltools.converters.mil.mil.passes.quantization_passes import AbstractQuantizationPass from coremltools.converters.mil.mil.passes.pass_registry import PASS_REGISTRY import logging as _logging from coremltools.converters._profile_utils import _profile from tqdm import tqdm as _tqdm from coremltools.converters.m...
coremltools/converters/mil/mil/passes/apply_common_pass_pipeline.py
from coremltools.converters.mil.mil.passes.quantization_passes import AbstractQuantizationPass from coremltools.converters.mil.mil.passes.pass_registry import PASS_REGISTRY import logging as _logging from coremltools.converters._profile_utils import _profile from tqdm import tqdm as _tqdm from coremltools.converters.m...
0.560493
0.274528
from csv import DictReader MAX_GLOBAL_CLOCKS = 24 MAX_COLUMN_CLOCKS = 12 def gen_rclk_int(grid): for tile_name in sorted(grid.tiles()): loc = grid.loc_of_tilename(tile_name) gridinfo = grid.gridinfo_at_loc(loc) if gridinfo.tile_type in ["RCLK_INT_L", "RCLK_INT_R"]: yield loc...
utils/clock_utils.py
from csv import DictReader MAX_GLOBAL_CLOCKS = 24 MAX_COLUMN_CLOCKS = 12 def gen_rclk_int(grid): for tile_name in sorted(grid.tiles()): loc = grid.loc_of_tilename(tile_name) gridinfo = grid.gridinfo_at_loc(loc) if gridinfo.tile_type in ["RCLK_INT_L", "RCLK_INT_R"]: yield loc...
0.474875
0.272956
import numpy as np from random import randint from PIL import Image # Basic implementation of recursive division maze generation # Credit to Wikipedia.org Maze Generation # 1s will represent wall 0s will represent white space # All positions are measured from the top left corner (0,0) Debug = True class Chamber: d...
Oldcrap/generator.py
import numpy as np from random import randint from PIL import Image # Basic implementation of recursive division maze generation # Credit to Wikipedia.org Maze Generation # 1s will represent wall 0s will represent white space # All positions are measured from the top left corner (0,0) Debug = True class Chamber: d...
0.422386
0.542742
import logging from typing import Optional from fastapi import HTTPException, Depends from fastapi.encoders import jsonable_encoder from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED from sqlalchemy.exc import IntegrityError from dispatch.plugins.base import plugins from dispat...
src/dispatch/auth/service.py
import logging from typing import Optional from fastapi import HTTPException, Depends from fastapi.encoders import jsonable_encoder from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED from sqlalchemy.exc import IntegrityError from dispatch.plugins.base import plugins from dispat...
0.784236
0.0584
import copy import datetime import itertools import json import os import sys import unittest sys.path.insert(1, os.path.abspath( os.path.join(os.path.dirname(__file__), '../telescope'))) import iptranslation import selector import utils class SelectorFileParserTest(unittest.TestCase): def parse_file_conte...
tests/test_selector.py
import copy import datetime import itertools import json import os import sys import unittest sys.path.insert(1, os.path.abspath( os.path.join(os.path.dirname(__file__), '../telescope'))) import iptranslation import selector import utils class SelectorFileParserTest(unittest.TestCase): def parse_file_conte...
0.424889
0.344761
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" __all__ = ('EnumOption',) import string import SCons.Errors def _validator(key, val, env, vals): if not val in vals: raise SCons.Errors.UserError( 'Invalid value for option %s: %s' % (key, val)) def EnumOption(key, help, defaul...
src/engine/SCons/Options/EnumOption.py
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" __all__ = ('EnumOption',) import string import SCons.Errors def _validator(key, val, env, vals): if not val in vals: raise SCons.Errors.UserError( 'Invalid value for option %s: %s' % (key, val)) def EnumOption(key, help, defaul...
0.533641
0.247192
# # elif a[l]==key and q>l: # # l=q # elif a[q]>key: # r=q # else: # p=q # q1=q # q2=q # while p<q1: # q=(p+q1)//2 # if a[q]==key: # ...
python/searching/var_binary_search.py
# # elif a[l]==key and q>l: # # l=q # elif a[q]>key: # r=q # else: # p=q # q1=q # q2=q # while p<q1: # q=(p+q1)//2 # if a[q]==key: # ...
0.042652
0.157137
from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import F from django.urls import reverse from ..cooggerapp.models.common import Common, View, Vote f...
core/threaded_comment/models.py
from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import F from django.urls import reverse from ..cooggerapp.models.common import Common, View, Vote f...
0.606265
0.09556
import numpy as np import matplotlib.pyplot as plt from deepblast.dataset.utils import states2alignment, tmstate_f, states2edges def roc_edges(true_edges, pred_edges): truth = set(true_edges) pred = set(pred_edges) tp = len(truth & pred) fp = len(pred - truth) fn = len(truth - pred) perc_id = ...
deepblast/score.py
import numpy as np import matplotlib.pyplot as plt from deepblast.dataset.utils import states2alignment, tmstate_f, states2edges def roc_edges(true_edges, pred_edges): truth = set(true_edges) pred = set(pred_edges) tp = len(truth & pred) fp = len(pred - truth) fn = len(truth - pred) perc_id = ...
0.718002
0.684462
from typing import NamedTuple, Dict, Callable, Union import os import json import wandb import torch import random import shutil import tarfile import tempfile import numpy as np from pathlib import Path from loguru import logger from copy import deepcopy from functools import wraps import torch.distributed as dist imp...
vae_lm/training/utils.py
from typing import NamedTuple, Dict, Callable, Union import os import json import wandb import torch import random import shutil import tarfile import tempfile import numpy as np from pathlib import Path from loguru import logger from copy import deepcopy from functools import wraps import torch.distributed as dist imp...
0.843412
0.168891
import sys from kikit.doc import runBoardExample, runBoardExampleJoin from pcbnewTransition import pcbnew counter = 0 def autoName(): global counter counter += 1 return f"examplePanel{counter}" SRC = "doc/resources/conn.kicad_pcb" print( """ # Examples This document will show you several examples of Ki...
scripts/exampleDoc.py
Then run KiKit: """) runBoardExample(autoName(), [["panelize"], ["--layout", "grid; rows: 2; cols: 2; space: 2mm"], ["--tabs", "fixed; width: 3mm; vcount: 2"], ["--cuts", "mousebites; drill: 0.5mm; spacing: 1mm; offset: 0.2mm; prolong: 0.5mm"], ["--framing", "railstb; width: 5mm; s...
0.556761
0.660898
"""Tests for the unconstrained BFGS optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import numpy as np from scipy.stats import special_ortho_group import tensorflow as tf import tensorflow_probability as tfp from tensorflow....
tensorflow_probability/python/optimizer/bfgs_test.py
"""Tests for the unconstrained BFGS optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import numpy as np from scipy.stats import special_ortho_group import tensorflow as tf import tensorflow_probability as tfp from tensorflow....
0.94001
0.531209
import time import webbrowser as web from datetime import datetime from typing import Optional from urllib.parse import quote import pyautogui import pyautogui as pg from pywhatkit.core import core, exceptions, log import winsound pg.FAILSAFE = False core.check_connection() WAIT_TO_LOAD_WEB = 8 WAIT_TO_LOAD_APP = ...
pywhatkit/whats.py
import time import webbrowser as web from datetime import datetime from typing import Optional from urllib.parse import quote import pyautogui import pyautogui as pg from pywhatkit.core import core, exceptions, log import winsound pg.FAILSAFE = False core.check_connection() WAIT_TO_LOAD_WEB = 8 WAIT_TO_LOAD_APP = ...
0.494141
0.091666
import discord from discord.ext import commands from discord import utils import asyncio import json class Developers: def __init__(self, bot): self.bot = bot @commands.group() @commands.is_owner() async def extension(self, ctx): if ctx.invoked_subcommand is None...
extensions/developer.py
import discord from discord.ext import commands from discord import utils import asyncio import json class Developers: def __init__(self, bot): self.bot = bot @commands.group() @commands.is_owner() async def extension(self, ctx): if ctx.invoked_subcommand is None...
0.532911
0.17971
''' distribute- and pip-enabled setup.py ''' from __future__ import print_function import sys import logging import os import re import shutil # ----- overrides ----- # set these to anything but None to override the automatic defaults packages = None package_name = None package_data = None scripts = None # ---------...
setup.py
''' distribute- and pip-enabled setup.py ''' from __future__ import print_function import sys import logging import os import re import shutil # ----- overrides ----- # set these to anything but None to override the automatic defaults packages = None package_name = None package_data = None scripts = None # ---------...
0.336113
0.098729
from __future__ import print_function import datetime import os import sys import pygrib import pytz from pyiem.datatypes import distance from pyiem.plot import MapPlot import matplotlib.cm as cm def do(ts, hours): """ Create a plot of precipitation stage4 estimates for some day """ ts = ts.replace(m...
scripts/current/stage4_xhour.py
from __future__ import print_function import datetime import os import sys import pygrib import pytz from pyiem.datatypes import distance from pyiem.plot import MapPlot import matplotlib.cm as cm def do(ts, hours): """ Create a plot of precipitation stage4 estimates for some day """ ts = ts.replace(m...
0.398289
0.221877
from __future__ import division import numpy as np from .J_table import J_table import sys from time import time from numpy import log, sqrt, exp, pi from scipy.signal import fftconvolve as convolve def P_IA_deltaE2(k,P): N=k.size n= np.arange(-N+1,N ) dL=log(k[1])-log(k[0]) s=n*dL cut=3 high_s=s[s > cut] lo...
fastpt/IA_ta.py
from __future__ import division import numpy as np from .J_table import J_table import sys from time import time from numpy import log, sqrt, exp, pi from scipy.signal import fftconvolve as convolve def P_IA_deltaE2(k,P): N=k.size n= np.arange(-N+1,N ) dL=log(k[1])-log(k[0]) s=n*dL cut=3 high_s=s[s > cut] lo...
0.16099
0.226431
from fractions import Fraction from wick.expression import AExpression from wick.wick import apply_wick from wick.convenience import one_e, two_e, E1, E2, commute from wick.convenience import ketE1, ketE2, ketEip1, ketEea1 from wick.convenience import ketEea2, ketEip2, ketEdea1, ketEdip1 from wick.convenience import br...
examples/ccsd_Heff.py
from fractions import Fraction from wick.expression import AExpression from wick.wick import apply_wick from wick.convenience import one_e, two_e, E1, E2, commute from wick.convenience import ketE1, ketE2, ketEip1, ketEea1 from wick.convenience import ketEea2, ketEip2, ketEdea1, ketEdip1 from wick.convenience import br...
0.291989
0.333992
import shlex import subprocess import doit # type: ignore from buildchain import config from buildchain import constants from buildchain import types from buildchain import utils def task__vagrantkey() -> types.TaskDict: """Generate a SSH key pair in the .vagrant folder.""" def mkdir_dot_vagrant() -> None...
buildchain/buildchain/vagrant.py
import shlex import subprocess import doit # type: ignore from buildchain import config from buildchain import constants from buildchain import types from buildchain import utils def task__vagrantkey() -> types.TaskDict: """Generate a SSH key pair in the .vagrant folder.""" def mkdir_dot_vagrant() -> None...
0.535827
0.31871
import numpy as np from astropy.units import Quantity, Unit from astropy.time import Time from astropy.io.votable.converters import ( get_converter as get_votable_converter) from .exceptions import DALServiceError NUMERIC_DATATYPES = {'short', 'int', 'long', 'float', 'double'} def find_param_by_keyword(keywor...
pyvo/dal/params.py
import numpy as np from astropy.units import Quantity, Unit from astropy.time import Time from astropy.io.votable.converters import ( get_converter as get_votable_converter) from .exceptions import DALServiceError NUMERIC_DATATYPES = {'short', 'int', 'long', 'float', 'double'} def find_param_by_keyword(keywor...
0.8321
0.409103
from morphotactics.morphotactics import compile from morphotactics.slot import Slot from morphotactics.stem_guesser import StemGuesser import pynini import pywrapfst from IPython.display import SVG, display # helper function that transduces input_str belonging to lower alphabet to string in upper alphabet def analyze...
tests/test_toy_nawat_nouns.py
from morphotactics.morphotactics import compile from morphotactics.slot import Slot from morphotactics.stem_guesser import StemGuesser import pynini import pywrapfst from IPython.display import SVG, display # helper function that transduces input_str belonging to lower alphabet to string in upper alphabet def analyze...
0.571527
0.555254
from abc import ABC, abstractmethod from typing import Sequence, Union, Tuple, Any import re import numpy as np from mdde.agent.abc import NodeAgentMapping from mdde.agent.enums import EActionResult from mdde.config import ConfigEnvironment from mdde.registry.protocol import PRegistryReadClient, PRegistryWriteClient ...
mdde/core/mdde/agent/abc/abc_agent.py
from abc import ABC, abstractmethod from typing import Sequence, Union, Tuple, Any import re import numpy as np from mdde.agent.abc import NodeAgentMapping from mdde.agent.enums import EActionResult from mdde.config import ConfigEnvironment from mdde.registry.protocol import PRegistryReadClient, PRegistryWriteClient ...
0.941808
0.350088
class CategoryAttribute(Attribute, _Attribute): """ Specifies the name of the category in which to group the property or event when displayed in a System.Windows.Forms.PropertyGrid control set to Categorized mode. CategoryAttribute() CategoryAttribute(category: str) """ def Equals(self, obj...
release/stubs.min/System/ComponentModel/__init___parts/CategoryAttribute.py
class CategoryAttribute(Attribute, _Attribute): """ Specifies the name of the category in which to group the property or event when displayed in a System.Windows.Forms.PropertyGrid control set to Categorized mode. CategoryAttribute() CategoryAttribute(category: str) """ def Equals(self, obj...
0.823719
0.408926
import json import math import unittest from pytopojson import ( feature, mesh, stitch, ) class MeshTestCase(unittest.TestCase): def setUp(self): self.feature = feature.Feature() self.mesh = mesh.Mesh() self.stitch = stitch.Stitch() def test_mesh_ignores_null_geometries(s...
tests/test_mesh.py
import json import math import unittest from pytopojson import ( feature, mesh, stitch, ) class MeshTestCase(unittest.TestCase): def setUp(self): self.feature = feature.Feature() self.mesh = mesh.Mesh() self.stitch = stitch.Stitch() def test_mesh_ignores_null_geometries(s...
0.552298
0.456773
from pathlib import Path from time import time import tempfile import pytest from target_extraction.data_types import TargetTextCollection from target_extraction.dataset_parsers import CACHE_DIRECTORY from target_extraction.dataset_parsers import download_election_folder from target_extraction.dataset_parsers import ...
tests/dataset_parsers/wang_2017_election_test.py
from pathlib import Path from time import time import tempfile import pytest from target_extraction.data_types import TargetTextCollection from target_extraction.dataset_parsers import CACHE_DIRECTORY from target_extraction.dataset_parsers import download_election_folder from target_extraction.dataset_parsers import ...
0.505859
0.442516
import logging from common_utils_py.did import did_to_id from contracts_lib_py.keeper import Keeper from contracts_lib_py.utils import process_fulfill_condition from eth_utils import add_0x_prefix logger = logging.getLogger(__name__) def fulfill_access_secret_store_condition(event, agreement_id, did, service_agreem...
nevermined_gateway_events/event_handlers/lockRewardCondition.py
import logging from common_utils_py.did import did_to_id from contracts_lib_py.keeper import Keeper from contracts_lib_py.utils import process_fulfill_condition from eth_utils import add_0x_prefix logger = logging.getLogger(__name__) def fulfill_access_secret_store_condition(event, agreement_id, did, service_agreem...
0.646125
0.115536
"""Tests for load_bigquery_stats.""" import datetime import unittest import flask import mock import webtest from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.tests.test_libs import helpers as test_helpers from clusterfuzz._internal.tests.test_libs import test_utils from handlers.cron ...
src/clusterfuzz/_internal/tests/appengine/handlers/cron/load_bigquery_stats_test.py
"""Tests for load_bigquery_stats.""" import datetime import unittest import flask import mock import webtest from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.tests.test_libs import helpers as test_helpers from clusterfuzz._internal.tests.test_libs import test_utils from handlers.cron ...
0.560974
0.314616
from conans import ConanFile, tools, CMake from conans.errors import ConanInvalidConfiguration import os required_conan_version = ">=1.33.0" class VulkanLoaderConan(ConanFile): name = "vulkan-loader" description = "Khronos official Vulkan ICD desktop loader for Windows, Linux, and MacOS." topics = ("vulk...
recipes/vulkan-loader/all/conanfile.py
from conans import ConanFile, tools, CMake from conans.errors import ConanInvalidConfiguration import os required_conan_version = ">=1.33.0" class VulkanLoaderConan(ConanFile): name = "vulkan-loader" description = "Khronos official Vulkan ICD desktop loader for Windows, Linux, and MacOS." topics = ("vulk...
0.297878
0.133669
import argparse import os import pickle import GPUtil import numpy as np from rte_pac.utils.data_reader import embed_data_set_with_glove_2, load_feature_by_data_set, \ number_feature, generate_concat_indices_for_inter_evidence, generate_concat_indices_for_claim from rte_pac.utils.estimator_definitions import get_...
src/scripts/rte.py
import argparse import os import pickle import GPUtil import numpy as np from rte_pac.utils.data_reader import embed_data_set_with_glove_2, load_feature_by_data_set, \ number_feature, generate_concat_indices_for_inter_evidence, generate_concat_indices_for_claim from rte_pac.utils.estimator_definitions import get_...
0.347426
0.09236
import random import pytest import networkx as nx import pandas as pd from stellargraph.mapper import DirectedGraphSAGENodeGenerator from stellargraph.core.graph import StellarGraph, StellarDiGraph def create_simple_graph(): """ Creates a simple directed graph for testing. The node ids are integers. Ret...
tests/mapper/test_directed_node_generator.py
import random import pytest import networkx as nx import pandas as pd from stellargraph.mapper import DirectedGraphSAGENodeGenerator from stellargraph.core.graph import StellarGraph, StellarDiGraph def create_simple_graph(): """ Creates a simple directed graph for testing. The node ids are integers. Ret...
0.765506
0.708944
import torch from torch.utils.data import Dataset import numpy as np import dgl from dgl.data.utils import download, extract_archive, get_download_dir from .mol_tree_nx import DGLMolTree from .mol_tree import Vocab from .mpn import mol2dgl_single as mol2dgl_enc from .jtmpn import mol2dgl_single as mol2dgl_dec from .j...
examples/pytorch/jtnn/jtnn/datautils.py
import torch from torch.utils.data import Dataset import numpy as np import dgl from dgl.data.utils import download, extract_archive, get_download_dir from .mol_tree_nx import DGLMolTree from .mol_tree import Vocab from .mpn import mol2dgl_single as mol2dgl_enc from .jtmpn import mol2dgl_single as mol2dgl_dec from .j...
0.494873
0.350727
from django import forms from django.contrib import messages from django.core.exceptions import ValidationError from django.db.models import ObjectDoesNotExist from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import ugettext as _ from django.views import generic from plata...
examples/custom/views.py
from django import forms from django.contrib import messages from django.core.exceptions import ValidationError from django.db.models import ObjectDoesNotExist from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import ugettext as _ from django.views import generic from plata...
0.516108
0.10923
import os import re import inspect import importlib from lxml import etree import click import jinja2 from prompt_toolkit import ( prompt ) from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.shortcuts import print_tokens from botocore import xform_name from botocore.session import Ses...
scripts/scaffold.py
import os import re import inspect import importlib from lxml import etree import click import jinja2 from prompt_toolkit import ( prompt ) from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.shortcuts import print_tokens from botocore import xform_name from botocore.session import Ses...
0.224565
0.090093
from selfdrive.kegman_conf import kegman_conf class AtomConf(): def __init__(self, CP=None): self.kegman = kegman_conf() self.tun_type = 'lqr' self.sR_KPH = [0] # Speed kph self.sR_BPV = [[0,]] self.sR_steerRatioV = [[13.85,]] self.sR_ActuatorDelayV = [[0.1,]] self...
selfdrive/atom_conf.py
from selfdrive.kegman_conf import kegman_conf class AtomConf(): def __init__(self, CP=None): self.kegman = kegman_conf() self.tun_type = 'lqr' self.sR_KPH = [0] # Speed kph self.sR_BPV = [[0,]] self.sR_steerRatioV = [[13.85,]] self.sR_ActuatorDelayV = [[0.1,]] self...
0.309337
0.09122
def part1(input_str: str) -> None: numbers: list[str] = input_str.split('\n') place_counts:dict[int, dict[int, int]] = get_place_counts(numbers) gamma_rate = '' epsilon_rate = '' for k, v in place_counts.items(): if v.get(0, 0) > v.get(1, 0): gamma_rate += '0' epsilon...
python/2021/aoc2021day3.py
def part1(input_str: str) -> None: numbers: list[str] = input_str.split('\n') place_counts:dict[int, dict[int, int]] = get_place_counts(numbers) gamma_rate = '' epsilon_rate = '' for k, v in place_counts.items(): if v.get(0, 0) > v.get(1, 0): gamma_rate += '0' epsilon...
0.278159
0.414425
from torchsummary import summary from torch import nn import torch.nn.functional as F class SEBlock(nn.Module): def __init__(self, in_channels, reduction=16): super().__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(in_channels, in_channels ...
SEResNeXt/SEResNeXt_pytorch.py
from torchsummary import summary from torch import nn import torch.nn.functional as F class SEBlock(nn.Module): def __init__(self, in_channels, reduction=16): super().__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(in_channels, in_channels ...
0.971712
0.510619
import time, re, csv, os from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains runList=[] def connect(driver): driver.get("https://www.strava.com/login") driver.find_element_by_id("email").send_keys("<EMAIL>") driver.find_element_by_id("password").send_keys("<PAS...
web_scraping/onemonth.py
import time, re, csv, os from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains runList=[] def connect(driver): driver.get("https://www.strava.com/login") driver.find_element_by_id("email").send_keys("<EMAIL>") driver.find_element_by_id("password").send_keys("<PAS...
0.080919
0.069415
from file import BankAccountFileWriter class BankAccount: def __init__(self, account_number, name, password, value, admin): self.account_number = account_number self.name = name self.password = password self.value = value self.admin = admin def check_account_number(se...
cash_machine.py
from file import BankAccountFileWriter class BankAccount: def __init__(self, account_number, name, password, value, admin): self.account_number = account_number self.name = name self.password = password self.value = value self.admin = admin def check_account_number(se...
0.572842
0.247726
import abc import logging import time import warnings from enum import Enum from typing import Any from dateutil.parser import parse from great_expectations.core import ExpectationSuite, RunIdentifier from great_expectations.exceptions import GreatExpectationsError from ..data_asset import DataAsset from ..dataset i...
great_expectations/profile/base.py
import abc import logging import time import warnings from enum import Enum from typing import Any from dateutil.parser import parse from great_expectations.core import ExpectationSuite, RunIdentifier from great_expectations.exceptions import GreatExpectationsError from ..data_asset import DataAsset from ..dataset i...
0.757615
0.300386
import os import sys import json import base64 import argparse import subprocess import collections from copy import deepcopy import torch.cuda from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LAUNCHER from ..constants import TORCH_...
deepspeed/launcher/runner.py
import os import sys import json import base64 import argparse import subprocess import collections from copy import deepcopy import torch.cuda from .multinode_runner import PDSHRunner, OpenMPIRunner, MVAPICHRunner from .constants import PDSH_LAUNCHER, OPENMPI_LAUNCHER, MVAPICH_LAUNCHER from ..constants import TORCH_...
0.452536
0.083516
from __future__ import print_function import unittest import numpy as np import os import sys import six import paddle import paddle.nn as nn import paddle.optimizer as opt import paddle.fluid as fluid from paddle.fluid.optimizer import Adam import paddle.fluid.framework as framework from test_imperative_base import...
python/paddle/fluid/tests/unittests/test_paddle_save_load.py
from __future__ import print_function import unittest import numpy as np import os import sys import six import paddle import paddle.nn as nn import paddle.optimizer as opt import paddle.fluid as fluid from paddle.fluid.optimizer import Adam import paddle.fluid.framework as framework from test_imperative_base import...
0.619586
0.29054
import unittest import numpy as np from mo.middle.passes.fusing.decomposition import convert_scale_shift_to_mul_add, convert_batch_norm from mo.utils.unittest.graph import build_graph from mo.utils.ir_engine.compare_graphs import compare_graphs nodes_attributes = { 'placeholder_1': {'shape': None, 'type': 'Param...
model-optimizer/mo/middle/passes/fusing/decomposition_test.py
import unittest import numpy as np from mo.middle.passes.fusing.decomposition import convert_scale_shift_to_mul_add, convert_batch_norm from mo.utils.unittest.graph import build_graph from mo.utils.ir_engine.compare_graphs import compare_graphs nodes_attributes = { 'placeholder_1': {'shape': None, 'type': 'Param...
0.557966
0.396068
import six import tensorflow as tf from deeplab import common from deeplab import model from deeplab.datasets import segmentation_dataset from deeplab.utils import input_generator from deeplab.utils import train_utils from deployment import model_deploy import numpy as np slim = tf.contrib.slim prefetch_queue = slim.p...
research/deeplab/train.py
import six import tensorflow as tf from deeplab import common from deeplab import model from deeplab.datasets import segmentation_dataset from deeplab.utils import input_generator from deeplab.utils import train_utils from deployment import model_deploy import numpy as np slim = tf.contrib.slim prefetch_queue = slim.p...
0.898254
0.383728
import random def main(): Name= raw_input("Your name:") phone= raw_input ("Your current phone:") sp= smartphone() cp= currentPhone() p=output(Name,phone,cp,sp) print p def calculation(afford,use,superRandom,password): return afford,use,superRandom,password def smartphone(): afford= money() use= re...
conditionals.py
import random def main(): Name= raw_input("Your name:") phone= raw_input ("Your current phone:") sp= smartphone() cp= currentPhone() p=output(Name,phone,cp,sp) print p def calculation(afford,use,superRandom,password): return afford,use,superRandom,password def smartphone(): afford= money() use= re...
0.136551
0.121425
import tensorflow as tf import tensorflow.contrib.slim as slim import logging from convlstm import ConvGRUCell, ConvLSTMCell logger = logging.getLogger('mview3d.' + __name__) def get_bias(shape, name='bias'): return tf.get_variable( name, shape=shape, initializer=tf.constant_initializer(0.0)) def get_...
ops.py
import tensorflow as tf import tensorflow.contrib.slim as slim import logging from convlstm import ConvGRUCell, ConvLSTMCell logger = logging.getLogger('mview3d.' + __name__) def get_bias(shape, name='bias'): return tf.get_variable( name, shape=shape, initializer=tf.constant_initializer(0.0)) def get_...
0.837188
0.482185
from __future__ import print_function import logging import os import sys import math import random import re from six.moves import input import apimetrics logging.basicConfig( stream=sys.stdout, format='%(asctime)s:%(levelname)s: %(message)s', level=os.environ.get('DEBUG_LEVEL') or logging.INFO) log = lo...
apimetrics/scripts/deploy_all_apis.py
from __future__ import print_function import logging import os import sys import math import random import re from six.moves import input import apimetrics logging.basicConfig( stream=sys.stdout, format='%(asctime)s:%(levelname)s: %(message)s', level=os.environ.get('DEBUG_LEVEL') or logging.INFO) log = lo...
0.34632
0.054676
from spack import * import re import os import glob class Zoltan(Package): """The Zoltan library is a toolkit of parallel combinatorial algorithms for parallel, unstructured, and/or adaptive scientific applications. Zoltan's largest component is a suite of dynamic load-balancing and partit...
var/spack/repos/builtin/packages/zoltan/package.py
from spack import * import re import os import glob class Zoltan(Package): """The Zoltan library is a toolkit of parallel combinatorial algorithms for parallel, unstructured, and/or adaptive scientific applications. Zoltan's largest component is a suite of dynamic load-balancing and partit...
0.469763
0.245266
import pytest from niacin.text.en import word @pytest.mark.parametrize( "string,p,exp", [ ("", 0.0, ""), ("", 1.0, ""), ("The man has a brown dog", 0.0, "The man has a brown dog"), ("The man has a brown dog", 1.0, "man has brown dog"), ], ) def test_remove_articles(string...
tests/test_text/test_en/test_word.py
import pytest from niacin.text.en import word @pytest.mark.parametrize( "string,p,exp", [ ("", 0.0, ""), ("", 1.0, ""), ("The man has a brown dog", 0.0, "The man has a brown dog"), ("The man has a brown dog", 1.0, "man has brown dog"), ], ) def test_remove_articles(string...
0.477067
0.71103
import warnings ''' Base environment definitions See docs/api.md for api documentation See docs/dev_docs.md for additional documentation and an example environment. ''' class AECEnv: ''' The AECEnv steps agents one at a time. If you are unsure if you have implemented a AECEnv correctly, try running the ...
pettingzoo/utils/env.py
import warnings ''' Base environment definitions See docs/api.md for api documentation See docs/dev_docs.md for additional documentation and an example environment. ''' class AECEnv: ''' The AECEnv steps agents one at a time. If you are unsure if you have implemented a AECEnv correctly, try running the ...
0.8308
0.51879
import datetime import json import pytest from app import app from app.db_connection import get_db_connection @pytest.fixture() def clean_up(): print("setup") yield print("deleting") docs = [ '2021-06-01_ACT_Estropada-test', '2021-06-01_ARC1_Estropada-test2', '2021-06-02_ARC1_E...
test/test_estropadak.py
import datetime import json import pytest from app import app from app.db_connection import get_db_connection @pytest.fixture() def clean_up(): print("setup") yield print("deleting") docs = [ '2021-06-01_ACT_Estropada-test', '2021-06-01_ARC1_Estropada-test2', '2021-06-02_ARC1_E...
0.266644
0.298137
import os import unittest from test import support spwd = support.import_module('spwd') @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') class TestSpwdRoot(unittest.TestCase): def test_getspall(self): entries = spwd.getspall() se...
Lib/test/test_spwd.py
import os import unittest from test import support spwd = support.import_module('spwd') @unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0, 'root privileges required') class TestSpwdRoot(unittest.TestCase): def test_getspall(self): entries = spwd.getspall() se...
0.428712
0.432243
class MiscellaneousLoads: def anpres(self, nfram="", delay="", ncycl="", refframe="", **kwargs): """Produces an animated sequence of the time-harmonic pressure variation APDL Command: ANPRES of an engine-order excitation in a cyclic harmonic analysis. Parameters ---------- ...
ansys/mapdl/core/_commands/solution/miscellaneous_loads.py
class MiscellaneousLoads: def anpres(self, nfram="", delay="", ncycl="", refframe="", **kwargs): """Produces an animated sequence of the time-harmonic pressure variation APDL Command: ANPRES of an engine-order excitation in a cyclic harmonic analysis. Parameters ---------- ...
0.967
0.835618
import asyncio import logging from collections import OrderedDict import voluptuous as vol from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( DOMAIN, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUP...
homeassistant/components/songpal/media_player.py
import asyncio import logging from collections import OrderedDict import voluptuous as vol from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( DOMAIN, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUP...
0.522689
0.09739
import sys import gym import pybullet_envs import argparse import itertools import collections import copy import time import numpy as np import torch import torch.nn as nn import torch.multiprocessing as mp from tensorboardX import SummaryWriter NOISE_STD = 0.005 POPULATION_SIZE = 2000 PARENTS_COUNT = 10 WORKERS_C...
Chapter20/05_cheetah_ga_batch.py
import sys import gym import pybullet_envs import argparse import itertools import collections import copy import time import numpy as np import torch import torch.nn as nn import torch.multiprocessing as mp from tensorboardX import SummaryWriter NOISE_STD = 0.005 POPULATION_SIZE = 2000 PARENTS_COUNT = 10 WORKERS_C...
0.709724
0.419053
from .test_utils import BaseWrapperTestCase class TestDirtyInput(BaseWrapperTestCase): def test_function_call_with_internal_trailing_comma(self) -> None: self.assertTransform( 1, 8, """ foo('abcd', 1234, spam='ham',) """, """ ...
tests/tests_dirty_input.py
from .test_utils import BaseWrapperTestCase class TestDirtyInput(BaseWrapperTestCase): def test_function_call_with_internal_trailing_comma(self) -> None: self.assertTransform( 1, 8, """ foo('abcd', 1234, spam='ham',) """, """ ...
0.688154
0.47384
from __future__ import unicode_literals import re from boto3 import Session from collections import defaultdict from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core.exceptions import RESTError from moto.cloudformation import cloudformation_backends import datetime import time import uuid import it...
moto/ssm/models.py
from __future__ import unicode_literals import re from boto3 import Session from collections import defaultdict from moto.core import ACCOUNT_ID, BaseBackend, BaseModel from moto.core.exceptions import RESTError from moto.cloudformation import cloudformation_backends import datetime import time import uuid import it...
0.379034
0.071656
import cv2 import numpy as np import os """ ์ด ์Šคํฌ๋ฆฝํŠธ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ์ˆ˜์ง‘ํ•œ ์›๋ณธ ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ฐ์ดํ„ฐ ์ฆ๊ฐ€ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜์—ฌ ๋”ฅ๋Ÿฌ๋‹ ๋ชจ๋ธ์ด ํ•™์Šต ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ์…‹์„ ๋Š˜๋ฆฌ๊ธฐ ์œ„ํ•œ ์Šคํฌ๋ฆฝํŠธ์ด๋‹ค. openCV ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ง์ ‘ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฏธ์ง€ ์ˆ˜์ • ๋ฐ ์ €์žฅ์„ ํ•˜์˜€์œผ๋‚˜, ๋‚˜์ค‘์— ์ฐพ์•„๋ณด๋‹ˆ Keras ์—์„œ๋Š” ImageGenerator๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์œ ์‚ฌํ•œ ์ž‘์—…์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค... ใ…Ž """ TS_PATH = "C:\\Users\\dry8r3ad\\PycharmProjects\\catBreedClassifier\\data\\" TS...
trainingModel/dataAgumentation.py
import cv2 import numpy as np import os """ ์ด ์Šคํฌ๋ฆฝํŠธ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ์ˆ˜์ง‘ํ•œ ์›๋ณธ ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ฐ์ดํ„ฐ ์ฆ๊ฐ€ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜์—ฌ ๋”ฅ๋Ÿฌ๋‹ ๋ชจ๋ธ์ด ํ•™์Šต ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ์…‹์„ ๋Š˜๋ฆฌ๊ธฐ ์œ„ํ•œ ์Šคํฌ๋ฆฝํŠธ์ด๋‹ค. openCV ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ง์ ‘ ์‚ฌ์šฉํ•˜์—ฌ ์ด๋ฏธ์ง€ ์ˆ˜์ • ๋ฐ ์ €์žฅ์„ ํ•˜์˜€์œผ๋‚˜, ๋‚˜์ค‘์— ์ฐพ์•„๋ณด๋‹ˆ Keras ์—์„œ๋Š” ImageGenerator๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์œ ์‚ฌํ•œ ์ž‘์—…์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค... ใ…Ž """ TS_PATH = "C:\\Users\\dry8r3ad\\PycharmProjects\\catBreedClassifier\\data\\" TS...
0.287668
0.530541
from __future__ import unicode_literals from ..utils import int_or_none, parse_iso8601 from .telecinco import TelecincoIE class MiTeleIE(TelecincoIE): IE_DESC = "mitele.es" _VALID_URL = r"https?://(?:www\.)?mitele\.es/(?:[^/]+/)+(?P<id>[^/]+)/player" _TESTS = [ { "url": "http://www.m...
nextdl/extractor/mitele.py
from __future__ import unicode_literals from ..utils import int_or_none, parse_iso8601 from .telecinco import TelecincoIE class MiTeleIE(TelecincoIE): IE_DESC = "mitele.es" _VALID_URL = r"https?://(?:www\.)?mitele\.es/(?:[^/]+/)+(?P<id>[^/]+)/player" _TESTS = [ { "url": "http://www.m...
0.390127
0.214836
from django.shortcuts import render,redirect from .forms import SignupForm,CreateProfile,UploadNewProject from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.generic.edit import CreateView from .models import Profile, Project, Rating from django.contrib.auth...
award_app/views.py
from django.shortcuts import render,redirect from .forms import SignupForm,CreateProfile,UploadNewProject from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.generic.edit import CreateView from .models import Profile, Project, Rating from django.contrib.auth...
0.421433
0.095518
import uuid from glance.api import policy from glance.openstack.common import local class RequestContext(object): """Stores information about the security context. Stores how the user accesses the system, as well as additional request information. """ user_idt_format = '{user} {tenant} {domai...
glance/context.py
import uuid from glance.api import policy from glance.openstack.common import local class RequestContext(object): """Stores information about the security context. Stores how the user accesses the system, as well as additional request information. """ user_idt_format = '{user} {tenant} {domai...
0.752649
0.100392
from django.conf import settings from django.core.management import base from django.utils import timezone from django.contrib.auth.models import Permission, Group from django.contrib.contenttypes.models import ContentType from users.models import PermissionSupport DELIMETER = '\n- ' class Command(base.BaseCommand...
api/users/management/commands/rebuild_permissions.py
from django.conf import settings from django.core.management import base from django.utils import timezone from django.contrib.auth.models import Permission, Group from django.contrib.contenttypes.models import ContentType from users.models import PermissionSupport DELIMETER = '\n- ' class Command(base.BaseCommand...
0.551574
0.101278
import numpy as np import daproli as dp import unittest class TransformerTest(unittest.TestCase): def test_Mapper(self): data = range(100) func = lambda x : x**2 res1 = dp.map(func, data) res2 = dp.Mapper(func).transform(data) self.assertEqual(res1, res2) def test_...
daproli/tests/test_transformer.py
import numpy as np import daproli as dp import unittest class TransformerTest(unittest.TestCase): def test_Mapper(self): data = range(100) func = lambda x : x**2 res1 = dp.map(func, data) res2 = dp.Mapper(func).transform(data) self.assertEqual(res1, res2) def test_...
0.729905
0.845624