code stringlengths 281 23.7M |
|---|
.parametrize('replication_globs, expected_replicated_paths', [(([['**']] * _WORLD_SIZE), ['0/my_stateful/foo', '0/my_stateful/bar', '0/my_stateful/baz/0', '0/my_stateful/baz/1', '0/my_stateful/qux/quux', '0/my_stateful/qux/quuz']), (([['my_stateful/baz/*', 'my_stateful/qux/*']] * _WORLD_SIZE), ['0/my_stateful/baz/0', '... |
class Dev(Cog):
def __init__(self, bot: Quotient):
self.bot = bot
def cog_check(self, ctx: Context):
return (ctx.author.id in ctx.config.DEVS)
(hidden=True, invoke_without_command=True)
async def bl(self, ctx: Context):
(await ctx.send_help(ctx.command))
(name='add')
asyn... |
class TestBernoulli(QiskitAquaTestCase):
def setUp(self):
super().setUp()
warnings.filterwarnings(action='ignore', category=DeprecationWarning)
self._statevector = QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'), seed_simulator=2, seed_transpiler=2)
self._unitar... |
def _perform_date_checks(self, date_checks):
errors = {}
for (model_class, lookup_type, field, unique_for) in date_checks:
lookup_kwargs = {}
date = getattr(self, unique_for)
if (date is None):
continue
if (lookup_type == 'date'):
lookup_kwargs[('%s__day' ... |
class EchoesRemoteConnector(PrimeRemoteConnector):
def __init__(self, version: EchoesDolVersion, executor: MemoryOperationExecutor):
super().__init__(version, executor)
def _asset_id_format(self):
return '>I'
def multiworld_magic_item(self) -> ItemResourceInfo:
return self.game.resou... |
class HBaseCollector(diamond.collector.Collector):
re_log = re.compile('^(?P<timestamp>\\d+) (?P<name>\\S+): (?P<metrics>.*)$')
def get_default_config_help(self):
config_help = super(HBaseCollector, self).get_default_config_help()
config_help.update({'metrics': 'List of paths to process metrics ... |
('/v1/user/starred')
class StarredRepositoryList(ApiResource):
schemas = {'NewStarredRepository': {'type': 'object', 'required': ['namespace', 'repository'], 'properties': {'namespace': {'type': 'string', 'description': 'Namespace in which the repository belongs'}, 'repository': {'type': 'string', 'description': 'R... |
.parametrize(('test_input', 'expected'), [(nodes.reference('', text='', refuri='mailto:'), '<raw format="html" xml:space="preserve">user at example.com</raw>'), (nodes.reference('', text='Introduction', refid='introduction'), '<reference refid="introduction">Introduction</reference>')])
def test_generate_li... |
def collect_results_cpu(result_part, size, tmpdir=None):
(rank, world_size) = get_dist_info()
if (tmpdir is None):
MAX_LEN = 512
dir_tensor = torch.full((MAX_LEN,), 32, dtype=torch.uint8, device='cuda')
if (rank == 0):
mmcv.mkdir_or_exist('.dist_test')
tmpdir = te... |
(python=USE_PYTHON_VERSIONS)
('command_a', install_commands)
('command_b', install_commands)
def session_cross_pkg_resources_pkgutil(session, command_a, command_b):
session.install('--upgrade', 'setuptools', 'pip')
install_packages(session, 'pkg_resources/pkg_a', 'pkgutil/pkg_b', command_a, command_b)
sessi... |
def distort_color(image):
def fn1():
return contrast(saturation(brightness(image)))
def fn2():
return saturation(contrast(brightness(image)))
def fn3():
return contrast(brightness(saturation(image)))
def fn4():
return brightness(contrast(saturation(image)))
def fn5():... |
class BaseInstance(Instance):
def __init__(self, instance_id, weight, input, output):
super().__init__(instance_id, weight, input, output)
def size(self):
return len(self.input)
def duplicate(self):
dup = BaseInstance(self.instance_id, self.weight, self.input, self.output)
re... |
class ResnetUtilsTest(tf.test.TestCase):
def testSubsampleThreeByThree(self):
x = tf.reshape(tf.to_float(tf.range(9)), [1, 3, 3, 1])
x = resnet_utils.subsample(x, 2)
expected = tf.reshape(tf.constant([0, 2, 6, 8]), [1, 2, 2, 1])
with self.test_session():
self.assertAllClo... |
def test_while_with_if_complex() -> None:
src = "\n while n > 10:\n print(n)\n if n > 20:\n print('hi')\n elif n > 25:\n continue\n print('unr')\n else:\n break\n print('bye')\n print('after')\n "
cfg = build_cfg(src... |
class SelfAttention(nn.Module):
def __init__(self, out_channels, embed_dim, num_heads, project_input=False, gated=False, downsample=False):
super().__init__()
self.attention = DownsampledMultiHeadAttention(out_channels, embed_dim, num_heads, dropout=0, bias=True, project_input=project_input, gated=g... |
class Water(unittest.TestCase):
def setUpClass(cls):
mol = gto.Mole()
mol.verbose = 4
mol.output = '/dev/null'
mol.atom = '\n O 0.00000 0.00000 0.11779\n H 0.00000 0.75545 -0.47116\n H 0.00000 -0.75545 ... |
def test_non_top_portmap(do_test):
def tv_in(m, tv):
m.in_ = Bits32(tv[0])
def tv_out(m, tv):
if (tv[1] != '*'):
assert (m.out == Bits32(tv[1]))
class VReg(Component, VerilogPlaceholder):
def construct(s):
s.in_ = InPort(Bits32)
s.out = OutPort(Bit... |
def count_gates(qobj, basis, qubits):
warn('The function `count_gates` will be deprecated. Gate count is integrated into `gates_per_clifford` function.', category=DeprecationWarning)
nexp = len(qobj.experiments)
ngates = np.zeros([nexp, len(qubits), len(basis)], dtype=int)
basis_ind = {basis[i]: i for i... |
def get_extensions():
this_dir = os.path.dirname(os.path.abspath(__file__))
extra_compile_args = {'cxx': []}
define_macros = []
if (torch.cuda.is_available() and (CUDA_HOME is not None)):
define_macros += [('WITH_CUDA', None)]
extra_compile_args['nvcc'] = ['-DCUDA_HAS_FP16=1', '-D__CUDA_... |
def selfdestruct_eip150(computation: ComputationAPI) -> None:
beneficiary = force_bytes_to_address(computation.stack_pop1_bytes())
if (not computation.state.account_exists(beneficiary)):
computation.consume_gas(constants.GAS_SELFDESTRUCT_NEWACCOUNT, reason=mnemonics.SELFDESTRUCT)
_selfdestruct(compu... |
def add_global_options(parser):
group = parser.add_argument_group('global options')
group.add_argument('-v', dest='verbosity', help='Set verbosity (log levels)', default='')
group.add_argument('-V', dest='verbosity_shortcuts', help='Set verbosity (shortcut-filter list)', default='')
group.add_argument('... |
def main():
running_reward = 10
for i_episode in count(1):
(state, _) = env.reset()
ep_reward = 0
for t in range(1, 10000):
action = select_action(state)
(state, reward, done, _, _) = env.step(action)
if args.render:
env.render()
... |
_on_failure
.parametrize('number_of_nodes', [2])
def test_channel_withdraw_expired(raiden_network: List[RaidenService], network_wait: float, number_of_nodes: int, token_addresses: List[TokenAddress], deposit: TokenAmount, retry_timeout: float, pfs_mock) -> None:
(alice_app, bob_app) = raiden_network
pfs_mock.ad... |
class TestURIReferenceParsesURIs(base.BaseTestParsesURIs):
test_class = URIReference
def test_authority_info_raises_InvalidAuthority(self, invalid_uri):
uri = URIReference.from_string(invalid_uri)
with pytest.raises(InvalidAuthority):
uri.authority_info()
def test_attributes_catc... |
def generate_optimal_model():
env = SM_env(max_hidden_block=HIDDEN_BLOCK, attacker_fraction=ALPHA, follower_fraction=GAMMA)
grid = 100
optimal_policy_all = np.zeros((grid, env._state_space_n), dtype=np.int)
for i in range(grid):
cur_env = SM_env(max_hidden_block=HIDDEN_BLOCK, attacker_fraction=(... |
def is_html(ct_headers, url=None, allow_xhtml=False):
if (not ct_headers):
return is_html_file_extension(url, allow_xhtml)
headers = split_header_words(ct_headers)
if (len(headers) < 1):
return is_html_file_extension(url, allow_xhtml)
first_header = headers[0]
first_parameter = first... |
class TestCluster(unittest.TestCase):
def test_multi_sites(self):
struc = pyxtal()
struc.from_random(0, 1, ['C'], [60], 1.0)
self.assertTrue(struc.valid)
struc = pyxtal()
struc.from_random(0, 3, ['C'], [60], 1.0)
self.assertTrue(struc.valid)
def test_single_specie... |
def blocks(tmin, tmax, deltat, nsamples_block=100000):
tblock = nice_time_tick_inc_approx_secs(util.to_time_float((deltat * nsamples_block)))
iblock_min = int(math.floor((tmin / tblock)))
iblock_max = int(math.ceil((tmax / tblock)))
for iblock in range(iblock_min, iblock_max):
(yield ((iblock * ... |
class SearchParams(BaseModel, extra='forbid'):
hnsw_ef: Optional[int] = Field(default=None, description='Params relevant to HNSW index Size of the beam in a beam-search. Larger the value - more accurate the result, more time required for search.')
exact: Optional[bool] = Field(default=False, description='Search... |
class nnUNetTrainer_DASegOrd0(nnUNetTrainer):
def get_dataloaders(self):
patch_size = self.configuration_manager.patch_size
dim = len(patch_size)
deep_supervision_scales = self._get_deep_supervision_scales()
(rotation_for_DA, do_dummy_2d_data_aug, initial_patch_size, mirror_axes) = s... |
class PointsTable(QuotientView):
def __init__(self, ctx: Context):
super().__init__(ctx, timeout=100)
self.teams: T.List[Team] = []
self.header: str = None
self.footer: str = None
def initial_msg(self):
_e = discord.Embed(color=self.bot.color, title='Points Table Maker')
... |
class attrlist_t(ctypes.Structure):
_fields_ = (('bitmapcount', ctypes.c_ushort), ('reserved', ctypes.c_uint16), ('commonattr', ctypes.c_uint32), ('volattr', ctypes.c_uint32), ('dirattr', ctypes.c_uint32), ('fileattr', ctypes.c_uint32), ('forkattr', ctypes.c_uint32))
def __init__(self, ql, base):
self.q... |
def run_precision_recall_analysis(main_eval, exact_raw, f1_raw, na_probs, qid_to_has_ans, out_image_dir):
if (out_image_dir and (not os.path.exists(out_image_dir))):
os.makedirs(out_image_dir)
num_true_pos = sum((1 for v in qid_to_has_ans.values() if v))
if (num_true_pos == 0):
return
pr... |
def render_pep8_errors_e306(msg, _node, source_lines=None):
line = (msg.line - 1)
(yield from render_context((line - 1), (line + 1), source_lines))
body = source_lines[line]
indentation = (len(body) - len(body.lstrip()))
(yield (None, slice(None, None), LineType.ERROR, ((body[:indentation] + NEW_BLA... |
def content_type_to_writer_kwargs(content_type: str) -> Dict[(str, Any)]:
if (content_type == ContentType.UNESCAPED_TSV.value):
return {'sep': '\t', 'header': False, 'na_rep': [''], 'line_terminator': '\n', 'quoting': csv.QUOTE_NONE, 'index': False}
if (content_type == ContentType.TSV.value):
re... |
class TwRwSparseFeaturesDist(BaseSparseFeaturesDist[KeyedJaggedTensor]):
def __init__(self, pg: dist.ProcessGroup, local_size: int, features_per_rank: List[int], feature_hash_sizes: List[int], device: Optional[torch.device]=None, has_feature_processor: bool=False, need_pos: bool=False) -> None:
super().__in... |
class SpeechT5Processor(ProcessorMixin):
feature_extractor_class = 'SpeechT5FeatureExtractor'
tokenizer_class = 'SpeechT5Tokenizer'
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
def __call__(self, *args, **kwargs):
audio = kwargs.pop('au... |
def delete_old_venv(venv_dir: pathlib.Path) -> None:
if (not venv_dir.exists()):
return
markers = [(venv_dir / '.tox-config1'), (venv_dir / 'pyvenv.cfg'), (venv_dir / 'Scripts'), (venv_dir / 'bin')]
if (not any((m.exists() for m in markers))):
raise Error('{} does not look like a virtualenv,... |
def _get_suffixes_dawg_data(endings, ending_counts, min_ending_freq):
counted_suffixes_dawg_data = []
for ending in endings:
if (ending_counts[ending] < min_ending_freq):
continue
for POS in endings[ending]:
common_form_counts = largest_elements(iterable=endings[ending][P... |
def make_pose_ren_net(output_dir, iter_num=2, test_iter_num=3):
for iter_idx in xrange(1, (iter_num + 1)):
with open('{}/model/train_nyu_pose_ren_s{}.prototxt'.format(output_dir, iter_idx), 'w') as f:
f.write(pose_ren_net('train', iter_idx, output_dir))
with open('{}/model/solver_nyu_pos... |
def generate_experiment(trainable_class, variant_spec, command_line_args):
params = variant_spec.get('algorithm_params')
local_dir = os.path.join(params.get('log_dir'), params.get('domain'))
resources_per_trial = _normalize_trial_resources(command_line_args.resources_per_trial, command_line_args.trial_cpus,... |
def mandatory_keys_exists(config_type: str) -> bool:
config = ConfigParser()
config.read(freshenv_config_location)
if ('personal' in config_type):
if ('provider' not in config[config_type]):
return False
if ('aws_profile' not in config[config_type]):
return False
... |
def test_assert_raises_on_assertthis_not_equals_lists():
context = Context({'assert': {'this': [1, 2, 8, 4.5], 'equals': [1, 2, 3, 4.5]}})
with pytest.raises(AssertionError) as err_info:
assert_step.run_step(context)
assert (str(err_info.value) == "assert assert['this'] is of type list and does not ... |
class CheckpointFunction(torch.autograd.Function):
def forward(ctx, run_function, parent_ctx_dict, kwarg_keys, *args):
if torch.is_grad_enabled():
checkpoint.check_backward_validity(args)
ctx.run_function = run_function
ctx.kwarg_keys = kwarg_keys
ctx.fwd_rng_state = util... |
class TeacherModelArguments():
teacher_name_or_path: Optional[str] = field(default='roberta-large-mnli', metadata={'help': 'The NLI/zero-shot teacher model to be distilled.'})
hypothesis_template: Optional[str] = field(default='This example is {}.', metadata={'help': 'Template used to turn class names into mock... |
class CalcAddImplantCommand(wx.Command):
def __init__(self, fitID, implantInfo, position=None):
wx.Command.__init__(self, True, 'Add Implant')
self.fitID = fitID
self.newImplantInfo = implantInfo
self.newPosition = position
self.oldImplantInfo = None
self.oldPosition ... |
.parametrize('change_default', [None, 'ini', 'cmdline'])
def test_removed_in_x_warning_as_error(pytester: Pytester, change_default) -> None:
pytester.makepyfile('\n import warnings, pytest\n def test():\n warnings.warn(pytest.PytestRemovedIn8Warning("some warning"))\n ')
if (change_d... |
def fix_database_local_govt_mdm(sqlite_file):
print('Editing database', sqlite_file)
conn = sqlite3.connect(sqlite_file)
conn.text_factory = (lambda b: b.decode(errors='ignore'))
c = conn.cursor()
data_command = f'INSERT INTO Council_Tax ( council_tax_id, cmi_cross_ref_id ) VALUES ( 6, 102 );'
... |
class Socks5(BaseProtocol):
async def guess(self, reader, **kw):
header = (await reader.read_w(1))
if (header == b'\x05'):
return True
reader.rollback(header)
async def accept(self, reader, user, writer, users, authtable, **kw):
methods = (await reader.read_n((await r... |
class Voc2007Classification(data.Dataset):
def __init__(self, root, set, transform=None, target_transform=None):
self.root = root
self.path_devkit = os.path.join(root, 'VOCdevkit')
self.path_images = os.path.join(root, 'VOCdevkit', 'VOC2007', 'JPEGImages')
self.set = set
self... |
class GRUNetwork(object):
def __init__(self, input_shape, output_dim, hidden_dim, hidden_nonlinearity=LN.rectify, output_nonlinearity=None, name=None, input_var=None, input_layer=None):
if (input_layer is None):
l_in = L.InputLayer(shape=((None, None) + input_shape), input_var=input_var, name='i... |
def create_cfg():
script_name = 'file_fixtures/my_file.py'
dot_file_path = os.path.splitext(os.path.basename(script_name))[0]
svg_file_path = (dot_file_path + '.svg')
cfg_generator.generate_cfg(mod=script_name, auto_open=False)
gv_file_io = open(dot_file_path)
(yield (dot_file_path, svg_file_pat... |
class Block_Resnet_GCN(nn.Module):
def __init__(self, kernel_size, in_channels, out_channels, stride=1):
super(Block_Resnet_GCN, self).__init__()
self.conv11 = nn.Conv2d(in_channels, out_channels, bias=False, stride=stride, kernel_size=(kernel_size, 1), padding=((kernel_size // 2), 0))
self.... |
def periodicity(f):
(f)
def wrapper(business_logic, query):
if ('periodicity' in query):
periodicity = query['periodicity'][(- 1)]
if re.match('[\\d.]+$', periodicity):
query['periodicity'] = float(periodicity)
else:
query['periodicity'... |
def test_complicated_target_register():
bloq = TestMultiCNOT()
cbloq = qlt_testing.assert_valid_bloq_decomposition(bloq)
assert (len(cbloq.bloq_instances) == (2 * 3))
binst_graph = _create_binst_graph(cbloq.connections)
assert (len(list(nx.topological_generations(binst_graph))) == ((2 * 3) + 2))
... |
class TestRelativeEntropy():
def _simple_relative_entropy_implementation(self, rho, sigma, log_base=np.log, tol=1e-12):
(rvals, rvecs) = rho.eigenstates()
(svals, svecs) = sigma.eigenstates()
rvecs = np.hstack([vec.full() for vec in rvecs]).T
svecs = np.hstack([vec.full() for vec in ... |
class TestParsePep440Version():
.parametrize('original, expected', [('0.7.0-alpha.1', '0.7.0a1'), ('0.8.0-alpha.2', '0.8.0a2')])
def test_semver2_to_pep440(self, original: str, expected: str):
from reana.reana_dev.utils import parse_pep440_version
assert (str(parse_pep440_version(original)) == e... |
('sys.stderr', new_callable=StringIO)
('sys.stdout', new_callable=StringIO)
def test_logger_stdout_vs_stderr(mock_stdout, mock_stderr):
with temp_logger('pypyr.xxx') as logger:
for handler in pypyr.log.logger.get_log_handlers(logging.DEBUG, None):
logger.addHandler(handler)
logger.setLev... |
def power_iteration(W, u_, update=True, eps=1e-12):
(us, vs, svs) = ([], [], [])
for (i, u) in enumerate(u_):
with torch.no_grad():
v = torch.matmul(u, W)
v = F.normalize(gram_schmidt(v, vs), eps=eps)
vs += [v]
u = torch.matmul(v, W.t())
u = F.... |
def pretty_seq(args: Sequence[str], conjunction: str) -> str:
quoted = [(('"' + a) + '"') for a in args]
if (len(quoted) == 1):
return quoted[0]
if (len(quoted) == 2):
return f'{quoted[0]} {conjunction} {quoted[1]}'
last_sep = ((', ' + conjunction) + ' ')
return ((', '.join(quoted[:(... |
class SettingsCM(object):
def __init__(self, database, settings_to_set):
self.database = database
self.settings_to_set = settings_to_set
def __enter__(self):
if hasattr(self, 'stored_settings'):
raise RuntimeError('cannot re-use setting CMs')
self.stored_settings = se... |
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
now = timezone.now()
return ((now - datetime.timedelta(days=1)) <= self.pub_date <... |
class Preprocessor(object):
def __init__(self, vocab, subgoal_ann=False, is_test_split=False, frame_size=300):
self.subgoal_ann = subgoal_ann
self.is_test_split = is_test_split
self.frame_size = frame_size
if (vocab is None):
self.vocab = {'word': Vocab(['<<pad>>', '<<seg... |
class DonutFeatureExtractor(DonutImageProcessor):
def __init__(self, *args, **kwargs) -> None:
warnings.warn('The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use DonutImageProcessor instead.', FutureWarning)
super().__init__(*args, **kwargs) |
def check_extras(dist, attr, value):
try:
list(itertools.starmap(_check_extra, value.items()))
except (TypeError, ValueError, AttributeError) as e:
raise DistutilsSetupError("'extras_require' must be a dictionary whose values are strings or lists of strings containing valid project/version requi... |
class HeatMap(base.ScriptBase):
ARGS_HELP = '<index> <column> <value>'
VERSION = '1.0'
COPYRIGHT = u'Copyright (c) 2018 PyroScope Project'
CMAP_MIN_MAX = 4.0
def add_options(self):
super(HeatMap, self).add_options()
self.add_bool_option('-o', '--open', help='open the resulting image ... |
class KannelBackend(BackendBase):
def configure(self, sendsms_url=' sendsms_params=None, charset=None, coding=None, encode_errors=None, delivery_report_url=None, **kwargs):
self.sendsms_url = sendsms_url
self.sendsms_params = (sendsms_params or {})
self.charset = (charset or 'ascii')
... |
def settings_converter(loaded_settings: dict, input_data: str) -> dict[(str, Any)]:
if (not input_data):
return {}
parsed = SETTINGS_DELIMITER.split(input_data)
if (not parsed):
return {}
try:
settings = {setting: value for (setting, value) in [part.split('=', maxsplit=1) for par... |
def get_pipeline_definition(pipeline_name, parent=None):
logger.debug('starting')
pipeline = get_pipeline_yaml(pipeline_name)
info = PipelineFileInfo(pipeline_name='', parent=parent, loader=__name__, path=None)
definition = PipelineDefinition(pipeline=pipeline, info=info)
logger.debug('found %d stag... |
.parametrize('repo_name, extended_repo_names, expected_failure', [('something', False, None), ('something', True, None), ('some/slash', False, Failures.SLASH_REPOSITORY), ('some/slash', True, None), ('some/more/slash', False, Failures.SLASH_REPOSITORY), ('some/more/slash', True, None), pytest.param(('x' * 255), False, ... |
class PyramidPooling(nn.Module):
def __init__(self, in_channels, sizes=(1, 2, 3, 6), norm_layer=nn.BatchNorm2d, **kwargs):
super(PyramidPooling, self).__init__()
out_channels = int((in_channels / 4))
self.avgpools = nn.ModuleList()
self.convs = nn.ModuleList()
for size in siz... |
_test
def test_layer_sharing_at_heterogenous_depth():
x_val = np.random.random((10, 5))
x = Input(shape=(5,))
A = Dense(5, name='A')
B = Dense(5, name='B')
output = A(B(A(B(x))))
M = Model(x, output)
output_val = M.predict(x_val)
config = M.get_config()
weights = M.get_weights()
... |
def chain_species_base(base, basesite, subunit, site1, site2, size, comp=1):
_verify_sites(base, basesite)
_verify_sites(subunit, site1, site2)
if (size <= 0):
raise ValueError('size must be an integer greater than 0')
if (comp == 1):
compbase = base({basesite: 1})
else:
comp... |
def exec_cmd_in_pod(command, pod_name, namespace, container=None, base_command='bash'):
exec_command = [base_command, '-c', command]
try:
if container:
ret = stream(cli.connect_get_namespaced_pod_exec, pod_name, namespace, container=container, command=exec_command, stderr=True, stdin=False, ... |
def test_from_snc_profiler():
file_name = get_data_file('test_varian_open.prs')
x_profile = Profile().from_snc_profiler(file_name, 'tvs')
y_profile = Profile().from_snc_profiler(file_name, 'rad')
assert np.isclose(x_profile.get_y(0), 45.)
assert np.isclose(y_profile.get_y(0), 45.)
assert (x_prof... |
class OneofPattern(Pattern):
def __init__(self, sub_patterns):
self._sub_patterns = sub_patterns
def match(self, op, tensor):
for sub_pattern in self._sub_patterns:
match_result = sub_pattern.match(op, tensor)
if (match_result is not None):
return match_re... |
def test_requests_pool_one_param(vk):
(users, error) = vk_request_one_param_pool(vk, 'users.get', key='user_ids', values=['durov', 'python273'], default_values={'fields': 'city'})
assert (error == {})
assert isinstance(users, dict)
assert (users['durov'][0]['city']['id'] == 2)
assert (users['python2... |
class KnownValues(unittest.TestCase):
def test_ip_adc2(self):
(e, t_amp1, t_amp2) = myadc.kernel_gs()
self.assertAlmostEqual(e, (- 0.), 6)
(e, v, p, x, es) = myadc.ip_adc(nroots=3)
es.analyze()
self.assertAlmostEqual(e[0], 0., 6)
self.assertAlmostEqual(e[1], 0., 6)
... |
def read_dataset(lang_id='eng'):
lexicon = read_lexicon(lang_id)
phoneme_lst = []
grapheme_lst = []
phoneme_set = set()
grapheme_set = set()
for (grapheme_str, phonemes) in lexicon.word2phoneme.items():
graphemes = list(grapheme_str)
phoneme_lst.append(phonemes)
grapheme_... |
def apply_tree(x, func, path=()):
if isinstance(x, Object):
for (name, val) in x.inamevals():
if isinstance(val, (list, tuple)):
for (iele, ele) in enumerate(val):
apply_tree(ele, func, path=(path + ((name, iele),)))
elif isinstance(val, dict):
... |
_fixtures(WebFixture, PanelSwitchFixture, TabbedPanelAjaxFixture)
def test_clicking_on_multi_tab(web_fixture, panel_switch_fixture, tabbed_panel_ajax_fixture):
if (not panel_switch_fixture.enable_js):
panel_switch_fixture.ensure_disabled_js_files_not_cached()
wsgi_app = tabbed_panel_ajax_fixture.new_wsg... |
class SetPartitioner(object):
def __init__(self, client, path, set, partition_func=None, identifier=None, time_boundary=30, max_reaction_time=1, state_change_event=None):
self.state_id = 0
self.state = PartitionState.ALLOCATING
self.state_change_event = (state_change_event or client.handler.... |
def test_wr_As_rd_A_rd_At_can_schedule():
class Top(ComponentLevel3):
def construct(s):
s.A = Wire(Bits32)
def up_wr_As():
s.A[1:3] = Bits2(2)
def up_rd_A():
z = s.A
def up_rd_As():
assert (s.A[2:4] == 1)
_te... |
def convertMesh(case, mesh_file, scale):
mesh_file = translatePath(mesh_file)
if (mesh_file.find('.unv') > 0):
cmdline = ['ideasUnvToFoam', '"{}"'.format(mesh_file)]
runFoamCommand(cmdline, case)
changeBoundaryType(case, 'defaultFaces', 'wall')
if (mesh_file[(- 4):] == '.msh'):
... |
def rescale_absorbance(spec, rescaled, initial, old_mole_fraction, new_mole_fraction, old_path_length_cm, new_path_length_cm, waveunit, rescaled_units, extra, true_path_length):
unit = None
if ('absorbance' in rescaled):
if __debug__:
printdbg('... rescale: absorbance was scaled already')
... |
class PrecipCloudsRGB(GenericCompositor):
def __call__(self, projectables, *args, **kwargs):
projectables = self.match_data_arrays(projectables)
light = projectables[0]
moderate = projectables[1]
intense = projectables[2]
status_flag = projectables[3]
if np.bitwise_an... |
class ProjectResourceGroupManager(RetrieveMixin, UpdateMixin, RESTManager):
_path = '/projects/{project_id}/resource_groups'
_obj_cls = ProjectResourceGroup
_from_parent_attrs = {'project_id': 'id'}
_list_filters = ('order_by', 'sort', 'include_html_description')
_update_attrs = RequiredOptional(opt... |
def convert_hit_area(filename, savename):
hit_x = []
hit_y = []
hit_area = []
landing_x = []
landing_y = []
landing_area = []
time = []
getpoint_player = []
lose_reason = []
ball_type = []
frame = []
output = pd.DataFrame([])
data = pd.read_csv(filename)
sets = da... |
def register_events(path_or_typeclass):
if isinstance(path_or_typeclass, str):
typeclass = class_from_module(path_or_typeclass)
else:
typeclass = path_or_typeclass
typeclass_name = ((typeclass.__module__ + '.') + typeclass.__name__)
try:
storage = ScriptDB.objects.get(db_key='eve... |
def gather_files_in_dirs(rootdir, targetdir, searchfilename, newfilesuffix='_Impact.png'):
for (root, dirs, files) in os.walk(rootdir):
for f in files:
if (os.path.basename(f) == searchfilename):
current_dir = os.path.dirname(os.path.join(root, f))
model_id = os.p... |
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('id_list_file', type=str, help=((('required list of project ids to delete in plain text format, ' + 'project ids have to be at the beginning of the line, ') + 'supports commenting lines out: if a line does ') + 'not start with ... |
class QnliProcessor(DataProcessor):
def get_example_from_tensor_dict(self, tensor_dict):
return InputExample(tensor_dict['idx'].numpy(), tensor_dict['question'].numpy().decode('utf-8'), tensor_dict['sentence'].numpy().decode('utf-8'), str(tensor_dict['label'].numpy()))
def get_train_examples(self, data_... |
def _prepare_instance_masks_thicken(instances, semantic_mapping, distance_field, frustum_mask) -> Dict[(int, Tuple[(torch.Tensor, int)])]:
instance_information = {}
for (instance_id, semantic_class) in semantic_mapping.items():
instance_mask: torch.Tensor = (instances == instance_id)
instance_di... |
def update_usage_list_schemas() -> None:
print('updating docs/usage.rst -- list schemas')
with open('docs/usage.rst') as fp:
content = fp.read()
vendored_list_start = '.. vendored-schema-list-start\n'
vendored_list_end = '\n.. vendored-schema-list-end'
content_head = content.split(vendored_l... |
class CLIPVisionCfg():
backbone: str = 'ModifiedRN50'
layers: Union[(Tuple[(int, int, int, int)], int)] = 12
width: int = 64
head_width: int = 64
mlp_ratio: float = 4.0
patch_size: int = 16
image_size: Union[(Tuple[(int, int)], int)] = 512
timm_model_name: str = None
timm_model_pretr... |
def reset_defaults():
defaults.update(_control_defaults)
from .freqplot import _freqplot_defaults, _nyquist_defaults
defaults.update(_freqplot_defaults)
defaults.update(_nyquist_defaults)
from .nichols import _nichols_defaults
defaults.update(_nichols_defaults)
from .pzmap import _pzmap_defa... |
def test_unused_udp_port_factory_selects_unused_port(pytester: Pytester):
pytester.makepyfile(dedent(' .asyncio\n async def test_unused_udp_port_factory_fixture(unused_udp_port_factory):\n class Closer:\n def connection_made(self, transport):\n ... |
class TourneySlotSelec(discord.ui.Select):
view: QuotientView
def __init__(self, slots: T.List[TMSlot], placeholder: str='Select a slot to cancel'):
_options = []
for slot in slots:
_options.append(discord.SelectOption(emoji=emote.TextChannel, label=f'Slot {slot.num} - {slot.team_nam... |
def get_data_points(data):
date_index = [m.span() for m in DATE_PATTERN.finditer(data)]
start_points = [(span[0] - 8) for span in date_index]
end_points = (start_points[1:] + [None])
data_points = [data[start:end] for (start, end) in zip(start_points, end_points)]
return data_points |
def keras_model_functional():
is_training = tf.compat.v1.placeholder_with_default(tf.constant(True), shape=(), name='is_training')
inputs = tf.keras.Input(shape=(32, 32, 3))
x = tf.keras.layers.Conv2D(32, (3, 3))(inputs)
x = tf.keras.layers.BatchNormalization(momentum=0.3, epsilon=0.65)(x, training=True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.