code stringlengths 281 23.7M |
|---|
def decode_list(t: Type[T]) -> Callable[([List[Any]], List[T])]:
decode_item = get_decoding_fn(t)
def _decode_list(val: List[Any]) -> List[T]:
if (type(val) != list):
raise Exception(f"The given value='{val}' is not of a valid input")
return [decode_item(v) for v in val]
return _... |
class Hydra():
def create_main_hydra_file_or_module(cls: Type['Hydra'], calling_file: Optional[str], calling_module: Optional[str], config_path: Optional[str], job_name: str) -> 'Hydra':
config_search_path = create_automatic_config_search_path(calling_file, calling_module, config_path)
return Hydra.... |
def add_to_app(components: List[Standalone.Component], app_path: str, folder: str=node.ASSET_FOLDER, name: str='{selector}', raise_exception: bool=False) -> dict:
result = {'dependencies': {}}
for component in components:
result[component.selector] = npm.check_component_requirements(component, app_path,... |
.external
.skipif((has_openai_key is False), reason='OpenAI API key not available')
.parametrize('cfg_string', ['zeroshot_cfg_string', 'zeroshot_cfg_string_v2_lds', 'fewshot_cfg_string', 'fewshot_cfg_string_v2', 'ext_template_cfg_string'])
def test_ner_config(cfg_string, request):
cfg_string = request.getfixtureval... |
def move():
mc.send_angles(init_angles[0], 50)
time.sleep(3)
mc.send_angles(init_angles[1], 50)
time.sleep(3)
gripper_on()
mc.send_angles([0.0, 26.27, 0.17, (- 72.86), (- 0.17), (- 77.51), 0.0], 50)
time.sleep(3)
mc.send_angles([(- 2.02), 41.74, 0.43, (- 86.13), (- 0.17), (- 46.05), 0.0]... |
class IterationBased():
def __init__(self, warmup_iterations, iterations):
self._warmup_iterations = warmup_iterations
self._iterations = iterations
if ((warmup_iterations is not None) and (iterations is not None)):
self._total_iterations = (self._warmup_iterations + self._iterat... |
class OptionPlotoptionsErrorbarSonificationDefaultinstrumentoptionsMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsErrorbarSonificationDefaultinstrumentoptionsMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsErrorbarSonificationDefaultinstrumentoptions... |
def validate_header(header: Header, parent_header: Header) -> None:
ensure((header.timestamp > parent_header.timestamp), InvalidBlock)
ensure((header.number == (parent_header.number + 1)), InvalidBlock)
ensure(check_gas_limit(header.gas_limit, parent_header.gas_limit), InvalidBlock)
ensure((len(header.e... |
class OptionSeriesColumnpyramidSonificationContexttracksMappingNoteduration(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: st... |
class OptionSeriesPolygonSonificationContexttracksMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
se... |
def create_dummy_serializer(serializer_cls, skip_fields=(), required_fields=()):
class Serializer(s.Serializer):
pass
for (name, field) in iteritems(serializer_cls.base_fields):
if ((name in skip_fields) or field.read_only):
continue
if isinstance(field, s.RelatedField):
... |
def test_slurm_node_list() -> None:
with with_slurm_job_nodelist('compute-b24') as env:
assert (['compute-b24'] == env.hostnames)
with with_slurm_job_nodelist('compute-a1,compute-b2') as env:
assert (['compute-a1', 'compute-b2'] == env.hostnames)
with with_slurm_job_nodelist('compute-b2[1,2]... |
def _cmd_export_vcf(args):
segarr = read_cna(args.segments)
cnarr = (read_cna(args.cnr) if args.cnr else None)
is_sample_female = verify_sample_sex(segarr, args.sample_sex, args.male_reference, args.diploid_parx_genome)
(header, body) = export.export_vcf(segarr, args.ploidy, args.male_reference, args.di... |
.django_db
def test_award_outlays_sum_multiple_years(client, monkeypatch, helpers, defc_codes, basic_ref_data, early_gtas, multi_year_faba):
helpers.patch_datetime_now(monkeypatch, LATE_YEAR, EARLY_MONTH, 25)
helpers.reset_dabs_cache()
resp = client.get(OVERVIEW_URL)
assert (resp.data['spending']['award... |
class Myclass():
attr: int
attr2: int
def __init__(self):
self.attr = 1
self.attr2 = 2
def func(self, arg: int):
if (self.func((arg - 1)) < 1):
return 1
else:
a = (self.func((arg - 1)) * self.func((arg - 1)))
return ((a + ((self.attr * ... |
class TestMockAsyncCallableIntegration(TestDSLBase):
def test_mock_async_callable_integration(self):
class SomeClass():
async def do_something():
return 'for real'
def fail_top(context):
_context
def fail_sub_context(context):
async... |
.external
.skipif((has_openai_key is False), reason='OpenAI API key not available')
.parametrize('cfg_string', ['zeroshot_cfg_string', 'fewshot_cfg_string', 'ext_template_cfg_string'])
def test_lemma_config(cfg_string, request):
cfg_string = request.getfixturevalue(cfg_string)
orig_config = Config().from_str(cf... |
class LowercasePropositions(Vars):
(a, b, c) = props('a b c')
(d, e, f) = props('d e f')
(g, h, i) = props('g h i')
(j, k, l) = props('j k l')
(m, n, o) = props('m n o')
(p, q, r) = props('p q r')
(s, t, u) = props('s t u')
(v, w, x) = props('v w x')
(y, z) = props('y z') |
()
('--config', default='', metavar='FILE', help='path to config file')
('--bench-config', default='', metavar='FILE', help='path to config file')
('--input', multiple=True, help="A list of space separated input images; or a single glob pattern such as 'directory/*.jpg'")
('--output', help='A file or directory to save ... |
def on_enable():
sitekey = os.getenv('GOOGLE_CAPTCHA2_SITEKEY', '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI')
secret = os.getenv('GOOGLE_CAPTCHA2_SECRET', '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe')
if ((not sitekey) or (not secret)):
raise RuntimeError('Required keys not found in the environment. Ple... |
class EventZebraBase(event.EventBase):
def __init__(self, zclient, msg):
super(EventZebraBase, self).__init__()
assert isinstance(msg, zebra.ZebraMessage)
self.__dict__ = msg.__dict__
self.zclient = zclient
def __repr__(self):
m = ', '.join([('%s=%r' % (k, v)) for (k, v) ... |
def set_site_config_nginx_property(site, config, bench_path='.', gen_config=True):
from bench.config.nginx import make_nginx_conf
from bench.bench import Bench
if (site not in Bench(bench_path).sites):
raise Exception('No such site')
update_site_config(site, config, bench_path=bench_path)
if... |
def generate_right_ssml_text(text, speaking_rate, speaking_pitch):
attribs = {'rate': speaking_rate, 'pitch': speaking_pitch}
cleaned_attribs_string = ''
for (k, v) in attribs.items():
if (not v):
continue
cleaned_attribs_string = f"{cleaned_attribs_string} {k}='{v}%'"
if (no... |
class KeolisIleviaStation(BikeShareStation):
def __init__(self, fields):
name = fields['nom']
(latitude, longitude) = map(float, fields['localisation'])
bikes = int(fields['nbvelosdispo'])
free = int(fields['nbplacesdispo'])
extra = {'status': fields['etat'], 'uid': str(field... |
def resolve_version():
if os.path.isdir(GIT_DIRECTORY):
version = git_version()
print('Computed package version: {}'.format(version))
print('Writing version to version file {}.'.format(VERSION_FILE))
write_version_file(*version)
elif ('$' not in ARCHIVE_COMMIT_HASH):
vers... |
_cache(maxsize=1)
def tokenize_css(css: str, start: int=0) -> dict[(str, Any)]:
tokens = {}
m = RE_HEX.match(css, start)
if m:
tokens['hex'] = {'start': m.group(1), 'value': m.group(0)}
tokens['id'] = 'srgb'
tokens['end'] = m.end()
return tokens
m = RE_NAME.match(css, sta... |
def extractTheCaptainSLog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postf... |
class EmbeddingOpenAI_0x(Embedding):
def __init__(self, model_name='openai'):
super().__init__(model_name)
print(f'Initialized EmbeddingOpenAI 0x: {openai.__version__}')
def dim(self):
return 1536
def getname(self, start_date, prefix='news'):
return f'{prefix}_embedding__{sta... |
class OptionPlotoptionsPictorialLabel(Options):
def boxesToAvoid(self):
return self._config_get(None)
def boxesToAvoid(self, value: Any):
self._config(value, js_type=False)
def connectorAllowed(self):
return self._config_get(False)
def connectorAllowed(self, flag: bool):
... |
def test_data_transfer_from_broker(load_broker_data):
call_command('transfer_procurement_records', '--reload-all')
table = SourceProcurementTransaction().table_name
with connections[DEFAULT_DB_ALIAS].cursor() as cursor:
cursor.execute(f'SELECT COUNT(*) FROM {table}')
assert (cursor.fetchall(... |
def _ambassador_module_onemapper(status_code, body_kind, body_value, content_type=None):
mod = (_ambassador_module_config() + f'''
error_response_overrides:
- on_status_code: "{status_code}"
body:
''')
if (body_kind == 'text_format_source'):
mod = (mod + f'''
{body_kind}:
filename:... |
def redirect_if_tags_query(view_fn):
(view_fn)
def wrapper(request, **kwargs):
if (not request.GET.get('tags')):
return view_fn(request, **kwargs)
if ('ccg_code' in kwargs):
url = reverse('measures_for_one_ccg', kwargs=kwargs)
else:
url = reverse('meas... |
class TestCreateEditor(unittest.TestCase):
_traitsui
def test_exists_controls_editor_dialog_style(self):
x = File(exists=True)
editor = x.create_editor()
self.assertEqual(editor.dialog_style, 'open')
x = File(exists=False)
editor = x.create_editor()
self.assertEqu... |
class ERI(Function):
def eval(cls, ia, ja, ka, ib, jb, kb, ic, jc, kc, id_, jd, kd, N, a, b, c, d, A, B, C, D):
ang_moms = np.array((ia, ja, ka, ib, jb, kb, ic, jc, kc, id_, jd, kd), dtype=int)
ang_moms2d = ang_moms.reshape((- 1), 3)
if any([(am < 0) for am in ang_moms]):
return ... |
.parametrize(*decode_tuples_args)
def test_tuple_contract_caller_default_with_decode_tuples(tuple_contract_with_decode_tuples, method_input, tuple_output, type_str, namedtuple_repr):
result = tuple_contract_with_decode_tuples.caller.method(method_input)
assert (result == tuple_output)
assert (str(type(resul... |
def extractFroglationXyz(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
bad = ['Fukusyu wo Chikatta Shironeko wa Ryuuou no Hiza no ue de Damin wo Musaboru (Manga)']
if any([(tmp in it... |
.parametrize(('words', 'score_expected'), [(('',), 100), ((' ',), 100), (('.uk',), 100), (('to', ''), 80), (('', ''), 100), (('',), 0)])
def test_email_magic_score(ocr_result, words, score_expected):
ocr_result.words = [{'text': w} for w in words]
magic = EmailMagic()
score = magic.score(ocr_result)
as... |
class RelationshipTlsPrivateKey(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_imp... |
class AbcdNet(decl):
_fields = ('name', 'args', 'body')
_attributes = ('lineno', 'col_offset')
def __init__(self, name, args, body, lineno=0, col_offset=0, **ARGS):
decl.__init__(self, **ARGS)
self.name = name
self.args = args
self.body = body
self.lineno = int(lineno... |
def extractDeepdreamtranlationsHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("The Scum Shou's Survival Guide", "The Scum Shou's Survival Guide", 'translated'), ('TSSS... |
class BaseProtocol(ProtocolAPI):
def __init__(self, transport: TransportAPI, command_id_offset: int, snappy_support: bool) -> None:
self.logger = get_logger('p2p.protocol.Protocol')
self.transport = transport
self.command_id_offset = command_id_offset
self.snappy_support = snappy_sup... |
def verify_apks(signed_apk, unsigned_apk, tmp_dir, v1_only=None):
if (not verify_apk_signature(signed_apk)):
logging.info('...NOT verified - {0}'.format(signed_apk))
return 'verification of signed APK failed'
if (not os.path.isfile(signed_apk)):
return 'can not verify: file does not exis... |
def test_issue_21_v0_3_8():
a = [1, 2, 3]
b = [0, 1, 0]
assert (np.inner(a, b) == 2)
na = np.array([1, 2, 3])
nb = np.array([0, 1, 0])
assert (np.inner(na, nb) == np.inner(a, b)).all()
fa = Fxp([1, 2, 3])
fb = Fxp([0, 1, 0])
z = np.inner(fa, fb)
assert (np.inner(fa, fb)() == np.i... |
def plot_histogram(counts, fontsize, dpi):
(fig, ax) = plt.subplots(dpi=dpi, figsize=(8, 20))
labels = []
for (k, v) in counts.items():
if isinstance(v, dict):
labels += list(v.keys())
v = list(v.values())
else:
labels.append(k)
v = [v]
... |
()
def setup_to_pass():
rules = ['-w /var/log/lastlog -p wa -k logins', '-w /var/run/faillock -p wa -k logins']
for rule in rules:
print(shellexec(f'echo "{rule}" >> /etc/audit/rules.d/pytest.rules'))
print(shellexec(f'auditctl {rule}'))
(yield None)
print(shellexec('cat /etc/audit/rules... |
def __app_sync(target, name='', host=None, port=0, view: Optional[AppView]=AppView.FLET_APP, assets_dir='assets', upload_dir=None, web_renderer: WebRenderer=WebRenderer.CANVAS_KIT, use_color_emoji=False, route_url_strategy='path', auth_token=None):
if isinstance(view, str):
view = AppView(view)
if isins... |
class DecimalField(NumberField[Decimal]):
max_digits: Optional[int] = None
max_decimal_places: Optional[int] = None
def __init__(self, *, max_digits: Optional[int]=None, max_decimal_places: Optional[int]=None, **kwargs: Any) -> None:
self.max_digits = max_digits
self.max_decimal_places = max... |
def extractWwwBlsfeedCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagm... |
def action_to_str(act, ofctl_action_to_str):
sub_type = act.subtype
if (sub_type == nicira_ext.NXAST_RESUBMIT):
return ('NX_RESUBMIT: {port: %s, table: %s}' % (act.in_port, act.table_id))
elif (sub_type == nicira_ext.NXAST_REG_MOVE):
src_start = act.src_ofs
dst_start = act.dst_ofs
... |
def _print_fnarg(a, env: PrintEnv) -> str:
if (a.type == T.size):
return f'{env.get_name(a.name)} : size'
elif (a.type == T.index):
return f'{env.get_name(a.name)} : index'
else:
ty = _print_type(a.type, env)
mem = (f' {a.mem.name()}' if a.mem else '')
return f'{env.g... |
def post_solve_pig_wood(arbiter, space, _):
pigs_to_remove = []
if (arbiter.total_impulse.length > 700):
(pig_shape, wood_shape) = arbiter.shapes
for pig in pigs:
if (pig_shape == pig.shape):
pig.life -= 20
global score
score += 10000
... |
def test_exception_is_caught_and_shows_error_message(dummy_execute_and_send):
(dummy, m) = dummy_execute_and_send
dummy._execute_and_send(cmd='raises_exception', args=[], match=None, msg=m, template_name=dummy.raises_exception._err_command_template)
assert (dummy.MSG_ERROR_OCCURRED in dummy.pop_message().bo... |
.parametrize('input_points, expected_points', [(range(10), [0, 4, 8, 9]), ([1, 10, 11, 12, 13, 14, 100, 10000], [1, 13, 10000])])
def test_downsample(string_to_well, input_points, expected_points):
well_definition = '1.01\n Unknown\n custom_name 0 0 0\n 1\n Zonelog DISC 1... |
class OptionPlotoptionsXrangeSonificationDefaultinstrumentoptionsMappingHighpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(... |
def import_template(module, zbx, filename, fmt):
if (not os.path.exists(filename)):
module.fail_json(msg=('template file %s not found' % filename))
with open(filename) as f:
data = f.read()
try:
return zbx.configuration.import_({'format': fmt, 'source': data, 'rules': {'items': {'cre... |
def extractPiperpickupsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('ss', 'Support System: Leading Two Souls Together', 'translated'), ('mstp', 'My Son is a Tran... |
([Output('activity-date', 'children'), Output('activity-kpi', 'children'), Output('oura-activity-content', 'children')], [Input('last-chart-clicked', 'children')])
def update_oura_activity_contents(date):
date = pd.to_datetime(date).date()
(date_title, star, score) = generate_oura_activity_header_kpi(date)
... |
('pyscf')
def test_composite_run_dict(this_dir):
run_dict = {'geom': {'type': 'cart', 'fn': str((this_dir / '00_ch4.xyz'))}, 'calc': {'type': 'composite', 'calcs': {'high': {'type': 'pyscf', 'basis': '321g'}, 'low': {'type': 'pyscf', 'basis': 'sto3g'}}, 'final': 'high - low', 'pal': 4}}
results = run_from_dict(... |
def _tag_webhook(func: Callable, uri_rule: str, methods: Tuple[str], form_param: Optional[str], raw: bool) -> Callable:
log.info(f"webhooks: Flag to bind {uri_rule} to {getattr(func, '__name__', func)}")
func._err_webhook_uri_rule = uri_rule
func._err_webhook_methods = methods
func._err_webhook_form_par... |
class _MemoryBroadcast():
class Subscription():
def __init__(self, queue: asyncio.Queue) -> None:
self._queue = queue
async def __aiter__(self) -> AsyncIterator[str]:
while True:
(yield (await self._queue.get()))
def __init__(self) -> None:
self._s... |
class OptionPlotoptionsFunnelSonificationContexttracksMappingPan(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def test_graphql_to_attachment_audio():
data = {'__typename': 'MessageAudio', 'attribution_app': None, 'attribution_metadata': None, 'filename': 'audio.mp3', 'playable_url': ' 'playable_duration_in_ms': 27745, 'is_voicemail': False, 'audio_type': 'FILE_ATTACHMENT', 'url_shimhash': 'AT0...', 'url_skipshim': True}
... |
def proportions_diff_z_stat_ind(ref: pd.DataFrame, curr: pd.DataFrame):
n1 = len(ref)
n2 = len(curr)
p1 = (float(sum(ref)) / n1)
p2 = (float(sum(curr)) / n2)
P = (float(((p1 * n1) + (p2 * n2))) / (n1 + n2))
return ((p1 - p2) / np.sqrt(((P * (1 - P)) * ((1.0 / n1) + (1.0 / n2))))) |
def test_with_nonexistent_id(client, create_idv_test_data):
response = client.get('/api/v2/idvs/count/federal_account/0/')
assert (response.status_code == status.HTTP_200_OK)
assert (response.data['count'] == 0)
response = client.get('/api/v2/idvs/count/federal_account/CONT_IDV_000/')
assert (respon... |
class TestNormalizedOutputValueDecimalField(TestCase):
def test_normalize_output(self):
field = serializers.DecimalField(max_digits=4, decimal_places=3, normalize_output=True)
output = field.to_representation(Decimal('1.000'))
assert (output == '1')
def test_non_normalize_output(self):
... |
.skipif((django.VERSION > (1, 9)), reason='MIDDLEWARE_CLASSES removed in Django 2.0')
def test_user_info_with_non_django_auth(django_elasticapm_client, client):
with (override_settings(INSTALLED_APPS=[app for app in settings.INSTALLED_APPS if (app != 'django.contrib.auth')]) and override_settings(MIDDLEWARE_CLASSES... |
class Valve():
__slots__ = ['_coprocessor_manager', '_dot1x_manager', '_last_advertise_sec', '_last_fast_advertise_sec', '_last_lldp_advertise_sec', '_last_packet_in_sec', '_packet_in_count_sec', '_port_highwater', '_route_manager_by_eth_type', '_route_manager_by_ipv', '_lldp_manager', '_managers', '_output_only_ma... |
def extractThetranslationsargeantWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (item['tags'] == ['Uncategorized']):
titlemap = [('TD Chapter ', 'Fun Territory Def... |
class Command(object):
def _execute(self, cmd, capture=False, executable=None):
if capture:
p_stdout = subprocess.PIPE
p_stderr = subprocess.PIPE
else:
p_stdout = None
p_stderr = None
pop = subprocess.Popen(cmd, shell=True, executable=executabl... |
def _load_modules_from_file(filepath: str):
import importlib
import importlib.machinery
import importlib.util
logger.info(f'Importing {filepath}')
(org_mod_name, _) = os.path.splitext(os.path.split(filepath)[(- 1)])
path_hash = hashlib.sha1(filepath.encode('utf-8')).hexdigest()
mod_name = f'... |
def catch_errors(obj, mth, paramflags, interface, mthname):
clsid = getattr(obj, '_reg_clsid_', None)
def call_with_this(*args, **kw):
try:
result = mth(*args, **kw)
except ReturnHRESULT as err:
(hresult, text) = err.args
return ReportError(text, iid=interface... |
class TestWorkflows(unittest.TestCase):
def test_matrix_to_lock_version_defaults(self):
lock_workflow_file = (GITHUB_WORKFLOWS / 'lock-versions.yml')
lock_workflow = yaml.safe_load(lock_workflow_file.read_text())
lock_versions = lock_workflow[True]['workflow_dispatch']['inputs']['branches'][... |
class OptionSeriesTreemapDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
self... |
.parametrize('items, stack_method', (([1], 'push_int'), ([1, 2, 3], 'push_int'), ([b'1', b'10', b'101', b'1010'], 'push_bytes')))
def test_pop_returns_latest_stack_item(stack, items, stack_method):
method = getattr(stack, stack_method)
for each in items:
method(each)
assert (stack.pop1_any() == item... |
def _soft_threshold(z, T, handle_complex=True):
sz = np.maximum((np.abs(z) - T), 0)
if (not handle_complex):
sz[:] = (np.sign(z) * sz)
else:
old_err_state = np.seterr(invalid='ignore')
sz[:] = np.nan_to_num((((1.0 * sz) / (sz + T)) * z))
np.seterr(**old_err_state)
return ... |
class TestChaining(testslide.TestCase):
def testBitwiseAnd(self):
self.assertTrue(isinstance((testslide.matchers.Any() & testslide.matchers.AnyStr()), testslide.matchers._AndMatcher))
self.assertEqual((testslide.matchers.Any() & testslide.matchers.AnyStr()), 'a')
self.assertNotEqual((testsli... |
class BaseStateActionCriticComposer(CriticComposerInterface):
def __init__(self, observation_spaces_dict: Dict[(Union[(str, int)], spaces.Dict)], action_spaces_dict: Dict[(Union[(str, int)], spaces.Dict)]):
self._observation_spaces_dict = observation_spaces_dict
self._action_spaces_dict = action_spa... |
def test_constant(converter):
w = converter._world
assert (converter.convert(Constant(6, Integer.int32_t())) == w.constant(6, 32))
assert (converter.convert(Constant(7.2, Float.float())) == w.constant(7.2, 32))
with pytest.raises(ValueError):
converter.convert(Constant('hello', Pointer(Integer.u... |
def create_isolation_field(level):
choices = []
default_choices = [('default', 'Use default configuration from mock-core-configs.rpm'), ('nspawn', 'systemd-nspawn'), ('simple', 'simple chroot')]
if (level == 'build'):
choices.append(('unchanged', 'Use project/chroot settings'))
elif (level == 'c... |
def install_prerequisites():
logger.info('installing inkscape_silhouette prerequisites')
for prerequisite in prerequisites:
logger.debug('installing %s', prerequisite)
try:
return_code = subprocess.call('pip3 install {}'.format(prerequisite), shell=True)
if (return_code >... |
.usefixtures('reindex_setup')
def test_all_documents_get_moved(sync_client):
helpers.reindex(sync_client, 'test_index', 'prod_index')
sync_client.indices.refresh()
assert sync_client.indices.exists(index='prod_index')
assert (50 == sync_client.count(index='prod_index', q='type:questions')['count'])
... |
def process_overlaps_clans_queries(namedhits, CLANS_FILE):
if ((not os.path.exists(CLANS_FILE)) or (not os.path.isfile(CLANS_FILE))):
raise Exception(f"Couldn't find PFAM clans file at path {CLANS_FILE}, or it is not a file.")
clans_dict = {}
with gzip.open(CLANS_FILE, 'rt') as clans_f:
for ... |
.parametrize('server,expected_num_flashes', [(lazy_fixture('no_lone_server'), 0), (lazy_fixture('lone_on_switch_server'), 1), (lazy_fixture('lone_on_open_close_server'), 0)])
def test_workspace_switching_behavior(server: FlashServer, expected_num_flashes: int) -> None:
with new_window_session({0: 1, 1: 1}) as windo... |
class HeaderRoutingAuth(ServiceType):
skip_variant: ClassVar[bool] = True
def __init__(self, *args, **kwargs) -> None:
kwargs['service_manifests'] = '\n---\nkind: Service\napiVersion: v1\nmetadata:\n name: {self.path.k8s}\nspec:\n selector:\n backend: {self.path.k8s}\n ports:\n - name: protoc... |
class ControllerBase():
special_vars = ['action', 'controller']
def __init__(self, req, link, data, **config):
self.req = req
self.link = link
self.data = data
self.parent = None
for (name, value) in config.items():
setattr(self, name, value)
def __call__(... |
class UninstallSystemAction(argparse.Action):
def __call__(self, parser, namespace, value, option_string=None):
if (os.getuid() != 0):
print('E: You must run nautilus-terminal as root to perform a system-wide removal.')
sys.exit(1)
uninstall_system()
sys.exit(0) |
class OptionPlotoptionsBulletSonificationContexttracksMappingFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class OptionSeriesFunnel3dSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionSeriesFunnel3dSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionSeriesFunnel3dSonificationTracksMappingHighpassFrequency)
def resonance(self) -> 'OptionSeriesFun... |
def update_shipping_info(doc, method=None):
so = doc
if (not so.has_value_changed(PACKAGE_TYPE_FIELD)):
return
package_type = so.get(PACKAGE_TYPE_FIELD)
if (not package_type):
return
frappe.enqueue(_update_package_info_on_unicommerce, queue='short', so_code=so.name) |
def check(ip, domain, port, args, timeout, payload_map):
username_list = payload_map.get('username')
password_list = payload_map.get('password')
try:
for username in username_list:
for password in password_list:
try:
conn = pymysql.connect(host=ip, por... |
class TestStubAction(PyTestServerTestCase):
server_class = _TestServiceServer
server_settings = {}
def setup_method(self):
super(TestStubAction, self).setup_method()
self.secondary_stub_client = Client(_secondary_stub_client_settings)
_action('test_service', 'test_action_1')
def test... |
def test_generated_js1():
m = app.assets.modules['flexx.app._component2']
js = m.get_js()
classes = []
for line in js.splitlines():
if ('._base_class =' in line):
classes.append(line.split('.')[0])
assert (classes == ['LocalProperty', 'BaseAppComponent', 'LocalComponent', 'ProxyC... |
.django_db(transaction=True)
def test_download_transactions_bad_filter_type_raises(client, monkeypatch, download_test_data, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string(... |
def test_external_template_actually_loads():
template_path = str((TEMPLATES_DIR / 'ner.jinja2'))
template = file_reader(template_path)
labels = 'PER,ORG,LOC'
nlp = spacy.blank('en')
doc = nlp.make_doc('Alice and Bob went to the supermarket')
llm_ner = make_ner_task_v3(examples=[], labels=labels,... |
class categorical_datasource(CategoricalDataSource):
def __init__(self, fnames_file, desc_file, feat_name, feats_dir, feats_dict=None):
super(categorical_datasource, self).__init__(fnames_file, desc_file, feat_name, feats_dir, feats_dict)
def __getitem__(self, idx):
assert (self.feat_type == 'ca... |
class OptionPlotoptionsLollipopSonificationContexttracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: fl... |
def test_threshold_peaks():
data = np.array([[10, 1, 1.8], [14, 2, 4], [12, 3, 2.5]])
assert np.array_equal(threshold_peaks(data, 2.5), np.array([[12, 3, 2.5]]))
data = np.array([[10, 1, 1.8], [14, 2, 4], [12, 3, 2.5]])
assert np.array_equal(threshold_peaks(data, 2, param='BW'), np.array([[14, 2, 4], [1... |
def _dhcpHandler(packet_type):
def decorator(f):
def wrappedHandler(self, packet, source_address, port):
with _PacketWrapper(self, packet, packet_type, source_address, port) as wrapper:
if (not wrapper.valid):
return
f(self, wrapper)
re... |
class VmMigrate(APIView):
def __init__(self, request, hostname_or_uuid, data):
super(VmMigrate, self).__init__(request)
self.hostname_or_uuid = hostname_or_uuid
self.data = data
self.vm = get_vm(request, hostname_or_uuid, exists_ok=True, noexists_fail=True)
def put(self):
... |
.django_db
def test_GmSettleRewards(Q, auth_header):
from player.tests import PlayerFactory
PlayerFactory.create()
PlayerFactory.create()
g = GameFactory.create()
game = {'gameId': g.id, 'name': 'foo!', 'type': 'THBattle2v2', 'flags': {}, 'players': [1, 2], 'winners': [1], 'deserters': [2], 'started... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.