code stringlengths 281 23.7M |
|---|
def check_logged_in():
print('\nVerifying logged in to Platform.sh CLI...')
auth_info_output = make_sp_call('platform auth:info --quiet', capture_output=True)
if ('LoginRequiredException' in auth_info_output.stderr.decode()):
msg = '\n----- Error: Not logged in through CLI -----'
msg += '\nP... |
class QemuExecInstaller(AbstractPluginInstaller):
base_path = Path(__file__).resolve().parent
def install_docker_images(self):
self._build_docker_image('fact/qemu-exec:alpine-3.18')
def install_files(self):
with TemporaryDirectory(dir=str(self.base_path)) as tmp_dir:
if (Path(f'{... |
def render_notebook(*args, **kwargs):
import markdown
from pymdownx import slugs, superfences
from js import document
gamut = kwargs.get('gamut', WEBSPACE)
text = globals().get('content', '')
extensions = ['markdown.extensions.toc', 'markdown.extensions.smarty', 'pymdownx.betterem', 'markdown.ex... |
def iter_seq(seq):
(seqnum, name, seq, servers, dbtype, evalue_thr, score_thr, max_hits, maxseqlen, fixed_Z, skip, cut_ga) = seq
num_servers = len(servers)
num_server = (seqnum % num_servers)
(host, port) = servers[num_server]
if (skip and (name in skip)):
return (name, (- 1), ['SKIPPED'], l... |
def confirm_use_org_name(org_name):
msg = dedent(f'''
--- The Platform.sh CLI requires an organization name when creating a new project. ---
When using --automate-all, a project will be created on your behalf. The following
organization name was found: {org_name}
This organization wi... |
_lxml
def test_simple_xml():
xml = BeautifulSoup(SIMPLE_XML, 'xml')
assert xml.select_one('Envelope')
assert xml.select_one('Envelope Header')
assert xml.select_one('Header')
assert (not xml.select_one('envelope'))
assert (not xml.select_one('envelope header'))
assert (not xml.select_one('he... |
def _cmd_scatter(args):
cnarr = (read_cna(args.filename, sample_id=args.sample_id) if args.filename else None)
segarr = (read_cna(args.segment, sample_id=args.sample_id) if args.segment else None)
varr = load_het_snps(args.vcf, args.sample_id, args.normal_id, args.min_variant_depth, args.zygosity_freq)
... |
class TestExon(unittest.TestCase):
def test_exon_no_data(self):
exon = Exon('PSR.hg.1', 'A1BG')
self.assertEqual(exon.name, 'PSR.hg.1')
self.assertEqual(exon.gene_symbol, 'A1BG')
self.assertEqual(exon.log2_fold_change, None)
self.assertEqual(exon.p_value, None)
self.a... |
def downgrade():
op.drop_index(op.f('ix_privacyexperiencehistory_regions'), table_name='privacyexperiencehistory')
op.drop_index(op.f('ix_privacyexperiencehistory_id'), table_name='privacyexperiencehistory')
op.drop_table('privacyexperiencehistory')
op.drop_index(op.f('ix_privacyexperience_regions'), ta... |
def extractTakemewithyuuHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('gomene onii-sama', 'Gomen ne, Onii-sama', 'translated'), ('', 'Gomen ne, Onii-sama', 'translate... |
def fortios_firewall(data, fos, check_mode):
fos.do_member_operation('firewall', 'internet-service-addition')
if data['firewall_internet_service_addition']:
resp = firewall_internet_service_addition(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_i... |
def vm_deploy(vm, force_stop=False):
if force_stop:
cmd = ('vmadm stop %s -F >/dev/null 2>/dev/null; vmadm get %s 2>/dev/null' % (vm.uuid, vm.uuid))
else:
cmd = ('vmadm start %s >/dev/null 2>/dev/null; vmadm get %s 2>/dev/null' % (vm.uuid, vm.uuid))
msg = 'Deploy server'
lock = ('vmadm d... |
def lazy_import():
from fastly.model.historical_ddos import HistoricalDdos
from fastly.model.historical_ddos_meta import HistoricalDdosMeta
from fastly.model.platform_ddos_response_all_of import PlatformDdosResponseAllOf
from fastly.model.platform_ddos_response_data import PlatformDdosResponseData
g... |
class Sso(MethodView):
def __init__(self):
if (CRACK_CONF['auth']['type'] == 'saml2'):
self.meta_url = CRACK_CONF['auth']['saml_manifest']
self.meta_file = CRACK_CONF['auth']['meta_file']
self.entity_id = CRACK_CONF['auth']['entity_id']
self.group = CRACK_CONF... |
class Endpoint():
states = ['known', 'unknown', 'operating', 'queued']
transitions = [endpoint_transit_wrap('operate', 'unknown', 'operating'), endpoint_transit_wrap('queue', 'unknown', 'queued'), endpoint_transit_wrap('operate', 'known', 'operating'), endpoint_transit_wrap('queue', 'known', 'queued'), endpoint... |
class OptionSeriesDumbbellLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(text, j... |
def test_header_chain_get_vm_class_for_block_number(base_db, genesis_header):
chain = ChainForTesting.from_genesis_header(base_db, genesis_header)
assert (chain.get_vm_class_for_block_number(0) is VM_A)
for num in range(1, 10):
assert (chain.get_vm_class_for_block_number(num) is VM_A)
assert (ch... |
def check_lastfm(force_check=False):
providers = get_search_providers()
print(providers)
print(force_check)
if (force_check or ('lastfm-search' in providers)):
connected = lastfm_connected()
print(connected)
return connected
elif (not ('lastfm-search' in providers)):
... |
class OptionSeriesLineSonificationTracksMappingPan(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):
self._config(... |
class OptionPlotoptionsItemSonificationContexttracksActivewhen(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: float)... |
class TextNotesTab(QWidget):
def __init__(self, parent):
self.parent = parent
QWidget.__init__(self)
self.setup_ui()
def setup_ui(self):
self.vbox_right = QVBoxLayout()
r_lbl = QLabel('Text notes, not in Queue')
r_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
... |
.integration()
def test_delete_simple_folder(random_file, fsspec_write_test_folder):
random_folder = random_file.get()
file1 = random_file.get()
file1_in_folder = f'{random_folder}/{file1}'
file2 = random_file.get()
file2_in_folder = f'{random_folder}/{file2}'
fs = FoundryFileSystem(dataset=fssp... |
class OptionSeriesHeatmapSonificationDefaultinstrumentoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: b... |
def unpackage():
rootDir = getRootDir.getEnvsDir()
compressed = getArg.getArg(0)
if (not compressed):
sys.exit(text.unpackageHelper)
if (not isRoot.isRoot()):
sys.exit(text.notRoot)
if (not remove.checkIfExists(compressed)):
sys.exit(text.packageDoesntExist)
env = compres... |
def test_does_not_count_multiple_kicks(paragon_chain):
head = paragon_chain.get_canonical_head()
clique = get_clique(paragon_chain)
snapshot = validate_seal_and_get_snapshot(clique, head)
assert (len(snapshot.tallies) == 0)
alice_votes_bob = make_next_header(paragon_chain, head, ALICE_PK, coinbase=B... |
def upgrade():
op.add_column('updates', sa.Column('autotime', sa.Boolean()))
op.execute('UPDATE updates SET autotime=FALSE')
op.alter_column('updates', 'autotime', existing_type=sa.Boolean(), nullable=False)
op.add_column('updates', sa.Column('stable_days', sa.Integer()))
op.execute('UPDATE updates ... |
.requires_window_manager
('ert.gui.tools.run_analysis.run_analysis_tool.QMessageBox')
('ert.gui.tools.run_analysis.run_analysis_tool.smoother_update')
(RunAnalysisTool, '_enable_dialog', new=(lambda self, enable: None))
def test_success(mock_esupdate, mock_msgbox, mock_tool, qtbot):
mock_tool.run()
qtbot.waitUn... |
def test_bkz_bkz():
for (m, n) in dimensions:
if ((m < 2) or (n < 2)):
continue
A = make_integer_matrix(m, n)
b00 = []
for float_type in float_types:
B = copy(A)
M = GSO.Mat(B, float_type=float_type)
lll_obj = LLL.Reduction(M)
... |
def _maybe_add_example_with_dropped_nonviolated_prompt_categories(training_example: TrainingExample, formatted_examples_being_built: List[str], indices_of_all_categories: range, nonviolated_category_indices: List[int], formatter_configs: FormatterConfigs) -> None:
if (not formatter_configs.augmentation_configs.shou... |
class TestGetConnectionDataset():
def test_get_dataset_not_authenticated(self, dataset_config, connection_config, api_client) -> None:
dataset_url = get_connection_dataset_url(connection_config, dataset_config)
response = api_client.get(dataset_url, headers={})
assert (response.status_code =... |
def main(args: Optional[List[str]]=None) -> Any:
args = (args or sys.argv[1:])
if ((not args) or (args == ['--help'])):
_print_usage()
_print_help()
sys.exit(0)
else:
script_name = args[0]
scripts = {script.name: script for script in entry_points(group='console_scripts')}... |
def main():
module = AnsibleModule(argument_spec=dict(server_url=dict(required=True, default=None, aliases=['url']), login_user=dict(required=True), login_password=dict(required=True), template=dict(required=True), state=dict(default='present'), timeout=dict(default=10, type='int'), target=dict(required=False), for... |
class TestBootstrapHookHandler():
class UnitTestComponentLoader():
def __init__(self, root_path, component_entry_point, recurse):
self.root_path = root_path
self.component_entry_point = component_entry_point
self.recurse = recurse
self.registration_function = ... |
def test_load_data(mocker):
content = 'temp.json'
mock_document = {'doc_id': hashlib.sha256((content + ', '.join(['content1', 'content2'])).encode()).hexdigest(), 'data': [{'content': 'content1', 'meta_data': {'url': content}}, {'content': 'content2', 'meta_data': {'url': content}}]}
mocker.patch('embedchai... |
(urls.POLICY_DETAIL, status_code=HTTP_200_OK, response_model=schemas.PolicyResponse, dependencies=[Security(verify_oauth_client, scopes=[scope_registry.POLICY_READ])])
def get_policy(*, policy_key: FidesKey, db: Session=Depends(deps.get_db)) -> schemas.Policy:
return get_policy_or_error(db, policy_key) |
def dq_a2(m0, m1, m2, o0, o1, o2, n0, n1, n2):
x0 = (- o0)
x1 = (n0 + x0)
x2 = (m0 + x0)
x3 = (- o1)
x4 = (n1 + x3)
x5 = (m1 + x3)
x6 = (((- x1) * x5) + (x2 * x4))
x7 = (- o2)
x8 = (n2 + x7)
x9 = (m2 + x7)
x10 = ((x1 * x9) - (x2 * x8))
x11 = (((- x4) * x9) + (x5 * x8))
... |
def test_wf1_with_list_of_inputs():
def t1(a: int) -> typing.NamedTuple('OutputsBC', t1_int_output=int, c=str):
return ((a + 2), 'world')
def t2(a: typing.List[str]) -> str:
return ' '.join(a)
def my_wf(a: int, b: str) -> (int, str):
(xx, yy) = t1(a=a)
d = t2(a=[b, yy])
... |
def main(args):
motion = bvh.load(args.input_file)
trajectory = motion.positions(local=False).reshape(motion.num_frames(), (- 1))
print('Total length (in s) ', motion.length())
acc = np.diff(trajectory, n=2, axis=0)
acc_norm = np.linalg.norm(acc, axis=1)
segs = find_peaks(acc_norm, height=0.075)... |
def bump_version(v: version.Version, level: str) -> str:
release: List[int] = list(v.release)
stage: Optional[str]
pre: Optional[int]
(stage, pre) = (v.pre if v.pre else (None, None))
dev: Optional[int] = v.dev
post: Optional[int] = v.post
if (level in ('major', 'minor', 'patch')):
s... |
class OptionSeriesTimelineDragdrop(Options):
def draggableX(self):
return self._config_get(None)
def draggableX(self, flag: bool):
self._config(flag, js_type=False)
def draggableY(self):
return self._config_get(None)
def draggableY(self, flag: bool):
self._config(flag, js... |
class DecisionStateMachine():
def get_decision(self) -> Optional[Command]:
raise NotImplementedError
def cancel(self, immediate_cancellation_callback: Callable) -> bool:
raise NotImplementedError
def handle_started_event(self, event: HistoryEvent):
raise NotImplementedError
def h... |
class Solution():
def gameOfLife(self, board: List[List[int]]) -> None:
def find_live_neighbors(board, i, j):
directions = [((- 1), (- 1)), ((- 1), 0), ((- 1), 1), (0, (- 1)), (0, 1), (1, (- 1)), (1, 0), (1, 1)]
num = 0
for (yd, xd) in directions:
(y, x) =... |
class TestMappings(BaseRuleTest):
FP_FILES = get_fp_data_files()
def evaluate(self, documents, rule, expected, msg):
filtered = evaluate(rule, documents)
self.assertEqual(expected, len(filtered), msg)
return filtered
def test_true_positives(self):
mismatched_ecs = []
... |
class OptionPlotoptionsVectorSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionPlotoptionsVectorSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsVectorSonificationDefaultinstrumentoptionsActivewhen)
def instrument(se... |
def extractThemtlgWordpressCom(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) i... |
def extractMochadelighttranslationWordpressCom(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, ... |
class SizedArrayEncoder(BaseArrayEncoder):
array_size = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.is_dynamic = self.item_encoder.is_dynamic
def validate(self):
super().validate()
if (self.array_size is None):
raise ValueError('`array_size`... |
class SettingsGroup(db.Model, CRUDMixin):
__tablename__ = 'settingsgroup'
key = db.Column(db.String(255), primary_key=True)
name = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text, nullable=False)
settings = db.relationship('Setting', lazy='dynamic', backref='group', cascade... |
class Slider(Html.Html):
requirements = ('jqueryui',)
name = 'Slider'
_option_cls = OptSliders.OptionsSlider
is_range = False
def __init__(self, page: primitives.PageModel, number: int, min_val: float, max_val: float, width: tuple, height: tuple, helper: Optional[str], options: Optional[dict], html_... |
class ClassSelect(GrpCls.ClassHtml):
def __init__(self, component: primitives.HtmlModel):
super(ClassSelect, self).__init__(component)
(self._css_class_dt, self._css_class_dt_ui, self._css_select) = (None, None, None)
(self._css_select_input, self._css_item_option, self._css_item_options, se... |
_mock.patch('flytekit.clients.friendly._RawSynchronousFlyteClient.list_projects')
def test_list_projects_paginated(mock_raw_list_projects):
client = _SynchronousFlyteClient(PlatformConfig.for_endpoint('a.b.com', True))
client.list_projects_paginated(limit=100, token='')
project_list_request = _project_pb2.P... |
('model')
def check_no_namespace(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
if len(pm.listNamespaces()):
progress_controller.complete()
raise PublishError('There should be no <b>Namespaces</b> in a <b>Model</b> scene.')
... |
def on_array(default=None):
def outer(f):
(f)
def wrapper(a, **kwargs):
a = np.asfarray(a)
a = a[(~ np.isnan(a))]
if (not len(a)):
return np.nan
if (len(a) == 1):
if (default is None):
return a[0]
... |
def get_valid_jump_destinations(code: bytes) -> Set[Uint]:
valid_jump_destinations = set()
pc = Uint(0)
while (pc < len(code)):
try:
current_opcode = Ops(code[pc])
except ValueError:
pc += 1
continue
if (current_opcode == Ops.JUMPDEST):
... |
def _get_dbt_packages() -> Iterator[Tuple[(str, Optional[str])]]:
package_distributions = importlib_metadata.packages_distributions()
for dbt_plugin_name in package_distributions.get('dbt', []):
distribution = importlib_metadata.distribution(dbt_plugin_name)
if (dbt_plugin_name == 'dbt-core'):
... |
def extractArkMachineTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('ark volume' in item['title'].lower()):
return buildReleaseMessageWithType(item, 'Ark', vol, c... |
class FuncCall(Node):
__slots__ = ('name', 'args', 'coord', '__weakref__')
def __init__(self, name, args, coord=None):
self.name = name
self.args = args
self.coord = coord
def children(self):
nodelist = []
if (self.name is not None):
nodelist.append(('name... |
def download_and_extract(archive, dest_dir, filename_prefix='', clobber=True):
debug_print((((('download_and_extract(archive=' + archive) + ', dest_dir=') + dest_dir) + ')'))
url = urljoin(emsdk_packages_url, archive)
def try_download(url, silent=False):
return download_file(url, download_dir, (not ... |
class TopologyView(GenericViewSet):
queryset = NetworkSliceSubnet.objects.all()
serializer_class = NetworkSliceSubnetTopologySerializer
def list(self, request):
queryset = self.filter_queryset(self.get_queryset())
serializer = self.serializer_class(queryset, many=True)
nsinfo_object ... |
def min_length_discard(records, min_length):
logging.info('Applying _min_length_discard generator: discarding records shorter than %d.', min_length)
for record in records:
if (len(record) < min_length):
logging.debug('Discarding short sequence: %s, length=%d', record.id, len(record))
... |
def test_liveness_if_else(construct_graph_if_else, variable_u, variable_v, aliased_variables_y, aliased_variables_z):
(nodes, cfg) = construct_graph_if_else
liveness_analysis = LivenessAnalysis(cfg)
assert ((liveness_analysis.live_in_of(nodes[0]) == {aliased_variables_y[1], aliased_variables_z[2]}) and (liv... |
def main():
parser = argparse.ArgumentParser(description='Runs clang-tidy over all files in a compilation database. Requires clang-tidy and clang-apply-replacements in $PATH or in your build directory.')
parser.add_argument('-allow-enabling-alpha-checkers', action='store_true', help='allow alpha checkers from c... |
def test_deeply_nested_optional_parameter_groups():
grandparent: GrandParent = GrandParent.setup()
assert (grandparent.niece is None)
assert (grandparent.nephew is None)
grandparent: GrandParent = GrandParent.setup('--niece.child.name Bob')
assert (grandparent.niece == Parent(child=Child(name='Bob')... |
class SchemaV1(SchemaAPI):
def make_canonical_head_hash_lookup_key() -> bytes:
return b'v1:canonical_head_hash'
def make_block_number_to_hash_lookup_key(block_number: BlockNumber) -> bytes:
number_to_hash_key = (b'block-number-to-hash:%d' % block_number)
return number_to_hash_key
def... |
def count_calls_to(utility_name, call_list, call_contains=None):
count = 0
for cmd in call_list:
if cmd.startswith(utility_name):
if (call_contains != None):
if (call_contains in cmd):
count += 1
else:
count += 1
return coun... |
class solver(object):
def __init__(self, step=1.0, accel=None):
if (step < 0):
raise ValueError('Step should be a positive number.')
self.step = step
self.accel = (acceleration.dummy() if (accel is None) else accel)
def pre(self, functions, x0):
self.sol = np.asarray(... |
def test_tensor_function_zero_with_subset(W):
f = Function(W)
assert (W.node_set.size > 3)
subset = op2.Subset(W.node_set, [0, 1, 2])
f.assign(1)
assert np.allclose(f.dat.data_ro, 1.0)
f.zero(subset=subset)
assert np.allclose(f.dat.data_ro[:3], 0.0)
assert np.allclose(f.dat.data_ro[3:], ... |
def test_sign_and_recover_message_public_key(ethereum_private_key_file):
account = EthereumCrypto(ethereum_private_key_file)
sign_bytes = account.sign_message(message=b'hello')
assert (len(sign_bytes) > 0), 'The len(signature) must not be 0'
recovered_public_keys = EthereumApi.recover_public_keys_from_m... |
def test_memoize():
def foo(*args, **kwargs):
calls.append(None)
return (args, kwargs)
calls = []
for x in range(2):
ret = foo()
expected = ((), {})
assert (ret == expected)
assert (len(calls) == 1)
for x in range(2):
ret = foo(1)
expected ... |
class GuidedDeathEffect(GenericAction):
def __init__(self, source, target_list):
self.source = source
self.target = source
self.target_list = target_list
def apply_action(self):
g = self.game
for p in self.target_list:
g.process_action(GuidedDeathLifeLost(p, p... |
_converter(acc_ops.avg_pool2d)
def acc_ops_avg_pool2d(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput:
input_val = ait_nchw2nhwc(kwargs['input'])
if (not isinstance(input_val, AITTensor)):
raise RuntimeError(f'Non-tensor inputs for {name}: {inpu... |
def name_replace(records, search_regex, replace_pattern):
regex = re.compile(search_regex)
for record in records:
maybe_id = record.description.split(None, 1)[0]
if (maybe_id == record.id):
record.description = regex.sub(replace_pattern, record.description)
record.id = re... |
def test_data_act_database_url_and_parts_error_if_inconsistent_none_parts():
consistent_dict = {ENV_CODE_VAR: _UnitTestDbPartsNoneConfig.ENV_CODE, 'DATABASE_URL': 'postgres://dummy::12345/fresh_new_db_name', 'DATA_BROKER_DATABASE_URL': 'postgres://broker:-foobar:54321/fresh_new_db_name_broker', 'BROKER_DB_HOST': 'b... |
def is_item_present_unified(ctx: Context, item_type: str, item_public_id: PublicId) -> bool:
is_in_vendor = is_item_present(ctx.cwd, ctx.agent_config, item_type, item_public_id, is_vendor=True)
if (item_public_id.author != ctx.agent_config.author):
return is_in_vendor
return (is_in_vendor or is_item... |
class frozenmultiset(TestCase):
def test_constructor(self):
src = ('spam', 'bacon', 'sausage', 'spam')
for (name, value) in [('tuple', src), ('frozenmultiset', nutils.types.frozenmultiset(src))]:
with self.subTest(name=name):
frozen = nutils.types.frozenmultiset(value)
... |
class UnderscoreProcessor(util.PatternSequenceProcessor):
PATTERNS = [util.PatSeqItem(re.compile(UNDER_STRONG_EM, (re.DOTALL | re.UNICODE)), 'double', 'strong,em'), util.PatSeqItem(re.compile(UNDER_EM_STRONG, (re.DOTALL | re.UNICODE)), 'double', 'em,strong'), util.PatSeqItem(re.compile(UNDER_STRONG_EM2, (re.DOTALL ... |
class TestMakeDefaultExpiresAt(TestCase):
def test_disabled(self):
conf = config.ExpireTimeDefaultSettings(ENABLE=False)
result = helpers.make_default_expires_at(conf)
self.assertIsNone(result)
def test_enabled(self):
conf = config.ExpireTimeDefaultSettings(ENABLE=True, MINUTES=0... |
def run(interface, app, host='127.0.0.1', port=8000, loop='auto', loop_opt=False, log_level=None, workers=1, threads=1, threading_mode='workers', backlog=1024, enable_websockets=True, ssl_certfile: Optional[str]=None, ssl_keyfile: Optional[str]=None):
app_path = ':'.join([app[0], (app[1] or 'app')])
runner = Gr... |
def fix_line(line, site, filetype):
assert (filetype in ['timings', 'pins', 'properties']), 'Unsupported filetype'
line = line.split()
newline = list()
sites_count = int(line[1])
newline.append(line[0])
newline.append('1')
newline.append(site)
newline.append('1')
newline.append(site)... |
def get_boolean_from_request(request_parameters: ImmutableMultiDict, name: str) -> bool:
try:
parameter = json.loads(request_parameters.get(name, 'false'))
if (not isinstance(parameter, bool)):
raise TypeError()
except (AttributeError, KeyError):
return False
except (json... |
class TestLayoutBlock():
def test_should_parse_text_with_two_tokens(self):
layout_block = LayoutBlock.for_text('token1 token2', tail_whitespace='\n')
assert ([(token.text, token.whitespace) for token in layout_block.lines[0].tokens] == [('token1', ' '), ('token2', '\n')])
def test_should_parse_t... |
def CustomEnumEditor(parent, factory, ui, object, name, description, style='custom', **kwargs):
if (factory._enum is None):
import traitsui.editors.enum_editor as enum_editor
factory._enum = enum_editor.ToolkitEditorFactory(values=list(range(factory.low, (factory.high + 1))), cols=factory.cols)
... |
class UnaryOp(OperatorInterface):
def __init__(self, func_name: str):
super(UnaryOp, self).__init__()
self.func_name: str = func_name
self.fwd_out: torch.tensor = None
self.grad_in: torch.tensor = None
def forward(self, *args, **kwargs):
with torch.no_grad():
... |
_as_global_kernel_arg.register(CellFacetKernelArg)
def _as_global_kernel_arg_cell_facet(_, self):
if self._mesh.extruded:
num_facets = self._mesh._base_mesh.ufl_cell().num_facets()
else:
num_facets = self._mesh.ufl_cell().num_facets()
return op2.DatKernelArg((num_facets, 2)) |
def test_outlay_calculations(client, awards_and_transactions):
defc = baker.make('references.DisasterEmergencyFundCode', code='L')
baker.make('submissions.DABSSubmissionWindowSchedule', submission_fiscal_year=2019, submission_fiscal_month=12, is_quarter=True, submission_reveal_date='2020-04-01', period_start_da... |
def test_filter_structures():
s1 = td.Structure(geometry=td.Box(size=(1, 1, 1)), medium=SCENE.medium)
s2 = td.Structure(geometry=td.Box(size=(1, 1, 1), center=(1, 1, 1)), medium=SCENE.medium)
plane = td.Box(center=(0, 0, 1.5), size=(td.inf, td.inf, 0))
SCENE._filter_structures_plane_medium(structures=[s... |
def downgrade():
op.create_table('modules', sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), sa.Column('ticket_include', sa.BOOLEAN(), autoincrement=False, nullable=True), sa.Column('payment_include', sa.BOOLEAN(), autoincrement=False, nullable=True), sa.Column('donation_include', sa.BOOLEAN(), au... |
def test_insert_intersecting_cases_before(task):
condition_handler = ConditionHandler()
cond_2_symbol = condition_handler.add_condition(Condition(OperationType.equal, [var_c, const[2]]))
ast = AbstractSyntaxForest(condition_handler=condition_handler)
root = ast.factory.create_seq_node()
missing_case... |
class bdist_wheel(Command):
description = 'create a wheel distribution'
user_options = [('bdist-dir=', 'b', 'temporary directory for creating the distribution'), ('plat-name=', 'p', ('platform name to embed in generated filenames (default: %s)' % get_platform())), ('keep-temp', 'k', ('keep the pseudo-installati... |
def log_sites_summary(log, loci, s_vars):
(s_total, s_mean, s_ci, s_min, s_max) = s_vars
text = ' Informative Sites summary '
log.info(text.center(65, '-'))
log.info('[Sites] loci:\t{:,}'.format(loci))
log.info('[Sites] total:\t{:,}'.format(s_total))
log.info('[Sites] mean:\t{:.2f}'.format(s_mea... |
def filter_versioned_items(items: t.Iterable[_VersionedObj], constraints: t.Iterable[t.Tuple[(str, _ComparableObj)]], to_version: t.Callable[([_VersionedObj], _ComparableObj)], sort=False) -> t.List[_VersionedObj]:
constraints = list(constraints)
new_items = []
for item in items:
version = to_versio... |
def evaljs(jscode, whitespace=True, print_result=True, extra_nodejs_args=None):
global _eval_count
cmd = [get_node_exe()]
if extra_nodejs_args:
cmd.extend(extra_nodejs_args)
if (len(jscode) > (2 ** 14)):
if print_result:
raise RuntimeError('evaljs() wont send more than 16 kB ... |
_required
_required
_POST
def nic_settings_form(request, hostname):
vm = get_vm(request, hostname)
if request.user.is_admin(request):
action = None
form = AdminServerNicSettingsForm(request, vm, request.POST, prefix='opt-nic')
else:
action = 'update'
form = ServerNicSettingsF... |
class TestAcceptAnyArg(TestCase):
def test_for_partial_call_accepts_all_other_args(self):
self.mock_callable(sample_module, 'test_function').for_partial_call('a').to_return_value(['blah'])
sample_module.test_function('a', 'b')
def test_for_partial_call_accepts_all_other_kwargs(self):
sel... |
.skipif((not (keras_weights_available and torch_weights_available)), reason='CRAFT weights required.')
def test_pytorch_identical_output():
import torch
weights_path_torch = keras_ocr.tools.download_and_verify(url=' filename='craft_mlt_25k.pth', sha256='4a5efbfb48be75e1e2b57f8de3d84f213004b14b85fd4b3748db17')
... |
def extractFakTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if (('Shrouding the Heavens' in item['tags']) or ('STH' in item['tags'])):
return buildReleaseMes... |
class OptionSeriesPackedbubbleSonificationContexttracksMappingTremoloSpeed(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 Handler(metaclass=MetaHandler):
__slots__ = ['app']
def __init__(self, app):
self.app = app
def on_event(cls, event: str) -> Callable[([EventHandler], EventHandlerWrapper)]:
def wrap(f: EventHandler) -> EventHandlerWrapper:
return EventHandlerWrapper(event, f)
retur... |
class Okhsl(HSL):
BASE = 'oklab'
NAME = 'okhsl'
SERIALIZE = ('--okhsl',)
CHANNELS = (Channel('h', 0.0, 360.0, bound=True, flags=FLG_ANGLE), Channel('s', 0.0, 1.0, bound=True), Channel('l', 0.0, 1.0, bound=True))
CHANNEL_ALIASES = {'hue': 'h', 'saturation': 's', 'lightness': 'l'}
def to_base(self... |
_module()
class NsfHifiGAN(pl.LightningModule):
def __init__(self, checkpoint_path: str='checkpoints/nsf_hifigan/model', config_file: Optional[str]=None, use_natural_log: bool=True, **kwargs):
super().__init__()
if (config_file is None):
config_file = (Path(checkpoint_path).parent / 'con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.