code stringlengths 281 23.7M |
|---|
class DictValues():
def __init__(self, dct: Dict[(str, str)], enum_key: Dict[(Color, str)], dataclass_val: Dict[(str, User)], passthrough_dict: Dict[(str, LibraryClass)], def_value: Dict[(str, str)]={}):
self.dct = dct
self.enum_key = enum_key
self.dataclass_val = dataclass_val
self.... |
(short_help='Azure Repository')
('--name', required=True, type=str, help='Repository name')
('--client', default='default', show_default=True, type=str, help='Azure named client to use.')
('--container', default='elasticsearch-snapshots', show_default=True, type=str, help='Container name. You must create the Azure cont... |
.django_db
def test_tas_filter_inappropriate_characters(client, monkeypatch, elasticsearch_award_index, award_with_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas(client, {'require': [['011', '[abc]']]})
assert (resp.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY), '... |
class CropscaleThumbnailer(Thumbnailer):
THUMBNAIL_SIZE_RE = re.compile('^(?P<w>\\d+)x(?P<h>\\d+)(-(?P<x>\\d+)x(?P<y>\\d+))?$')
MARKER = '_cropscale_'
def generate(self, storage, original, size, miniature):
with storage.open(original) as original_handle:
with BytesIO(original_handle.read... |
class Components():
def __init__(self, ui):
self.page = ui.page
def alert(self, kind: str=None, components: List[primitives.HtmlModel]=None, width: types.SIZE_TYPE=(100, '%'), height: types.SIZE_TYPE=(None, 'px'), html_code: str=None, options: dict=None, profile: types.PROFILE_TYPE=None):
conten... |
class SyncTrainingTimeEstimator(TrainingTimeEstimator):
def __init__(self, total_users: int, users_per_round: int, epochs: int, training_dist: IDurationDistribution, num_examples: Optional[List[int]]=None):
super().__init__(total_users=total_users, users_per_round=users_per_round, epochs=epochs, num_example... |
class _DoNormalize(Cursor_Rewrite):
def __init__(self, proc):
self.C = Sym('temporary_constant_symbol')
self.env = IndexRangeEnvironment(proc._loopir_proc)
self.ir = proc._loopir_proc
self.fwd = (lambda x: x)
super().__init__(proc)
new_preds = self.map_exprs(self.ir.p... |
def get_app_data_folder() -> str:
app_name = 'BCSFE_Python'
os_name = os.name
if (os_name == 'nt'):
path = os.path.join(os.environ['APPDATA'], app_name)
elif (os_name == 'mac'):
path = os.path.join(os.environ['HOME'], 'Library', 'Application Support', app_name)
elif (os_name == 'posi... |
class DecoderFactory(McapDecoderFactory):
def __init__(self):
self._types: Dict[(int, Type[Any])] = {}
def _get_message_classes(self, file_descriptors: Iterable[FileDescriptorProto]):
descriptor_by_name = {file_descriptor.name: file_descriptor for file_descriptor in file_descriptors}
fac... |
def unsupported_node_fixer(bmg: BMGraphBuilder, typer: LatticeTyper) -> NodeFixer:
usnf = UnsupportedNodeFixer(bmg, typer)
return node_fixer_first_match([type_guard(bn.Chi2Node, usnf._replace_chi2), type_guard(bn.DivisionNode, usnf._replace_division), type_guard(bn.Exp2Node, usnf._replace_exp2), type_guard(bn.I... |
_db(transaction=True)
def test_load_table_to_delta_for_sam_recipient(spark, s3_unittest_data_bucket, populate_broker_data):
expected_data = [{'awardee_or_recipient_uniqu': '', 'legal_business_name': 'EL COLEGIO DE LA FRONTERA SUR', 'dba_name': 'RESEARCH CENTER', 'ultimate_parent_unique_ide': '', 'ultimate_parent_le... |
def test_flow_predicate():
root = FlowRoot('test', 'This is my flowroot')
node = root.connect('a', (lambda ctx: (('toto' in ctx) and (ctx['toto'] == 'titui'))))
somebody = TestPerson('me')
flow = Flow(root, somebody, {})
assert (node in flow.next_steps())
assert (node not in flow.next_autosteps(... |
def test_mapping_saved_into_es(write_client):
m = mapping.Mapping()
m.field('name', 'text', analyzer=analysis.analyzer('my_analyzer', tokenizer='keyword'))
m.field('tags', 'keyword')
m.save('test-mapping', using=write_client)
assert ({'test-mapping': {'mappings': {'properties': {'name': {'type': 'te... |
def get_high_incidence_issues():
with db_pool.db_cursor() as cur:
cur.execute('\n\t\t\tSELECT\n\t\t\t\tdbid,\n\t\t\t\tphash,\n\t\t\t\tmatch_count,\n\t\t\t\tdistance\n\t\t\tFROM\n\t\t\t\thigh_incidence_hashes\n\t\t\tORDER BY\n\t\t\t\tmatch_count DESC\n\t\t\tLIMIT\n\t\t\t\t5000\n\t\t\t\t;')
rets = cur... |
class FBTapLoggerCommand(fb.FBCommand):
def name(self):
return 'taplog'
def description(self):
return 'Log tapped view to the console.'
def run(self, arguments, options):
parameterExpr = objc.functionPreambleExpressionForObjectParameterAtIndex(0)
breakpoint = lldb.debugger.Ge... |
class TabsExtraSortMenuCommand(sublime_plugin.WindowCommand):
def run(self):
sort_layout = sublime.load_settings(SETTINGS).get('sort_layout', [])
if len(sort_layout):
self.sort_commands = []
sort_menu = []
for sort_entry in sort_layout:
caption = s... |
def test_template_rendering(instrument, django_elasticapm_client, client):
with override_settings(**middleware_setting(django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware'])):
client.get(reverse('render-heavy-template'))
client.get(reverse('render-heavy-template'))
clien... |
class PrivateComputationPrivateIdDfcaStageFlow(PrivateComputationBaseStageFlow):
_order_ = 'CREATED PC_PRE_VALIDATION PID_SHARD PID_PREPARE ID_MATCH ID_MATCH_POST_PROCESS ID_SPINE_COMBINER PRIVATE_ID_DFCA_AGGREGATE POST_PROCESSING_HANDLERS'
CREATED = PrivateComputationStageFlowData(initialized_status=PrivateCom... |
def hmm_alignments(n, seed, n_alignments, hmmfile):
cmd = f'hmmemit -a -N {n} --seed {seed} {hmmfile}'
proc = Popen(cmd, shell=True, stdout=PIPE)
proc.wait()
lines = proc.stdout.readlines()
lines = list(map((lambda x: x.decode('utf-8')), lines))
lines = list(map((lambda x: x.rstrip().upper()), l... |
def test_kafka_send_unsampled_transaction(instrument, elasticapm_client, producer, topics):
transaction_object = elasticapm_client.begin_transaction('transaction')
transaction_object.is_sampled = False
producer.send('test', key=b'foo', value=b'bar')
elasticapm_client.end_transaction('foo')
spans = e... |
class TestApiGateway(TestCase):
api_endpoint: str
def get_stack_name(cls) -> str:
stack_name = os.environ.get('AWS_SAM_STACK_NAME')
if (not stack_name):
raise Exception('Cannot find env var AWS_SAM_STACK_NAME. \nPlease setup this environment variable with the stack name where we are ... |
class TestEntrypoint():
def test_empty_get_all(self, fledge_url, reset_and_start_fledge):
jdoc = self._get_all(fledge_url)
assert ([] == jdoc)
.parametrize('payload', [payload1, payload2, payload3])
def test_create(self, fledge_url, payload):
ep_name = payload['name']
conn = ... |
class OptionPlotoptionsStreamgraphDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._c... |
class BeautifierTest(unittest.TestCase):
def setUp(self):
super(BeautifierTest, self).setUp()
self.b = Beautifier()
def tearDown(self):
super(BeautifierTest, self).tearDown()
def testGetInputCmd(self):
cmd = ['test']
self.b.setInputCmd(cmd)
self.assertEqual(se... |
('foremast.utils.awslambda.boto3.Session')
def test_get_lambda_alias_arn_failure(mock_boto3):
client = mock_boto3.return_value.client.return_value
client.list_aliases.return_value = lambda_no_alias_list_mock()
with pytest.raises(LambdaAliasDoesNotExist):
get_lambda_alias_arn('lambdatest', 'dev', 'us... |
class WorkflowMethodTask(ITask):
task_id: str = None
workflow_input: Payloads = None
worker: Worker = None
workflow_type: WorkflowType = None
workflow_instance: object = None
ret_value: object = None
data_converter: DataConverter = None
def __post_init__(self):
logger.debug(f'[ta... |
.integration_saas
class TestHeapConnector():
def test_connection(self, heap_runner: ConnectorRunner):
heap_runner.test_connection()
async def test_non_strict_erasure_request(self, heap_runner: ConnectorRunner, policy: Policy, erasure_policy_string_rewrite: Policy, heap_erasure_identity_email: str):
... |
_toolkit([ToolkitName.qt])
(NO_WEBKIT_OR_WEBENGINE, 'Tests require either QtWebKit or QtWebEngine')
class TestHTMLEditor(BaseTestMixin, unittest.TestCase):
def setUp(self):
BaseTestMixin.setUp(self)
self.tester = get_custom_ui_tester()
def tearDown(self):
BaseTestMixin.tearDown(self)
... |
.parametrize('value, valuefilename', [([1, 2], '1-2.dlis.part'), ([0.5, 1.5], '0.5-1.5.dlis.part'), ([False, True], 'False-True.dlis.part'), (['val1', 'val2'], 'string-val1,val2.dlis.part'), ([(0.5, 1.5), (2.5, 3.5)], 'validated-(0.5-1.5),(2.5-3.5).dlis.part'), ([complex(0.5, 1.5), complex(2.5, 3.5)], 'complex-(0.5-1.5... |
class TransformerModel(Model):
def __init__(self, name: str, get_spans: Callable, tokenizer_config: dict={}, transformer_config: dict={}, mixed_precision: bool=False, grad_scaler_config: dict={}):
hf_model = HFObjects(None, None, None, tokenizer_config, transformer_config)
wrapper = HFWrapper(hf_mod... |
def extractOinktranslationsHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('his royal highness, wants a divorce!', 'his royal highness, wants a divorce!', 'translated')... |
class CloudBillingRepositoryClient(_base_repository.BaseRepositoryClient):
def __init__(self, quota_max_calls=None, quota_period=60.0, use_rate_limiter=True, cache_discovery=False, cache=None):
if (not quota_max_calls):
use_rate_limiter = False
self._billing_accounts = None
self.... |
class OptionSeriesTreegraphSonificationTracksMappingVolume(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.... |
class SlateWrapperBag():
def __init__(self, coeffs, constants):
self.coefficients = coeffs
self.constants = constants
self.inames = OrderedDict()
self.needs_cell_orientations = False
self.needs_cell_sizes = False
self.needs_cell_facets = False
self.needs_mesh_... |
class TacotronOneSeqwiseMultispeakerLSTMs(TacotronOneLSTMsBlock):
def __init__(self, n_vocab, embedding_dim=256, mel_dim=80, linear_dim=1025, r=5, num_spk=2, padding_idx=None, use_memory_mask=False):
super(TacotronOneSeqwiseMultispeakerLSTMs, self).__init__(n_vocab, embedding_dim=256, mel_dim=80, linear_dim... |
def _install_package(module, conda, installed, name, version, installed_version):
if (installed and ((version is None) or (installed_version == version))):
module.exit_json(changed=False, name=name, version=version)
if module.check_mode:
if ((not installed) or (installed and (installed_version !... |
('update')
('is_all', '--all', '-a', default=False, is_flag=True, help='Updates the plugin translations as well.')
('--plugin', '-p', type=click.STRING, help='Updates the language of the given plugin.')
def update_translation(is_all, plugin):
if (plugin is not None):
validate_plugin(plugin)
click.se... |
def test_task_failed():
task = Task()
assert (not task.failed)
task.future = asyncio.Future()
assert (not task.failed)
task.future.set_result(None)
assert (not task.failed)
task.future = asyncio.Future()
task.future.set_exception(KeyboardInterrupt())
assert (not task.failed)
task... |
def test_event_graph_accumulated_time_before_start(mocker: Any) -> None:
message = DeferredMessage(MyMessage, 'unittest_args', kwargs_field='unittest_kwargs')
topic = Topic(MyMessage)
start = Event(message, topic, 0.0, 1.0)
graph = EventGraph(start)
parent = Event(message, topic, 0.0, 1.0)
child... |
class TaskLog(_common.FlyteIdlEntity):
class MessageFormat(object):
UNKNOWN = _execution_pb2.TaskLog.UNKNOWN
CSV = _execution_pb2.TaskLog.CSV
JSON = _execution_pb2.TaskLog.JSON
def __init__(self, uri: str, name: str, message_format: typing.Optional[MessageFormat]=None, ttl: typing.Option... |
class ServiceManagementClient(object):
DEFAULT_MAX_RESULTS = 100
def __init__(self, global_configs, **kwargs):
(max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME)
cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) el... |
def get_data(first_url, second_url):
first_response = send_request(first_url)
second_response = send_request(second_url)
first_content = str(first_response.content)
second_content = str(second_response.content)
first_subdomain_first_filter = re.findall('(?:<TD>)(.*?)</TD>', first_content)
second... |
def filter_firewall_vipgrp_data(json):
option_list = ['color', 'comments', 'interface', 'member', 'name', 'uuid']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[... |
def get_filesystem_event_details(io, metadata, event, extra_detail_io):
sub_operation = read_u8(io)
io.seek(3, 1)
if ((0 != sub_operation) and (FilesystemOperation[event.operation] in FilesystemSubOperations)):
try:
event.operation = FilesystemSubOperations[FilesystemOperation[event.oper... |
class WebhooksResultGenerator(CursorResultsGenerator):
def process_page(self):
search_results = list()
for object_json in self._response_json['webhooks']:
search_results.append(self.response_handler.api._object_mapping.object_from_json('webhook', object_json))
return search_resul... |
.django_db
def test_extract_business_categories(monkeypatch):
recipient_hash = 'a52a7544-829b-c925-e1ba-d04d3171c09a'
recipient_name = TEST_RECIPIENT_LOOKUPS[recipient_hash]['legal_business_name']
recipient_uei = TEST_RECIPIENT_LOOKUPS[recipient_hash]['uei']
business_categories = ['le', 'business', 'cat... |
def extract_filesystem_bundle(docker_driver, container_id=None, image_name=None):
temporary_dir = tempfile.mkdtemp()
if (container_id is not None):
image = docker_driver.get_docker_client().export(container=container_id)
name = container_id
else:
image = docker_driver.get_docker_clie... |
class OptionSeriesPyramidSonificationDefaultspeechoptionsActivewhen(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: f... |
class StartTransform(Runner):
async def __call__(self, es, params):
transform_id = mandatory(params, 'transform-id', self)
timeout = params.get('timeout')
(await es.transform.start_transform(transform_id=transform_id, timeout=timeout))
def __repr__(self, *args, **kwargs):
return ... |
class EfuseDefineFields(EfuseFieldsBase):
def __init__(self) -> None:
self.EFUSES = []
self.KEYBLOCKS = []
self.BLOCK2_CALIBRATION_EFUSES = []
dir_name = os.path.dirname(os.path.abspath(__file__))
(dir_name, file_name) = os.path.split(dir_name)
file_name = (file_name ... |
class Dump():
def __init__(self):
self.variables = []
def add(self, variable):
self.variables.append(variable)
def add_from_layout(self, layout, variable):
offset = 0
for (name, sample_width) in layout:
values = variable[offset:(offset + sample_width)]
... |
def get_total_memory_usage(keep_raw=False):
if (importlib.util.find_spec('psutil') is None):
return '??'
else:
import psutil
current_process = psutil.Process(os.getpid())
mem = current_process.memory_info().rss
for child in current_process.children(recursive=True):
try:
... |
def test_bf():
job_id = '63ece9904eb8478896baf3300a2c9513'
hash_file = 'tests/deadbeef.hashes'
outfile = '{}{}.cracked'.format(log_dir, job_id)
pot_path = '{}crackq.pot'.format(log_dir)
hc_args = {'hash_mode': 1000, 'hash_file': hash_file, 'name': 'tests', 'brain': False, 'pot_path': pot_path, 'sess... |
def fortios_log_tacacsplusaccounting3(data, fos):
fos.do_member_operation('log.tacacs+accounting3', 'setting')
if data['log_tacacsplusaccounting3_setting']:
resp = log_tacacsplusaccounting3_setting(data, fos)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'log_tacacsplusaccountin... |
class PlayerRevive(GenericAction):
def __init__(self, source, target, hp):
self.source = source
self.target = target
self.hp = hp
def apply_action(self):
tgt = self.target
assert tgt.dead
tgt.dead = False
tgt.maxlife = tgt.__class__.maxlife
tgt.ski... |
def data_fixture(db):
baker.make('accounts.TreasuryAppropriationAccount', pk=1, allocation_transfer_agency_id='123', agency_id='123', main_account_code='0111', fr_entity_code='2345')
baker.make('accounts.TreasuryAppropriationAccount', pk=2, allocation_transfer_agency_id=None, agency_id='234', main_account_code=... |
def _install_freetz():
logging.info('Installing FREETZ')
current_user = getuser()
freetz_build_config = (Path(__file__).parent / 'freetz.config')
with TemporaryDirectory(prefix='fact_freetz') as build_directory:
with OperateInDirectory(build_directory):
os.umask(18)
insta... |
def test_point_gauge_output_2():
filename = 'test_gauge_output_2.csv'
silent_rm(filename)
p = PointGauges(gauges=((('u0',), ((0, 0, 0), (0.5, 0.5, 0.5), (1, 1, 1))),), fileName=filename)
time_list = [0.0, 1.0, 2.0]
run_gauge(p, time_list)
correct_gauge_names = ['u0 [ 0 0 0... |
def _is_status_not_found(error):
if (isinstance(error, errors.HttpError) and (error.resp.status == 404)):
if error.resp.get('content-type', '').startswith('application/json'):
error_details = json.loads(error.content.decode('utf-8'))
if (error_details.get('error', {}).get('status', '... |
def expected_interactions_non_zero(pSubmatrix):
expected_interactions = np.zeros(pSubmatrix.shape[0])
(row, col) = pSubmatrix.nonzero()
distance = np.absolute((row - col))
occurences = np.zeros(pSubmatrix.shape[0])
for (i, distance_) in enumerate(distance):
expected_interactions[distance_] +... |
class TestCoprDetail(CoprsTestCase):
def test_copr_detail_not_found(self):
r = self.tc.get('/coprs/foo/bar/')
assert (r.status_code == 404)
def test_copr_detail_normal(self, f_users, f_coprs, f_db):
r = self.tc.get('/coprs/{0}/{1}/'.format(self.u1.name, self.c1.name))
assert (r.s... |
class _ThreadedBridgeWorker(threading.Thread):
def __init__(self, mb, options):
threading.Thread.__init__(self)
self.mb = mb
self.options = options
def run(self):
with self.mb as mb:
launched = False
while (not launched):
try:
... |
def highest_justified_epoch(min_total_deposits: wei_value) -> uint256:
epoch: uint256
for i in range():
epoch = (self.current_epoch - convert(i, 'uint256'))
is_justified: bool = self.checkpoints[epoch].is_justified
enough_cur_dyn_deposits: bool = (self.checkpoints[epoch].cur_dyn_deposits... |
class Analyzer():
MAX_DELAY_SECS = 0.1
TIMEOUT_SECS = 1.0
CACHED_METHODS = ['X', 'Y', 'calcH', 'H', 'H2', 'h', 'h_inv', 'spectrum', 'frequency', 'calibration', 'target']
chirp: np.ndarray
x: np.ndarray
y: np.ndarray
sumH: np.ndarray
numMeasurements: int
rate: int
fmin: float
... |
class OptionPlotoptionsArcdiagramSonificationContexttracksMappingTremoloSpeed(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: ... |
.parametrize('opt_cls, opt_kwargs_, ref_cycle', [(RFOptimizer, {}, 18), (RFOptimizer, {'adapt_step_func': True}, 18), (NCOptimizer, {}, 13), pytest.param(LBFGS, {'double_damp': True, 'gamma_mult': True}, 19), pytest.param(LBFGS, {'double_damp': True, 'gamma_mult': False}, 19), pytest.param(LBFGS, {'double_damp': False}... |
def create(identifier: str) -> TAuth:
namespace = 'puresnmp_plugins.auth'
loader = Loader(namespace, is_valid_auth_mod)
result = loader.create(identifier)
if (not result):
raise UnknownAuthModel(namespace, identifier, sorted(loader.discovered_plugins.keys()))
return result |
class Delaunay3D(FilterBase):
__version__ = 0
filter = Instance(tvtk.Delaunay3D, args=(), allow_none=False, record=True)
input_info = PipelineInfo(datasets=['structured_grid', 'poly_data', 'unstructured_grid'], attribute_types=['any'], attributes=['any'])
output_info = PipelineInfo(datasets=['unstructur... |
(PRIVACY_REQUEST_RESUME_FROM_REQUIRES_INPUT, status_code=HTTP_200_OK, response_model=PrivacyRequestResponse, dependencies=[Security(verify_oauth_client, scopes=[PRIVACY_REQUEST_CALLBACK_RESUME])])
def resume_privacy_request_from_requires_input(privacy_request_id: str, *, db: Session=Depends(deps.get_db)) -> PrivacyRequ... |
class DatabaseCache(Cache):
def __init__(self, path, event_ttl=None):
self._database_path = path
self._connection = None
self._event_ttl = event_ttl
def _connect(self):
try:
self._open()
with self._connection as connection:
(yield connectio... |
def _parse_model_max_length(model, tokenizer) -> Optional[int]:
if (not (tokenizer or model)):
return None
try:
if (tokenizer and hasattr(tokenizer, 'model_max_length')):
return tokenizer.model_max_length
if (model and hasattr(model, 'config')):
model_config = mod... |
class BaseBot(object):
func_map_topic = {'on_subscription': 'subscription'}
def on_init(self):
pass
def after_init(self):
pass
def on_event(self, event_item):
self.logger.info('got event:{}'.format(event_item))
def on_timer(self, event_item):
self.logger.info('got eve... |
def generate_robustness_report(suite_summary: TestSuiteSummary, model_name: str, save_dir: str, logger: Optional[logging.Logger]=None):
cur_dir = Path(__file__).resolve().parent
template_dir = (cur_dir / 'templates/')
environment = Environment(loader=FileSystemLoader(template_dir))
template = environmen... |
class OptionPlotoptionsTreemapSonificationContexttracksMappingLowpassFrequency(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:... |
class DefaultGptsMessageMemory(GptsMessageMemory):
def __init__(self):
self.df = pd.DataFrame(columns=[field.name for field in fields(GptsMessage)])
def append(self, message: GptsMessage):
self.df.loc[len(self.df)] = message.to_dict()
def get_by_agent(self, conv_id: str, agent: str) -> Optio... |
def splitH5single(basename1, basename2, proc, start, finaltime, stride):
filename = ((basename1 + str(proc)) + '.h5')
print(' Open:', filename)
f1 = tables.open_file(filename)
filename = ((basename2 + str(proc)) + '.h5')
print(' Open:', filename)
f2 = tables.open_file(filename)
print(' Ste... |
def upgrade():
op.drop_index('ix_ctl_data_qualifiers_fides_key', table_name='ctl_data_qualifiers')
op.drop_index('ix_ctl_data_qualifiers_id', table_name='ctl_data_qualifiers')
op.drop_table('ctl_data_qualifiers')
op.drop_column('ctl_datasets', 'data_qualifier')
op.drop_index('ix_ctl_systems_name', t... |
def test_checkpoint_deposits(tester, casper, concise_casper, funded_accounts, validation_keys, deposit_amount, deposit_validator, new_epoch, send_vote, mk_suggested_vote):
current_epoch = concise_casper.current_epoch()
assert (concise_casper.checkpoints__cur_dyn_deposits(current_epoch) == 0)
assert (concise... |
def _wrap_signature_and_type_validation(value: Union[('_DefaultMagic', Callable, '_CallableMock')], template: Any, attr_name: str, type_validation: bool) -> Union[(Callable, '_CallableMock')]:
if _is_a_mock(template):
template = _extract_mock_template(template)
if (not template):
return ... |
def test_callback_no_command(testbot):
extra_plugin_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'commandnotfound_plugin')
cmd = '!this_is_not_a_real_command_at_all'
expected_str = f'Command fell through: {cmd}'
testbot.exec_command('!plugin deactivate CommandNotFoundFilter')
test... |
def _to_wei(value: WeiInputTypes) -> int:
original = value
if isinstance(value, bytes):
value = HexBytes(value).hex()
if ((value is None) or (value == '0x')):
return 0
if (isinstance(value, float) and ('e+' in str(value))):
(num_str, dec) = str(value).split('e+')
num = (n... |
def run_test(layers, quadrilateral):
m = UnitSquareMesh(1, 1, quadrilateral=quadrilateral)
mesh = ExtrudedMesh(m, layers, layer_height=(1.0 / layers))
V = FunctionSpace(mesh, 'CG', 1)
bcs = [DirichletBC(V, 0, 'bottom'), DirichletBC(V, 42, 'top')]
v = TestFunction(V)
u = TrialFunction(V)
a = ... |
class INI(Database):
_maps = None
_subnets = None
_lock = None
def __init__(self):
self._maps = {}
self._subnets = {}
self._lock = threading.Lock()
self.reinitialise()
def _parse_extra_option(self, reader, section, option):
method = reader.get
none_on_... |
class DictItemObserver():
__slots__ = ('notify', 'optional')
def __init__(self, *, notify, optional):
self.notify = notify
self.optional = optional
def __hash__(self):
return hash((type(self).__name__, self.notify, self.optional))
def __eq__(self, other):
return ((type(se... |
def generate_params():
bscan_already_on = False
icap_already_on = False
tile_params = []
for (loci, (site, site_type)) in enumerate(sorted(gen_sites())):
p = {}
if ((site_type in 'ICAP') and (not icap_already_on)):
p['ICAP_WIDTH'] = verilog.quote(random.choice(['X32', 'X8', '... |
def legal_doc_data(*args, **kwargs):
return {'hits': {'hits': [{'_source': {'type': 'document type', 'no': '100', 'summary': 'summery 100', 'documents': [{'document_id': 111, 'category': 'Final Opinion', 'description': 'Closeout Letter', 'url': 'files/legal/aos/100/111.pdf'}, {'document_id': 222, 'category': 'Draft... |
def test_build_from():
key_hash = b'key_hash'
key_data = b'key_data'
value_data = b'value_data'
item = StorageItem.build_from(key_hash, key_data, value_data)
assert (item.key_hash == key_hash)
assert (item.key_data == key_data)
assert (item.value_data == value_data)
assert (item.length =... |
def test_align_missing_data_designators(o_dir, e_dir, request):
program = 'bin/align/phyluce_align_add_missing_data_designators'
output = os.path.join(o_dir, 'mafft-missing-data-designators')
cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft'), '--output', outp... |
.parametrize('elasticapm_client', [{'client_class': AzureFunctionsTestClient}], indirect=['elasticapm_client'])
def test_service_info(elasticapm_client):
with mock.patch.dict(os.environ, {'FUNCTIONS_EXTENSION_VERSION': '1.1', 'FUNCTIONS_WORKER_RUNTIME': 'MontyPython', 'FUNCTIONS_WORKER_RUNTIME_VERSION': '2.2', 'WEB... |
class NoSuchObject(Type[None]):
TYPECLASS = TypeClass.CONTEXT
NATURE = [TypeNature.PRIMITIVE]
TAG = 0
def __init__(self, value: Union[(TWrappedPyType, _SENTINEL_UNINITIALISED)]=UNINITIALISED) -> None:
if (value is UNINITIALISED):
super().__init__(value=None)
else:
... |
class Block(Serializable):
fields = [('header', BlockHeader), ('transaction_list', CountableList(Transaction)), ('uncles', CountableList(BlockHeader))]
def __init__(self, header, transaction_list=None, uncles=None, **kwargs):
super().__init__(header, (transaction_list or []), (uncles or []), **kwargs) |
class HTTPIter(HTTPResponse):
def __init__(self, iter: Iterable[bytes], headers: Dict[(str, str)]={}, cookies: Dict[(str, Any)]={}):
super().__init__(200, headers=headers, cookies=cookies)
self.iter = iter
async def _send_body(self, send):
for chunk in self.iter:
(await send(... |
def extractAaokossWordpressCom(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... |
class LogFormatter(object):
def format(lid, msg, efile=None, eline=None):
rval = ('%3d:' % lid)
if (efile is not None):
rval += ('%s:' % efile)
if (eline is not None):
rval += ('%s:' % eline)
rval += ('%s' % msg)
return rval
def rmte(rmte):
... |
def test_serialization_set_command():
def t1() -> str:
return 'Hello'
def new_command_fn(settings: SerializationSettings) -> typing.List[str]:
return ['echo', 'hello', 'world']
t1.set_command_fn(new_command_fn)
custom_command = t1.get_command(serialization_settings)
assert (['echo', ... |
class _KeywordSearch(_Filter):
underscore_name = 'keyword_search'
def generate_elasticsearch_query(cls, filter_values: List[str], query_type: _QueryType, **options) -> ES_Q:
keyword_queries = []
fields = ['recipient_name', 'parent_recipient_name', 'naics_code', 'naics_description', 'product_or_s... |
class i2c_msg():
def write(address, buf):
if (sys.version_info.major >= 3):
if (type(buf) is str):
buf = bytes(map(ord, buf))
else:
buf = bytes(buf)
elif (type(buf) is not str):
buf = ''.join([chr(x) for x in buf])
return (a... |
def extractCourageMyFriendOrg(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... |
def upgrade():
session = sa.orm.sessionmaker(bind=op.get_bind())()
tito_package_rows = session.execute('SELECT * FROM package WHERE source_type=:param', {'param': 3})
for package in tito_package_rows:
source_dict = (json.loads(package['source_json']) if package['source_json'] else {})
new_so... |
class JsHtmlIcon(JsHtml):
def val(self):
return JsObjects.JsObjects.get(('{%s: {value: %s, timestamp: Date.now(), offset: new Date().getTimezoneOffset()}}' % (self.htmlCode, self.component.dom.getAttribute('class'))))
def content(self):
return self.component.dom.getAttribute('class')
def spi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.