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 types import time from pandac.PandaModules import * from direct.distributed.ClockDelta import * from direct.gui.DirectGui import * from pandac.PandaModules import * from direct.interval.IntervalGlobal import ivalMgr from direct.directnotify import DirectNotifyGlobal from direct.distributed import DistributedSmoo...
toontown/distributed/ToontownClientRepository.py
import types import time from pandac.PandaModules import * from direct.distributed.ClockDelta import * from direct.gui.DirectGui import * from pandac.PandaModules import * from direct.interval.IntervalGlobal import ivalMgr from direct.directnotify import DirectNotifyGlobal from direct.distributed import DistributedSmoo...
0.244634
0.059102
from __future__ import absolute_import import json from awkward._v2.types.type import Type import awkward as ak np = ak.nplike.NumpyMetadata.instance() _primitive_to_dtype = { "bool": np.dtype(np.bool_), "int8": np.dtype(np.int8), "uint8": np.dtype(np.uint8), "int16": np.dtype(np.int16), "uint...
src/awkward/_v2/types/numpytype.py
from __future__ import absolute_import import json from awkward._v2.types.type import Type import awkward as ak np = ak.nplike.NumpyMetadata.instance() _primitive_to_dtype = { "bool": np.dtype(np.bool_), "int8": np.dtype(np.int8), "uint8": np.dtype(np.uint8), "int16": np.dtype(np.int16), "uint...
0.73307
0.261357
import os import sys from RLTest import Env from redisgraph import Graph, Node, Edge from base import FlowTestsBase sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../demo/social/') import social_utils redis_graph = None class testIndexScanFlow(FlowTestsBase): def __init__(self): self.e...
tests/flow/test_index_scans.py
import os import sys from RLTest import Env from redisgraph import Graph, Node, Edge from base import FlowTestsBase sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../demo/social/') import social_utils redis_graph = None class testIndexScanFlow(FlowTestsBase): def __init__(self): self.e...
0.490968
0.424233
from rantlib.core_application.ui.window.window import Window from rantlib.core_application.ui.theme import * from rantlib.core_application.ui.runnables.load_themes import LoadThemesRunnable from rantlib.core_application.ui.parts.pg_theme_sample import ThemeSamplePage from PyQt5.QtWidgets import QWidget, QHBoxLayout, QV...
rantlib/core_application/ui/window/theme_tool.py
from rantlib.core_application.ui.window.window import Window from rantlib.core_application.ui.theme import * from rantlib.core_application.ui.runnables.load_themes import LoadThemesRunnable from rantlib.core_application.ui.parts.pg_theme_sample import ThemeSamplePage from PyQt5.QtWidgets import QWidget, QHBoxLayout, QV...
0.528047
0.071949
import errno import select import socket import struct import threading import time from paramiko.common import * from paramiko import util from paramiko.ssh_exception import SSHException, ProxyCommandFailure from paramiko.message import Message try: from r_hmac import HMAC except ImportError: from Crypto.Ha...
.venv/lib/python2.7/site-packages/paramiko/packet.py
import errno import select import socket import struct import threading import time from paramiko.common import * from paramiko import util from paramiko.ssh_exception import SSHException, ProxyCommandFailure from paramiko.message import Message try: from r_hmac import HMAC except ImportError: from Crypto.Ha...
0.563498
0.094552
import argparse import logging from collections import defaultdict from paasta_tools.config_utils import AutoConfigUpdater from paasta_tools.contrib.paasta_update_soa_memcpu import get_report_from_splunk from paasta_tools.utils import DEFAULT_SOA_CONFIGS_GIT_URL from paasta_tools.utils import format_git_url from paast...
paasta_tools/contrib/rightsizer_soaconfigs_update.py
import argparse import logging from collections import defaultdict from paasta_tools.config_utils import AutoConfigUpdater from paasta_tools.contrib.paasta_update_soa_memcpu import get_report_from_splunk from paasta_tools.utils import DEFAULT_SOA_CONFIGS_GIT_URL from paasta_tools.utils import format_git_url from paast...
0.462716
0.100879
import logging import sys from os.path import join from subprocess import CalledProcessError from pkgpanda.util import write_string LOGGING_FORMAT = '[%(asctime)s|%(name)s|%(levelname)s]: %(message)s' logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO) log = logging.getLogger(__name__) def integration_te...
test_util/test_runner.py
import logging import sys from os.path import join from subprocess import CalledProcessError from pkgpanda.util import write_string LOGGING_FORMAT = '[%(asctime)s|%(name)s|%(levelname)s]: %(message)s' logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO) log = logging.getLogger(__name__) def integration_te...
0.404625
0.192046
import struct from bxcommon import constants from bxcommon.messages.abstract_internal_message import AbstractInternalMessage from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage from bxcommon.messages.bloxroute.abstract_broadcast_message import AbstractBroadcastMessage from bxcom...
src/bxcommon/messages/bloxroute/v8/broadcast_message_converter_v8.py
import struct from bxcommon import constants from bxcommon.messages.abstract_internal_message import AbstractInternalMessage from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage from bxcommon.messages.bloxroute.abstract_broadcast_message import AbstractBroadcastMessage from bxcom...
0.5144
0.079531
from __future__ import absolute_import import imp import os import mock from collections import defaultdict import unittest2 from oslo_config import cfg from st2common import config from st2common.util import loader CURRENT_DIR = os.path.dirname(__file__) ST2CONTENT_DIR = os.path.join(CURRENT_DIR, '../fixtures') ...
st2common/tests/unit/test_util_loader.py
from __future__ import absolute_import import imp import os import mock from collections import defaultdict import unittest2 from oslo_config import cfg from st2common import config from st2common.util import loader CURRENT_DIR = os.path.dirname(__file__) ST2CONTENT_DIR = os.path.join(CURRENT_DIR, '../fixtures') ...
0.52074
0.132486
import json import os import random import bottle from bottle import HTTPResponse @bottle.route("/") def index(): return "Your Battlesnake is alive!" @bottle.post("/ping") def ping(): """ Used by the Battlesnake Engine to make sure your snake is still working. """ return HTTPResponse(status=200...
app/server.py
import json import os import random import bottle from bottle import HTTPResponse @bottle.route("/") def index(): return "Your Battlesnake is alive!" @bottle.post("/ping") def ping(): """ Used by the Battlesnake Engine to make sure your snake is still working. """ return HTTPResponse(status=200...
0.558809
0.161883
from unittest import mock import pytest from cumulusci.tasks.push.push_api import BasePushApiObject from cumulusci.tasks.push.push_api import SalesforcePushApi from cumulusci.tasks.push.push_api import memoize, batch_list, MetadataPackage def test_memoize(): def test_func(number): return number memo...
cumulusci/tasks/push/tests/test_push_api.py
from unittest import mock import pytest from cumulusci.tasks.push.push_api import BasePushApiObject from cumulusci.tasks.push.push_api import SalesforcePushApi from cumulusci.tasks.push.push_api import memoize, batch_list, MetadataPackage def test_memoize(): def test_func(number): return number memo...
0.723114
0.580293
import numpy from numpy.testing import assert_array_almost_equal from keras import backend as K from keras.layers import Input, Masking from keras.models import Model from scipy.stats import logistic from deep_qa.layers.tuple_matchers import SlotSimilarityTupleMatcher from deep_qa.tensors.similarity_functions.cosine_s...
tests/layers/tuple_matchers/slot_similarity_tuple_matcher_test.py
import numpy from numpy.testing import assert_array_almost_equal from keras import backend as K from keras.layers import Input, Masking from keras.models import Model from scipy.stats import logistic from deep_qa.layers.tuple_matchers import SlotSimilarityTupleMatcher from deep_qa.tensors.similarity_functions.cosine_s...
0.889721
0.565899
import struct import threading from pixiv_fetcher.utils.log import get_logger from pixiv_fetcher.utils.path import make_direct_open class BaseStrategy(object): def __init__(self, maxsize=None, maxcount=None): self.maxsize = maxsize self.maxcount = maxcount def reset(self, key): rais...
pixiv_fetcher/cache/strategy.py
import struct import threading from pixiv_fetcher.utils.log import get_logger from pixiv_fetcher.utils.path import make_direct_open class BaseStrategy(object): def __init__(self, maxsize=None, maxcount=None): self.maxsize = maxsize self.maxcount = maxcount def reset(self, key): rais...
0.531209
0.114666
from .base_date_time import BaseDateTime # pylint: disable=line-too-long class EnglishDateTime: LangMarker = 'Eng' CheckBothBeforeAfter = False TillRegex = f'(?<till>\\b(to|(un)?till?|thru|through)\\b(\\s+the\\b)?|{BaseDateTime.RangeConnectorSymbolRegex})' RangeConnectorRegex = f'(?<and>\\b(and|throu...
Python/libraries/recognizers-date-time/recognizers_date_time/resources/english_date_time.py
from .base_date_time import BaseDateTime # pylint: disable=line-too-long class EnglishDateTime: LangMarker = 'Eng' CheckBothBeforeAfter = False TillRegex = f'(?<till>\\b(to|(un)?till?|thru|through)\\b(\\s+the\\b)?|{BaseDateTime.RangeConnectorSymbolRegex})' RangeConnectorRegex = f'(?<and>\\b(and|throu...
0.327453
0.370966
import json from alipay.aop.api.constant.ParamConstants import * class MergePayOrder(object): def __init__(self): self._amount = None self._fail_reason = None self._fee = None self._order_id = None self._out_biz_no = None self._payee_display_account = None ...
alipay/aop/api/domain/MergePayOrder.py
import json from alipay.aop.api.constant.ParamConstants import * class MergePayOrder(object): def __init__(self): self._amount = None self._fail_reason = None self._fee = None self._order_id = None self._out_biz_no = None self._payee_display_account = None ...
0.495361
0.061706
import hydra from omegaconf import DictConfig from torch.optim.lr_scheduler import _LRScheduler from torch.optim.lr_scheduler import ReduceLROnPlateau class GradualWarmupScheduler(_LRScheduler): """ Gradually warm-up(increasing) learning rate in optimizer. Proposed in 'Accurate, Large Minibatch SGD: Training...
hyperbox/schedulers/warmup_scheduler.py
import hydra from omegaconf import DictConfig from torch.optim.lr_scheduler import _LRScheduler from torch.optim.lr_scheduler import ReduceLROnPlateau class GradualWarmupScheduler(_LRScheduler): """ Gradually warm-up(increasing) learning rate in optimizer. Proposed in 'Accurate, Large Minibatch SGD: Training...
0.840815
0.276275
__version__ = '0.0.8' # Time-stamp: <2021-09-14T10:47:01Z> ## Language: Japanese/UTF-8 """Simulation Buddhism Prototype No.3 - Death 死亡関連 """ ## ## Author: ## ## JRF ( http://jrf.cocolog-nifty.com/statuses/ (in Japanese)) ## ## License: ## ## The author is a Japanese. ## ## I intended this pro...
simbdp3/death.py
__version__ = '0.0.8' # Time-stamp: <2021-09-14T10:47:01Z> ## Language: Japanese/UTF-8 """Simulation Buddhism Prototype No.3 - Death 死亡関連 """ ## ## Author: ## ## JRF ( http://jrf.cocolog-nifty.com/statuses/ (in Japanese)) ## ## License: ## ## The author is a Japanese. ## ## I intended this pro...
0.33764
0.208803
import unittest from configparser import ConfigParser from os import environ import logging import json import mock from GenomeFileUtil.GenomeFileUtilImpl import GenomeFileUtil, SDKConfig from GenomeFileUtil.GenomeFileUtilServer import MethodContext from GenomeFileUtil.core.GenomeInterface import GenomeInterface from...
test/utility/utils_data_integrity_test.py
import unittest from configparser import ConfigParser from os import environ import logging import json import mock from GenomeFileUtil.GenomeFileUtilImpl import GenomeFileUtil, SDKConfig from GenomeFileUtil.GenomeFileUtilServer import MethodContext from GenomeFileUtil.core.GenomeInterface import GenomeInterface from...
0.193033
0.187114
__author__ = 'stephen' # =============================================================================== # GLOBAL IMPORTS: import os,sys import numpy as np import argparse import time # =============================================================================== # LOCAL IMPORTS: #HK_DataMiner_Path = os.path.relpath(...
hkdataminer/scripts/test_faiss_dbscan_old.py
__author__ = 'stephen' # =============================================================================== # GLOBAL IMPORTS: import os,sys import numpy as np import argparse import time # =============================================================================== # LOCAL IMPORTS: #HK_DataMiner_Path = os.path.relpath(...
0.418222
0.121217
import numpy as np import warnings import copy import numpy as np import numpy.random as ra from astropy import log from astropy.logger import AstropyUserWarning from .utils import njit __all__ = ['Window1D', 'Optimal1D'] class Window1D(object): """ Make a top hat filter (window function) for power spectru...
stingray/filters.py
import numpy as np import warnings import copy import numpy as np import numpy.random as ra from astropy import log from astropy.logger import AstropyUserWarning from .utils import njit __all__ = ['Window1D', 'Optimal1D'] class Window1D(object): """ Make a top hat filter (window function) for power spectru...
0.84039
0.449634
from __future__ import unicode_literals import io from os import path try: from pip.req import parse_requirements except ImportError: # pip >= 10 from pip._internal.req import parse_requirements from setuptools import find_packages, setup def get_requirements(requirements_file): """Use pip to parse...
setup.py
from __future__ import unicode_literals import io from os import path try: from pip.req import parse_requirements except ImportError: # pip >= 10 from pip._internal.req import parse_requirements from setuptools import find_packages, setup def get_requirements(requirements_file): """Use pip to parse...
0.437824
0.104569
import json import logging import ckan.plugins as p try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config log = logging.getLogger(__name__) ignore_empty = p.toolkit.get_validator('ignore_empty') DEFAULT_AGS_FORMATS = ['ags', 'e...
ckanext/agsview/plugin.py
import json import logging import ckan.plugins as p try: # CKAN 2.7 and later from ckan.common import config except ImportError: # CKAN 2.6 and earlier from pylons import config log = logging.getLogger(__name__) ignore_empty = p.toolkit.get_validator('ignore_empty') DEFAULT_AGS_FORMATS = ['ags', 'e...
0.435902
0.162081
# This file provides some classes for setting up (partially-populated) # homeservers; either as a full homeserver as a real application, or a small # partial one for unit test mocking. # Imports required for the default HomeServer() implementation import abc import logging import os from twisted.mail.smtp import se...
synapse/server.py
# This file provides some classes for setting up (partially-populated) # homeservers; either as a full homeserver as a real application, or a small # partial one for unit test mocking. # Imports required for the default HomeServer() implementation import abc import logging import os from twisted.mail.smtp import se...
0.547948
0.095349
import logging from plugwise.exceptions import InvalidAuthentication, PlugwiseException from plugwise.smile import Smile import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.const import ( CONF_BASE, CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, ...
homeassistant/components/plugwise/config_flow.py
import logging from plugwise.exceptions import InvalidAuthentication, PlugwiseException from plugwise.smile import Smile import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.const import ( CONF_BASE, CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, ...
0.68616
0.074332
# Copyright (c) 2016, <NAME> <<EMAIL>> # All rights reserved. import json import interfaces.ckan import datetime license_id_to_name = { "Apache": "Apache License", "Apache-1.0": "Apache License 1.0", "Apache-2.0": "Apache License 2.0", "Artistic": "Artistic License", "Artistic-1.0": "Artistic Lic...
refresh_datajs.py
# Copyright (c) 2016, <NAME> <<EMAIL>> # All rights reserved. import json import interfaces.ckan import datetime license_id_to_name = { "Apache": "Apache License", "Apache-1.0": "Apache License 1.0", "Apache-2.0": "Apache License 2.0", "Artistic": "Artistic License", "Artistic-1.0": "Artistic Lic...
0.516108
0.351728
import rospy import numpy as np from geometry_msgs.msg import Twist, Vector3 from sensor_msgs.msg import LaserScan def converte(valor): return valor*44.4/0.501 def scaneou(dado): #print("Faixa valida: ", dado.range_min , " - ", dado.range_max ) #print("Leituras:") distancias = np.array(dado.ranges) #print(d...
Scripts/desviar.py
import rospy import numpy as np from geometry_msgs.msg import Twist, Vector3 from sensor_msgs.msg import LaserScan def converte(valor): return valor*44.4/0.501 def scaneou(dado): #print("Faixa valida: ", dado.range_min , " - ", dado.range_max ) #print("Leituras:") distancias = np.array(dado.ranges) #print(d...
0.071892
0.39257
import base64 from asyncio import sleep from os import sep, remove, listdir from os.path import isfile, exists from time import strftime, localtime from pagermaid import version from pagermaid.listener import listener from pagermaid.utils import alias_command, execute, pip_install pip_install("pyncm") from mutagen....
neteasedown.py
import base64 from asyncio import sleep from os import sep, remove, listdir from os.path import isfile, exists from time import strftime, localtime from pagermaid import version from pagermaid.listener import listener from pagermaid.utils import alias_command, execute, pip_install pip_install("pyncm") from mutagen....
0.298594
0.077622
### I. Initialisation # Fundamental libraries import os import re import sys import time import glob import random import datetime import warnings import itertools import numpy as np import pandas as pd import pickle as cp import seaborn as sns import multiprocessing from scipy import stats from pathlib import Path fr...
scripts/07b_CPM_compile_metrics.py
### I. Initialisation # Fundamental libraries import os import re import sys import time import glob import random import datetime import warnings import itertools import numpy as np import pandas as pd import pickle as cp import seaborn as sns import multiprocessing from scipy import stats from pathlib import Path fr...
0.564819
0.24262
import os __ALL__ = ["colored", "cprint"] VERSION = (1, 1, 0) ATTRIBUTES = dict( list( zip( [ "bold", "dark", "", "underline", "blink", "", "reverse", "concealed", ...
src/termcolor/termcolor.py
import os __ALL__ = ["colored", "cprint"] VERSION = (1, 1, 0) ATTRIBUTES = dict( list( zip( [ "bold", "dark", "", "underline", "blink", "", "reverse", "concealed", ...
0.459561
0.161287
{ 'target_defaults': { 'defines': [ 'OPJ_STATIC', '_CRT_SECURE_NO_WARNINGS', ], 'msvs_disabled_warnings': [ 4005, 4018, 4146, 4333, 4345, 4267 ], }, 'targets': [ { 'target_name': 'bigint', 'type': 'static_library', 'sources': [ 'bigint/BigInteger.hh...
third_party/third_party.gyp
{ 'target_defaults': { 'defines': [ 'OPJ_STATIC', '_CRT_SECURE_NO_WARNINGS', ], 'msvs_disabled_warnings': [ 4005, 4018, 4146, 4333, 4345, 4267 ], }, 'targets': [ { 'target_name': 'bigint', 'type': 'static_library', 'sources': [ 'bigint/BigInteger.hh...
0.314366
0.098555
import _plotly_utils.basevalidators class IndicatorValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="indicator", parent_name="", **kwargs): super(IndicatorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
validators/_indicator.py
import _plotly_utils.basevalidators class IndicatorValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="indicator", parent_name="", **kwargs): super(IndicatorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
0.868213
0.352313
import math import numpy as np from utils.env_objects import Cylinder, Cube import os class EnvDefs: epuck = ('EPUCK', os.path.abspath('webots_objects/E-puck.wbo')) cylinders = [ # node DEF, node file definition, radius ('Cylinder1', os.path.abspath('webots_objects/Cylinder1.wbo'), 0.05), ...
epuck-nav/controllers/supervisor_controller/environment/__init__.py
import math import numpy as np from utils.env_objects import Cylinder, Cube import os class EnvDefs: epuck = ('EPUCK', os.path.abspath('webots_objects/E-puck.wbo')) cylinders = [ # node DEF, node file definition, radius ('Cylinder1', os.path.abspath('webots_objects/Cylinder1.wbo'), 0.05), ...
0.622459
0.163579
from django.db import models # Staff Detail class StaffDetail(models.Model): Employee_ID = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=50) GENDER_MALE = 'Male' GENDER_FEMALE = 'Female' GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')] gender ...
school_management_system_app/models.py
from django.db import models # Staff Detail class StaffDetail(models.Model): Employee_ID = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=50) GENDER_MALE = 'Male' GENDER_FEMALE = 'Female' GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')] gender ...
0.486088
0.184859
import numpy as np from numba import jit import cv2 import os @jit(cache=True, nopython=True) def compute_errors(image_gt, image_pred): """ Compute Errors from two floating point image. init errors 1. mae 2. rmse 3. inverse mae 4. inverse rmse 5. log mae 6. log rmse 7. scale invaria...
visualDet3D/evaluator/kitti_depth_prediction/evaluate_depth.py
import numpy as np from numba import jit import cv2 import os @jit(cache=True, nopython=True) def compute_errors(image_gt, image_pred): """ Compute Errors from two floating point image. init errors 1. mae 2. rmse 3. inverse mae 4. inverse rmse 5. log mae 6. log rmse 7. scale invaria...
0.482429
0.430447
import ctypes as ct import math import pdb _ConvNet = ct.cdll.LoadLibrary('libcudamat_conv_gemm.so') def DivUp(a, b): return (a + b - 1) / b def AddAtAllLocs(h, b): batch_size, size_x, size_y, num_channels = h.shape4d b_shape = b.shape h.reshape((-1, num_channels)) b.reshape((1, -1)) assert b.shape[1] == ...
cudamat/cudamat_conv_gemm.py
import ctypes as ct import math import pdb _ConvNet = ct.cdll.LoadLibrary('libcudamat_conv_gemm.so') def DivUp(a, b): return (a + b - 1) / b def AddAtAllLocs(h, b): batch_size, size_x, size_y, num_channels = h.shape4d b_shape = b.shape h.reshape((-1, num_channels)) b.reshape((1, -1)) assert b.shape[1] == ...
0.51879
0.601535
from decimal import Decimal from pathlib import Path from typing import Callable, Dict, Tuple, List, Any from srctools import FileSystem, VMF, Output, Entity, FGD from srctools.bsp import BSP from srctools.logger import get_logger from srctools.packlist import PackList from srctools.game import Game LOGGER = get_log...
srctools/bsp_transform/__init__.py
from decimal import Decimal from pathlib import Path from typing import Callable, Dict, Tuple, List, Any from srctools import FileSystem, VMF, Output, Entity, FGD from srctools.bsp import BSP from srctools.logger import get_logger from srctools.packlist import PackList from srctools.game import Game LOGGER = get_log...
0.771672
0.187877
Case Type : 服务端工具 Case Name : set 方式设置认证参数:HOSTTYPE DATABASE USERNAME IPADDR IPMASK Description : 1.设置认证参数 2.设置认证参数 3.重启数据库 4.查看是否设置成功 5.注释已经设置的客户端认证策略 6.重启数据库 Expect : 1.设置失败 2.设置完成 3.重启成功 4.设置成功 5.注释成功 6.重启成功 History : """ import unittest from yat.test imp...
openGaussBase/testcase/TOOLS/SERVER_TOOLS/gs_guc/Opengauss_Function_Tools_gs_guc_Case0026.py
Case Type : 服务端工具 Case Name : set 方式设置认证参数:HOSTTYPE DATABASE USERNAME IPADDR IPMASK Description : 1.设置认证参数 2.设置认证参数 3.重启数据库 4.查看是否设置成功 5.注释已经设置的客户端认证策略 6.重启数据库 Expect : 1.设置失败 2.设置完成 3.重启成功 4.设置成功 5.注释成功 6.重启成功 History : """ import unittest from yat.test imp...
0.204421
0.358746
import argparse import os from decouple import config from rasa.core.nlg import TemplatedNaturalLanguageGenerator, NaturalLanguageGenerator from rasa.utils.endpoints import EndpointConfig from sanic import Sanic, response from rasa.constants import ENV_SANIC_BACKLOG, DEFAULT_SANIC_WORKERS import logging from rasa.shar...
server.py
import argparse import os from decouple import config from rasa.core.nlg import TemplatedNaturalLanguageGenerator, NaturalLanguageGenerator from rasa.utils.endpoints import EndpointConfig from sanic import Sanic, response from rasa.constants import ENV_SANIC_BACKLOG, DEFAULT_SANIC_WORKERS import logging from rasa.shar...
0.356447
0.078325
from collections import defaultdict from rqalpha.utils.i18n import gettext as _ from rqalpha.const import ORDER_TYPE, SIDE, BAR_STATUS from rqalpha.model.trade import Trade from rqalpha.environment import Environment from rqalpha.events import EVENT class Matcher(object): def __init__(self, dea...
engine/matcher.py
from collections import defaultdict from rqalpha.utils.i18n import gettext as _ from rqalpha.const import ORDER_TYPE, SIDE, BAR_STATUS from rqalpha.model.trade import Trade from rqalpha.environment import Environment from rqalpha.events import EVENT class Matcher(object): def __init__(self, dea...
0.628521
0.188641
import sys import json from subprocess import Popen, PIPE try: import yaml except ImportError: print('Unable to import YAML module: please install PyYAML', file=sys.stderr) sys.exit(1) class Reporter(object): """Collect and report errors.""" def __init__(self): """Constructor.""" ...
bin/util.py
import sys import json from subprocess import Popen, PIPE try: import yaml except ImportError: print('Unable to import YAML module: please install PyYAML', file=sys.stderr) sys.exit(1) class Reporter(object): """Collect and report errors.""" def __init__(self): """Constructor.""" ...
0.325413
0.279901
import os.path import qprompt from cosmic_ray.config import ConfigDict from cosmic_ray.plugins import execution_engine_names MODULE_PATH_HELP = """The path to the module that will be mutated. If this is a package (as opposed to a single file module), then all modules in the package and its subpackages will be muta...
src/cosmic_ray/commands/new_config.py
import os.path import qprompt from cosmic_ray.config import ConfigDict from cosmic_ray.plugins import execution_engine_names MODULE_PATH_HELP = """The path to the module that will be mutated. If this is a package (as opposed to a single file module), then all modules in the package and its subpackages will be muta...
0.529263
0.318803
import os import json from functools import partial from http.server import SimpleHTTPRequestHandler , test from http import HTTPStatus ENCODING = "utf-8" UPLOAD_DIR = "upload" CONTENT_TYPE_FORM = "multipart/form-data" CONTENT_TYPE_RAW_JSON = "application/json" class CustomRequestHandler(SimpleHTTPRequestHandler): ...
simpleFtp.py
import os import json from functools import partial from http.server import SimpleHTTPRequestHandler , test from http import HTTPStatus ENCODING = "utf-8" UPLOAD_DIR = "upload" CONTENT_TYPE_FORM = "multipart/form-data" CONTENT_TYPE_RAW_JSON = "application/json" class CustomRequestHandler(SimpleHTTPRequestHandler): ...
0.328529
0.055823
import json import re from wtforms import StringField from wtforms.validators import DataRequired, ValidationError from app.validators.base import NotRequiredDateTimeForm class CreateProblemSetForm(NotRequiredDateTimeForm): name = StringField(validators=[DataRequired(message='Problem set name cannot be empty')]...
app/validators/problem_set.py
import json import re from wtforms import StringField from wtforms.validators import DataRequired, ValidationError from app.validators.base import NotRequiredDateTimeForm class CreateProblemSetForm(NotRequiredDateTimeForm): name = StringField(validators=[DataRequired(message='Problem set name cannot be empty')]...
0.298491
0.073132
import os import pytest import yaml import re import requests from kiali import KialiClient from utils.command_exec import command_exec from pkg_resources import resource_string from urllib.request import urlopen CONFIG_PATH = '../config' ENV_FILE = CONFIG_PATH + '/env.yaml' ASSETS_PATH = os.path.join(os.path.dirname(...
tests/e2e/tests/conftest.py
import os import pytest import yaml import re import requests from kiali import KialiClient from utils.command_exec import command_exec from pkg_resources import resource_string from urllib.request import urlopen CONFIG_PATH = '../config' ENV_FILE = CONFIG_PATH + '/env.yaml' ASSETS_PATH = os.path.join(os.path.dirname(...
0.237399
0.040846
from msrest.serialization import Model class AccountSasParameters(Model): """The parameters to list SAS credentials of a storage account. :param services: The signed services accessible with the account SAS. Possible values include: Blob (b), Queue (q), Table (t), File (f). Possible values include...
azure-mgmt-storage/azure/mgmt/storage/v2017_10_01/models/account_sas_parameters.py
from msrest.serialization import Model class AccountSasParameters(Model): """The parameters to list SAS credentials of a storage account. :param services: The signed services accessible with the account SAS. Possible values include: Blob (b), Queue (q), Table (t), File (f). Possible values include...
0.878939
0.400192
from copy import deepcopy from typing import Any, Dict, List, Tuple, Union from torch import nn from torchmetrics.metric import Metric class MetricCollection(nn.ModuleDict): """ MetricCollection class can be used to chain metrics that have the same call pattern into one single class. Args: ...
torchmetrics/collections.py
from copy import deepcopy from typing import Any, Dict, List, Tuple, Union from torch import nn from torchmetrics.metric import Metric class MetricCollection(nn.ModuleDict): """ MetricCollection class can be used to chain metrics that have the same call pattern into one single class. Args: ...
0.960398
0.510985
import tensorflow.compat.v2 as tf from keras import backend from keras.layers.pooling.base_global_pooling1d import GlobalPooling1D # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export( "keras.layers.GlobalAveragePooling1D", "keras.layers.GlobalAvgPool1D" ) class GlobalAveragePool...
keras/layers/pooling/global_average_pooling1d.py
import tensorflow.compat.v2 as tf from keras import backend from keras.layers.pooling.base_global_pooling1d import GlobalPooling1D # isort: off from tensorflow.python.util.tf_export import keras_export @keras_export( "keras.layers.GlobalAveragePooling1D", "keras.layers.GlobalAvgPool1D" ) class GlobalAveragePool...
0.962497
0.622431
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_in...
gen/pb_python/flyteidl/plugins/spark_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_in...
0.229018
0.136493
import numpy as np from scipy import linalg from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_array from utils_wpca import check_array_with_weights, weighted_mean class WPCA(BaseEstimator, TransformerMixin): """Weighted Principal Component Analysis Parameter...
wpca.py
import numpy as np from scipy import linalg from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_array from utils_wpca import check_array_with_weights, weighted_mean class WPCA(BaseEstimator, TransformerMixin): """Weighted Principal Component Analysis Parameter...
0.878295
0.646711
import abc from collections import defaultdict import networkx as nx from aizynthfinder.chem import ( Molecule, UniqueMolecule, FixedRetroReaction, hash_reactions, ) from aizynthfinder.utils.image import make_visjs_page class _ReactionTreeLoader(abc.ABC): """ Base class for classes that creates ...
aizynthfinder/utils/analysis_helpers.py
import abc from collections import defaultdict import networkx as nx from aizynthfinder.chem import ( Molecule, UniqueMolecule, FixedRetroReaction, hash_reactions, ) from aizynthfinder.utils.image import make_visjs_page class _ReactionTreeLoader(abc.ABC): """ Base class for classes that creates ...
0.779616
0.362913
import sys import time import os import re import requests import json import numpy as np import matplotlib.pyplot as plt domain = "https://qiita.com" username = "" token = "" def check_domain_valid(domain: str): regex = "^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$" return True if re.match(regex...
getqiitainfo.py
import sys import time import os import re import requests import json import numpy as np import matplotlib.pyplot as plt domain = "https://qiita.com" username = "" token = "" def check_domain_valid(domain: str): regex = "^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$" return True if re.match(regex...
0.196749
0.217753
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE """ Base class defining the interface for a printer. """ from abc import ABC, abstractmethod from enum import Enum from typing import List, NamedTuple, Optional from astro...
Lib/site-packages/pylint/pyreverse/printer.py
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE """ Base class defining the interface for a printer. """ from abc import ABC, abstractmethod from enum import Enum from typing import List, NamedTuple, Optional from astro...
0.969368
0.272572
import os import csv from pylab import * from numpy import * from loadData import loadData from mymath import statistic, revcumsum from random import sample as spl #sim N = 200000 # number of users t0 = 500 # initial time for observation T = t0 +320 P = [0.52] # probability of joining a banned group mxP = 2 # maximum c...
survival/lifespan-bannedsimVsdata.py
import os import csv from pylab import * from numpy import * from loadData import loadData from mymath import statistic, revcumsum from random import sample as spl #sim N = 200000 # number of users t0 = 500 # initial time for observation T = t0 +320 P = [0.52] # probability of joining a banned group mxP = 2 # maximum c...
0.154089
0.279203
from __future__ import annotations from typing import TYPE_CHECKING, Any import logging import random from pajbot.models.command import Command, CommandExample from pajbot.modules import BaseModule, ModuleSetting from pajbot.modules.basic import BasicCommandsModule if TYPE_CHECKING: from pajbot.bot import Bot ...
pajbot/modules/basic/selftimeout.py
from __future__ import annotations from typing import TYPE_CHECKING, Any import logging import random from pajbot.models.command import Command, CommandExample from pajbot.modules import BaseModule, ModuleSetting from pajbot.modules.basic import BasicCommandsModule if TYPE_CHECKING: from pajbot.bot import Bot ...
0.826467
0.131006
import contextlib import enum import socket import uuid import weakref from typing import Any, Mapping, Optional, Sequence try: from pymongocrypt.auto_encrypter import AutoEncrypter from pymongocrypt.errors import MongoCryptError # noqa: F401 from pymongocrypt.explicit_encrypter import ExplicitEncrypter ...
pymongo/encryption.py
import contextlib import enum import socket import uuid import weakref from typing import Any, Mapping, Optional, Sequence try: from pymongocrypt.auto_encrypter import AutoEncrypter from pymongocrypt.errors import MongoCryptError # noqa: F401 from pymongocrypt.explicit_encrypter import ExplicitEncrypter ...
0.749821
0.099602
# New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Traditional Chinese language mappings for language-...
selenium/src/py/lib/docutils/parsers/rst/languages/zh_tw.py
# New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language: one in docutils/languages, the other in # docutils/parsers/rst/languages. """ Traditional Chinese language mappings for language-...
0.536556
0.097305
from PySide6 import QtCore, QtGui, QtWidgets, QtXml class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.xbelTree = XbelTree() self.setCentralWidget(self.xbelTree) self.createActions() self.createMenus() ...
venv/Lib/site-packages/PySide6/examples/xml/dombookmarks/dombookmarks.py
from PySide6 import QtCore, QtGui, QtWidgets, QtXml class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.xbelTree = XbelTree() self.setCentralWidget(self.xbelTree) self.createActions() self.createMenus() ...
0.431464
0.055952
import pytest from httpx import URL, Origin from httpx.exceptions import InvalidURL @pytest.mark.parametrize( "given,idna,host,scheme,port", [ ( "http://中国.icom.museum:80/", "http://xn--fiqs8s.icom.museum:80/", "xn--fiqs8s.icom.museum", "http", ...
tests/models/test_url.py
import pytest from httpx import URL, Origin from httpx.exceptions import InvalidURL @pytest.mark.parametrize( "given,idna,host,scheme,port", [ ( "http://中国.icom.museum:80/", "http://xn--fiqs8s.icom.museum:80/", "xn--fiqs8s.icom.museum", "http", ...
0.46393
0.477311
from __future__ import division, print_function, absolute_import import pickle import shutil import os.path as osp import warnings from functools import partial from collections import OrderedDict import torch import torch.nn as nn from .tools import mkdir_if_missing __all__ = [ 'save_checkpoint', 'load_checkpoin...
torchreid/utils/torchtools.py
from __future__ import division, print_function, absolute_import import pickle import shutil import os.path as osp import warnings from functools import partial from collections import OrderedDict import torch import torch.nn as nn from .tools import mkdir_if_missing __all__ = [ 'save_checkpoint', 'load_checkpoin...
0.864896
0.156137
import matplotlib matplotlib.use('Agg') from typing import Any, AnyStr from matplotlib.figure import Figure from datetime import datetime from matplotlib.pyplot import title from experiment_automator.constants import ExperimentConstants, SlackConstants from textwrap import wrap class ResultContainer(dict): def ...
experiment_automator/result_container.py
import matplotlib matplotlib.use('Agg') from typing import Any, AnyStr from matplotlib.figure import Figure from datetime import datetime from matplotlib.pyplot import title from experiment_automator.constants import ExperimentConstants, SlackConstants from textwrap import wrap class ResultContainer(dict): def ...
0.5083
0.229665
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://res2net101_v1d_26w_4s', backbone=dict( type='Res2Net', depth=101, scales=4, base_width=26, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, no...
configs/vfnet/vfnet_r2_101_fpn_mdconv_c3-c5_mstrain_2x_coco_cate2.py
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py' model = dict( pretrained='open-mmlab://res2net101_v1d_26w_4s', backbone=dict( type='Res2Net', depth=101, scales=4, base_width=26, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, no...
0.430985
0.160661
import datetime from pandas import DataFrame from tests.utils import NormTestCase class PythonTestCase(NormTestCase): def test_python_declaration(self): script = """ test := {{ from datetime import datetime test = datetime.utcnow }}; """ self.exec...
tests/python_tests.py
import datetime from pandas import DataFrame from tests.utils import NormTestCase class PythonTestCase(NormTestCase): def test_python_declaration(self): script = """ test := {{ from datetime import datetime test = datetime.utcnow }}; """ self.exec...
0.612541
0.544559
import logging from typing import Iterator, Dict import torch from torch.optim import SGD from torch.optim.optimizer import Optimizer from tqdm import tqdm from forte.common.configuration import Config from forte.data import BaseExtractor from forte.data.data_pack import DataPack from forte.data.readers.conll03_read...
examples/tagging/tagging_trainer.py
import logging from typing import Iterator, Dict import torch from torch.optim import SGD from torch.optim.optimizer import Optimizer from tqdm import tqdm from forte.common.configuration import Config from forte.data import BaseExtractor from forte.data.data_pack import DataPack from forte.data.readers.conll03_read...
0.876463
0.130452
from datetime import date from django.test import TestCase from django.core.exceptions import ValidationError from django.conf import settings from django.contrib.contenttypes.models import ContentType import time_machine from nautobot.dcim.models import DeviceType, Manufacturer, Platform from nautobot.extras.choices...
nautobot_device_lifecycle_mgmt/tests/test_model.py
from datetime import date from django.test import TestCase from django.core.exceptions import ValidationError from django.conf import settings from django.contrib.contenttypes.models import ContentType import time_machine from nautobot.dcim.models import DeviceType, Manufacturer, Platform from nautobot.extras.choices...
0.758511
0.21712
import argparse import json import logging import lib.db as db import lib.logs as logs MAPPINGS = { 'problemCategoryAlgorithmAndNetworkOptimization': 'problemLevelIntermediateAnalysisAndDesignOfAlgorithms', 'problemCategoryCompetitiveProgramming': 'problemLevelAdvancedCompetitiveProgramming', ...
stuff/standardize_tags.py
import argparse import json import logging import lib.db as db import lib.logs as logs MAPPINGS = { 'problemCategoryAlgorithmAndNetworkOptimization': 'problemLevelIntermediateAnalysisAndDesignOfAlgorithms', 'problemCategoryCompetitiveProgramming': 'problemLevelAdvancedCompetitiveProgramming', ...
0.466846
0.127354
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://assets-cdn.github.com"> <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com"> <link rel="dns-prefetch" href="https...
scraping/extract_course_info_from_json_resp.py
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://assets-cdn.github.com"> <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com"> <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com"> <link rel="dns-prefetch" href="https...
0.424293
0.151184
# Quick notebook to prepae examples (not the tfrecord kind) from Project Gutenborgs Bible text # In[1]: import re # In[2]: txt = open('./pg10.txt').read() # In[3]: split_reg = re.compile('\n{4}') # # split the raw text of the bible into books # In[4]: books = split_reg.split(txt) # In[5]: books = b...
PrepareBibleExamples.py
# Quick notebook to prepae examples (not the tfrecord kind) from Project Gutenborgs Bible text # In[1]: import re # In[2]: txt = open('./pg10.txt').read() # In[3]: split_reg = re.compile('\n{4}') # # split the raw text of the bible into books # In[4]: books = split_reg.split(txt) # In[5]: books = b...
0.44071
0.606324
from brownie import * from brownie.network.contract import InterfaceContainer import json import csv def main(): global contracts, acct thisNetwork = network.show_active() # == Load config ====================================================================================================================...
scripts/deployment/distribution/create_vesting_migrations.py
from brownie import * from brownie.network.contract import InterfaceContainer import json import csv def main(): global contracts, acct thisNetwork = network.show_active() # == Load config ====================================================================================================================...
0.431105
0.10307
from random import randrange from typing import List, Tuple PointType = Tuple[int, int] VectorType = PointType SeaType = Tuple[List[int], ...] SEA_WIDTH = 6 DESTROYER_LENGTH = 2 CRUISER_LENGTH = 3 AIRCRAFT_CARRIER_LENGTH = 4 def random_vector() -> Tuple[int, int]: while True: vector = (randrange(-1, 2),...
09_Battle/python/battle.py
from random import randrange from typing import List, Tuple PointType = Tuple[int, int] VectorType = PointType SeaType = Tuple[List[int], ...] SEA_WIDTH = 6 DESTROYER_LENGTH = 2 CRUISER_LENGTH = 3 AIRCRAFT_CARRIER_LENGTH = 4 def random_vector() -> Tuple[int, int]: while True: vector = (randrange(-1, 2),...
0.672547
0.639567
import os import platform from setuptools import ( find_packages, setup, ) py_version = platform.python_version() PACKAGE_VERSION = '3.1.5' EXTRAS_REQUIRE = { 'tester': [ 'coverage', 'pep8', 'pyflakes', 'pylint', 'pytest-cov' ], 'docs': [ "mock", ...
setup.py
import os import platform from setuptools import ( find_packages, setup, ) py_version = platform.python_version() PACKAGE_VERSION = '3.1.5' EXTRAS_REQUIRE = { 'tester': [ 'coverage', 'pep8', 'pyflakes', 'pylint', 'pytest-cov' ], 'docs': [ "mock", ...
0.24963
0.252724
__author__ = '<NAME> @MadMax93' import matplotlib.dates as mdates import matplotlib.pyplot as plt import numpy as np import scipy.signal as signal import peakutils import matplotlib.gridspec as gridspec from peakutils.plot import plot as pplot from matplotlib.offsetbox import AnchoredText class Visualization(object)...
Code/Visualization.py
__author__ = '<NAME> @MadMax93' import matplotlib.dates as mdates import matplotlib.pyplot as plt import numpy as np import scipy.signal as signal import peakutils import matplotlib.gridspec as gridspec from peakutils.plot import plot as pplot from matplotlib.offsetbox import AnchoredText class Visualization(object)...
0.670393
0.682389
from __future__ import absolute_import import six from thrift.util.Recursive import fix_spec from thrift.Thrift import * from thrift.protocol.TProtocol import TProtocolException import pprint import warnings from thrift import Thrift from thrift.transport import TTransport from thrift.protocol import TBinaryProtoco...
thrift/compiler/test/fixtures/constants/gen-py/module/ttypes.py
from __future__ import absolute_import import six from thrift.util.Recursive import fix_spec from thrift.Thrift import * from thrift.protocol.TProtocol import TProtocolException import pprint import warnings from thrift import Thrift from thrift.transport import TTransport from thrift.protocol import TBinaryProtoco...
0.383988
0.105902
from flask import request from flask_restful import Resource from flask_jwt_extended import jwt_required from {{cookiecutter.app_name}}.models import User from {{cookiecutter.app_name}}.extensions import ma, db from {{cookiecutter.app_name}}.commons.pagination import paginate class UserSchema(ma.ModelSchema): i...
{{cookiecutter.project_name}}/{{cookiecutter.app_name}}/api/resources/user.py
from flask import request from flask_restful import Resource from flask_jwt_extended import jwt_required from {{cookiecutter.app_name}}.models import User from {{cookiecutter.app_name}}.extensions import ma, db from {{cookiecutter.app_name}}.commons.pagination import paginate class UserSchema(ma.ModelSchema): i...
0.619471
0.089733
import asyncio import json from asyncio import Event from typing import Optional, Union, Dict, Any, Tuple, TYPE_CHECKING from aiohttp import FormData, WSMsgType, WebSocketError from arclet.edoves.main.server_docker import BaseServerDocker, DockerBehavior, BaseDockerMetaComponent from arclet.edoves.main.network import N...
arclet/edoves/mah/server_docker.py
import asyncio import json from asyncio import Event from typing import Optional, Union, Dict, Any, Tuple, TYPE_CHECKING from aiohttp import FormData, WSMsgType, WebSocketError from arclet.edoves.main.server_docker import BaseServerDocker, DockerBehavior, BaseDockerMetaComponent from arclet.edoves.main.network import N...
0.595845
0.110904
import numpy as np import cvxpy as cp from cvxpy.error import SolverError from cvxpy.tests.base_test import BaseTest class TestSupportFunctions(BaseTest): """ Test the implementation of support function atoms. Relevant source code includes: cvxpy.atoms.suppfunc cvxpy.transforms.suppfunc ...
cvxpy/tests/test_suppfunc.py
import numpy as np import cvxpy as cp from cvxpy.error import SolverError from cvxpy.tests.base_test import BaseTest class TestSupportFunctions(BaseTest): """ Test the implementation of support function atoms. Relevant source code includes: cvxpy.atoms.suppfunc cvxpy.transforms.suppfunc ...
0.645679
0.745676
import argparse import ast import traceback from typing import List from typing import NamedTuple from typing import Optional from typing import Sequence DEBUG_STATEMENTS = { 'ipdb', 'pdb', 'pdbr', 'pudb', 'pydevd_pycharm', 'q', 'rdb', 'rpdb', 'wdb', } class Debug(NamedTuple): ...
pre_commit_hooks/debug_statement_hook.py
import argparse import ast import traceback from typing import List from typing import NamedTuple from typing import Optional from typing import Sequence DEBUG_STATEMENTS = { 'ipdb', 'pdb', 'pdbr', 'pudb', 'pydevd_pycharm', 'q', 'rdb', 'rpdb', 'wdb', } class Debug(NamedTuple): ...
0.606149
0.146087
import magma as m import mantle def define_simple_circuit(T, circ_name, has_clk=False): class _Circuit(m.Circuit): __test__ = False # Disable pytest discovery name = circ_name IO = ["I", m.In(T), "O", m.Out(T)] if has_clk: IO += ["CLK", m.In(m.Clock)] @classm...
tests/common.py
import magma as m import mantle def define_simple_circuit(T, circ_name, has_clk=False): class _Circuit(m.Circuit): __test__ = False # Disable pytest discovery name = circ_name IO = ["I", m.In(T), "O", m.Out(T)] if has_clk: IO += ["CLK", m.In(m.Clock)] @classm...
0.511717
0.629689
import firebase_admin from firebase_admin import db from firebase_admin import credentials import datetime from time import sleep import codecs from ghsTools import ghsTools import database import mail from utils import datetime_utils from utils.generic import clear_output def main(): """Runs the main program ...
serverMonitor/main.py
import firebase_admin from firebase_admin import db from firebase_admin import credentials import datetime from time import sleep import codecs from ghsTools import ghsTools import database import mail from utils import datetime_utils from utils.generic import clear_output def main(): """Runs the main program ...
0.329284
0.077588
import copy from quant import const from quant.error import Error from quant.utils import logger from quant.tasks import SingleTask from quant.order import ORDER_TYPE_LIMIT from quant.order import Order from quant.position import Position from quant.event import EventOrder class Trade: """ Trade Module. Att...
quant/trade.py
import copy from quant import const from quant.error import Error from quant.utils import logger from quant.tasks import SingleTask from quant.order import ORDER_TYPE_LIMIT from quant.order import Order from quant.position import Position from quant.event import EventOrder class Trade: """ Trade Module. Att...
0.854824
0.155976
from jnius import autoclass import re import io from PIL import Image from parsers.contenttypeanalyzer import ContentTypeAnalyzer from parsers.ocrproxy import OCRProxy, OCRProxyResponse from parsers.fileparserresponse import FileParserResponse from parsers.binarystringparser import BinaryStringParser class TikaParser:...
Pipeline/parsers/tikaparser.py
from jnius import autoclass import re import io from PIL import Image from parsers.contenttypeanalyzer import ContentTypeAnalyzer from parsers.ocrproxy import OCRProxy, OCRProxyResponse from parsers.fileparserresponse import FileParserResponse from parsers.binarystringparser import BinaryStringParser class TikaParser:...
0.429908
0.080538
from __future__ import absolute_import, division, print_function, unicode_literals import argparse import functools import glob import os import re import sys from concurrent.futures import ProcessPoolExecutor import setuptools from isort import SortImports, __version__ from isort.settings import DEFAULT_SECTIONS, d...
isort/main.py
from __future__ import absolute_import, division, print_function, unicode_literals import argparse import functools import glob import os import re import sys from concurrent.futures import ProcessPoolExecutor import setuptools from isort import SortImports, __version__ from isort.settings import DEFAULT_SECTIONS, d...
0.429669
0.239227
import random from django.core.exceptions import ValidationError from django.db import models from django import forms from staging.generators import BaseGenerator class RandomObjectFilterForm(forms.Form): filter_name = forms.CharField(label=u'queryset filter name', required=False) filter_value = forms.CharFi...
staging/generators/random_object.py
import random from django.core.exceptions import ValidationError from django.db import models from django import forms from staging.generators import BaseGenerator class RandomObjectFilterForm(forms.Form): filter_name = forms.CharField(label=u'queryset filter name', required=False) filter_value = forms.CharFi...
0.370795
0.138055
import os import time from tensorboard.compat.proto import event_pb2 from tensorboard.compat.proto.config_pb2 import RunMetadata from tensorboard.compat.proto.event_pb2 import Event, SessionLog from tensorboard.compat.proto.graph_pb2 import GraphDef from tensorboard.compat.proto.step_stats_pb2 import DeviceStepStats,...
nnabla_nas/utils/tensorboard/writer.py
import os import time from tensorboard.compat.proto import event_pb2 from tensorboard.compat.proto.config_pb2 import RunMetadata from tensorboard.compat.proto.event_pb2 import Event, SessionLog from tensorboard.compat.proto.graph_pb2 import GraphDef from tensorboard.compat.proto.step_stats_pb2 import DeviceStepStats,...
0.888221
0.265299
from __future__ import absolute_import import logging logger = logging.getLogger(__name__) import re from django.core.exceptions import (ImproperlyConfigured, ObjectDoesNotExist, ValidationError as DjValidationError) from django.core.validators import (slug_re, comma_separated_int_...
spyne/util/django.py
from __future__ import absolute_import import logging logger = logging.getLogger(__name__) import re from django.core.exceptions import (ImproperlyConfigured, ObjectDoesNotExist, ValidationError as DjValidationError) from django.core.validators import (slug_re, comma_separated_int_...
0.761627
0.102844
import datetime import click import psycopg2 from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server.TServer import TThreadPoolServer from gen_auth.auth import TAuthService from gen_auth.auth.ttypes import TAccount, TInvalidCredential...
WISEServices/auth/src/py/server.py
import datetime import click import psycopg2 from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server.TServer import TThreadPoolServer from gen_auth.auth import TAuthService from gen_auth.auth.ttypes import TAccount, TInvalidCredential...
0.384797
0.058453
import argparse import signal import os import sys import time import pyinotify import requests import base64 import json import fnmatch import time def now(): return(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))) def signalHandler(signum, frame): print "%s : sprinkler.py receive signal %d" ...
root/usr/local/bin/sprinkler.py
import argparse import signal import os import sys import time import pyinotify import requests import base64 import json import fnmatch import time def now(): return(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))) def signalHandler(signum, frame): print "%s : sprinkler.py receive signal %d" ...
0.115923
0.075142
try: from setuptools import setup except ImportError: from distutils.core import setup for line in open("qimage2ndarray/__init__.py"): if line.startswith("__version__"): exec(line) setup(name = 'qimage2ndarray', version = __version__, description = 'Conversion between QImages and numpy...
setup.py
try: from setuptools import setup except ImportError: from distutils.core import setup for line in open("qimage2ndarray/__init__.py"): if line.startswith("__version__"): exec(line) setup(name = 'qimage2ndarray', version = __version__, description = 'Conversion between QImages and numpy...
0.626353
0.386879
import os import random from collections import deque import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader import numpy as np from sklearn.metrics import f1_score, precision_recall_curve import matplotlib.pyplot as plt import g...
code/modules/clustering_module.py
import os import random from collections import deque import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader import numpy as np from sklearn.metrics import f1_score, precision_recall_curve import matplotlib.pyplot as plt import g...
0.776029
0.33112
from ykdl.util.html import get_content, add_header from ykdl.util.match import match1, matchall from ykdl.extractor import VideoExtractor from ykdl.videoinfo import VideoInfo from ykdl.compact import urlencode from .util import get_h5enc, ub98484234 import json douyu_match_pattern = [ 'class="hroom_id" value="([^"...
ykdl/extractors/douyu/live.py
from ykdl.util.html import get_content, add_header from ykdl.util.match import match1, matchall from ykdl.extractor import VideoExtractor from ykdl.videoinfo import VideoInfo from ykdl.compact import urlencode from .util import get_h5enc, ub98484234 import json douyu_match_pattern = [ 'class="hroom_id" value="([^"...
0.412885
0.206774
import datetime import mock from keystoneclient import access from keystoneclient import httpclient from keystoneclient.openstack.common import timeutils from keystoneclient.tests import utils from keystoneclient.tests.v2_0 import client_fixtures try: import keyring # noqa import pickle # noqa except Impo...
keystoneclient/tests/test_keyring.py
import datetime import mock from keystoneclient import access from keystoneclient import httpclient from keystoneclient.openstack.common import timeutils from keystoneclient.tests import utils from keystoneclient.tests.v2_0 import client_fixtures try: import keyring # noqa import pickle # noqa except Impo...
0.558086
0.14072
from PIL import Image import ass from datetime import timedelta import sys doc = ass.document.Document() SCALE = 2 DPI = 72 doc.styles.append(ass.document.Style( name="Default", shadow=0, outline=0, alignment=7, bold=False, margin_l=int(1.25 * DPI * SCALE), margin_r=int(1.25 * DPI * SCAL...
renderer_test.py
from PIL import Image import ass from datetime import timedelta import sys doc = ass.document.Document() SCALE = 2 DPI = 72 doc.styles.append(ass.document.Style( name="Default", shadow=0, outline=0, alignment=7, bold=False, margin_l=int(1.25 * DPI * SCALE), margin_r=int(1.25 * DPI * SCAL...
0.184473
0.111193
import json from os.path import join from twisted.trial import unittest from twisted.internet.defer import inlineCallbacks from twisted.web.server import Site from twisted.web.static import File from twisted.internet import reactor from slyd.bot import create_bot_resource from .utils import TestSite, test_spec_manager ...
slyd/tests/test_bot.py
import json from os.path import join from twisted.trial import unittest from twisted.internet.defer import inlineCallbacks from twisted.web.server import Site from twisted.web.static import File from twisted.internet import reactor from slyd.bot import create_bot_resource from .utils import TestSite, test_spec_manager ...
0.385259
0.118309
import fire from fastai.text import * from fastai.lm_rnn import * def freeze_all_but(learner, n): c=learner.get_layer_groups() for l in c: set_trainable(l, False) set_trainable(c[n], True) def train_clas(dir_path, cuda_id, lm_id='', clas_id=None, bs=64, cl=1, backwards=False, startat=0, unfreeze=True, ...
courses/dl2/imdb_scripts/train_clas.py
import fire from fastai.text import * from fastai.lm_rnn import * def freeze_all_but(learner, n): c=learner.get_layer_groups() for l in c: set_trainable(l, False) set_trainable(c[n], True) def train_clas(dir_path, cuda_id, lm_id='', clas_id=None, bs=64, cl=1, backwards=False, startat=0, unfreeze=True, ...
0.276788
0.157979
"""Affine Scalar Tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf from tensorflow_probability.python import bijectors as tfb from tensorfl...
tensorflow_probability/python/bijectors/affine_scalar_test.py
"""Affine Scalar Tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf from tensorflow_probability.python import bijectors as tfb from tensorfl...
0.91571
0.538437
import os import glob import json import tqdm import pickle import functools from indra.sources import eidos from read_pmids import OUTPUT_PATH from indra.tools import assemble_corpus as ac from indra.assemblers.html import HtmlAssembler def fix_provenance(stmts, pmid): for stmt in stmts: for ev in stmt.e...
eidos/process_output.py
import os import glob import json import tqdm import pickle import functools from indra.sources import eidos from read_pmids import OUTPUT_PATH from indra.tools import assemble_corpus as ac from indra.assemblers.html import HtmlAssembler def fix_provenance(stmts, pmid): for stmt in stmts: for ev in stmt.e...
0.247623
0.075653
from rlkit.envs.multitask.point2d import MultitaskImagePoint2DEnv from rlkit.envs.multitask.pusher2d import FullPusher2DEnv from rlkit.launchers.arglauncher import run_variants import rlkit.misc.hyperparameter as hyp from rlkit.torch.vae.relabeled_vae_experiment import experiment if __name__ == "__main__": # noin...
experiments/ashvin/vae/fixed3/pusher2d/vae_dense3.py
from rlkit.envs.multitask.point2d import MultitaskImagePoint2DEnv from rlkit.envs.multitask.pusher2d import FullPusher2DEnv from rlkit.launchers.arglauncher import run_variants import rlkit.misc.hyperparameter as hyp from rlkit.torch.vae.relabeled_vae_experiment import experiment if __name__ == "__main__": # noin...
0.511229
0.305892
import sys import time from functools import partial from PySide import QtGui import harmony.session import harmony.ui.widget.factory import harmony.ui.error_tree import harmony.ui.publisher class Publisher(harmony.ui.publisher.Publisher): '''Customised publisher.''' def _publish(self, instance): ...
test/interactive/publisher.py
import sys import time from functools import partial from PySide import QtGui import harmony.session import harmony.ui.widget.factory import harmony.ui.error_tree import harmony.ui.publisher class Publisher(harmony.ui.publisher.Publisher): '''Customised publisher.''' def _publish(self, instance): ...
0.422981
0.218357
#!/usr/bin/env pythons class CONF: def __init__(self): self.TABLE_NAME = 'table_name' self.TABLET_NUM = 'tablet_number' self.KEY_SIZE = 'key_size(B)' # Bytes self.VALUE_SIZE = 'value_sizeB(B)' # Bytes self.KEY_SEED = 'key_seed' self.VALUE_SEED = 'value_s...
src/benchmark/eva/eva_var.py
#!/usr/bin/env pythons class CONF: def __init__(self): self.TABLE_NAME = 'table_name' self.TABLET_NUM = 'tablet_number' self.KEY_SIZE = 'key_size(B)' # Bytes self.VALUE_SIZE = 'value_sizeB(B)' # Bytes self.KEY_SEED = 'key_seed' self.VALUE_SEED = 'value_s...
0.144783
0.072112
import unittest2 class Test_ClientFactoryMixin(unittest2.TestCase): def _getTargetClass(self): from gcloud.client import _ClientFactoryMixin return _ClientFactoryMixin def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_virtual(self): se...
src/lib/gcloud/test_client.py
import unittest2 class Test_ClientFactoryMixin(unittest2.TestCase): def _getTargetClass(self): from gcloud.client import _ClientFactoryMixin return _ClientFactoryMixin def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_virtual(self): se...
0.58948
0.198763
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.dataflow import apis from googlecloudsdk.calliope import actions from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.calliope import base from googlecloudsdk.comman...
google-cloud-sdk/lib/surface/dataflow/jobs/run.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.dataflow import apis from googlecloudsdk.calliope import actions from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.calliope import base from googlecloudsdk.comman...
0.682997
0.102574