code stringlengths 281 23.7M |
|---|
def test_df(categorical: bool=False, datetime: bool=False) -> Tuple[(pd.DataFrame, pd.Series)]:
(X, y) = make_classification(n_samples=1000, n_features=12, n_redundant=4, n_clusters_per_class=1, weights=[0.5], class_sep=2, random_state=1)
colnames = [f'var_{i}' for i in range(12)]
X = pd.DataFrame(X, column... |
def test_flatten_does_not_persist_0_checkpoints(journal_db, memory_db):
journal_db.set(b'before-record', b'test-a')
journal_db.flatten()
assert (b'before-record' not in memory_db)
assert (b'before-record' in journal_db)
journal_db.persist()
assert (b'before-record' in memory_db) |
class TestDataFrameHist(TestData):
def test_flights_hist(self):
pd_flights = self.pd_flights()
ed_flights = self.ed_flights()
num_bins = 10
pd_distancekilometers = np.histogram(pd_flights['DistanceKilometers'], num_bins)
pd_flightdelaymin = np.histogram(pd_flights['FlightDela... |
class MinhaLista(MutableSequence):
def __init__(self, *vals):
self.vals = vals
def __getitem__(self, pos):
return self.vals[pos]
def __len__(self):
return len(self.vals)
def __delitem__(self, item):
del self.vals[item]
def __setitem__(self, pos, valor):
self.v... |
class Demo(lg.Graph):
AVERAGED_NOISE: AveragedNoise
PLOT: Plot
def setup(self) -> None:
self.AVERAGED_NOISE.configure(AveragedNoiseConfig(sample_rate=SAMPLE_RATE, num_features=NUM_FEATURES, window=WINDOW))
self.PLOT.configure(PlotConfig(refresh_rate=REFRESH_RATE, num_bars=NUM_FEATURES))
... |
def annotate_project(project):
(project)
def wrapper(*args, **kwargs):
ad_block_tag = kwargs.pop('ad_block_tag', None)
annotate = annotate_tape(kwargs)
if annotate:
bcs = kwargs.get('bcs', [])
sb_kwargs = ProjectBlock.pop_kwargs(kwargs)
if isinstance(a... |
def test_create_from_cookiecutter(temp_with_override: Path, cli):
book = (temp_with_override / 'new_book')
result = cli.invoke(commands.create, [book.as_posix(), '--cookiecutter'])
assert (result.exit_code == 0)
assert book.joinpath('my_book', 'my_book', '_config.yml').exists()
assert (len(list(book... |
class TestScriptedFields(TestData):
def test_add_new_scripted_field(self):
ed_field_mappings = FieldMappings(client=ES_TEST_CLIENT, index_pattern=FLIGHTS_INDEX_NAME)
ed_field_mappings.add_scripted_field('scripted_field_None', None, np.dtype('int64'))
expected = self.pd_flights().columns.to_l... |
def is_valid_directory(path_to_directory: str, must_be_writable: bool=False) -> OperationOutcome:
if (path_to_directory and os.path.isdir(path_to_directory) and os.access(path_to_directory, os.R_OK)):
if ((not must_be_writable) or os.access(path_to_directory, os.W_OK)):
return OperationOutcome(T... |
def test_single_window_when_using_freq(df_time):
expected_results = {'ambient_temp': [31.31, 31.51, 32.15, 32.39, 32.62, 32.5, 32.52, 32.68, 33.76], 'module_temp': [49.18, 49.84, 52.35, 50.63, 49.61, 47.01, 46.67, 47.52, 49.8], 'irradiation': [0.51, 0.79, 0.65, 0.76, 0.42, 0.49, 0.57, 0.56, 0.74], 'color': ['blue',... |
def filter_extender_lte_carrier_list_data(json):
option_list = ['sn']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attribute]
return dictionary |
def test_standard_calls_passthrough(accounts, tester):
addr = accounts[1]
value = ['blahblah', addr, ['yesyesyes', '0x1234']]
tester.setTuple(value)
with brownie.multicall:
assert (tester.getTuple.call(addr) == value)
assert (not isinstance(tester.getTuple.call(addr), Proxy)) |
_toolkit([ToolkitName.qt, ToolkitName.wx])
class TestExample(BaseTestMixin, unittest.TestCase):
def setUp(self):
BaseTestMixin.setUp(self)
def tearDown(self):
BaseTestMixin.tearDown(self)
def test_run(self):
(accepted_files, skipped_files) = SEARCHER.get_python_files()
for fi... |
def update_heartbeat(submission_id: int, processor_id: str) -> int:
sql = f'''
update {DABSLoaderQueue._meta.db_table}
set heartbeat = %s::timestamptz
where submission_id = %s and processor_id = %s and state = %s
'''
with psycopg2.connect(dsn=get_database_dsn_string()) as conn... |
def recurse_check_structure(sample: Any, to_check: Any) -> None:
sample_type = type(sample)
to_check_type = type(to_check)
if ((sample is not None) and (sample_type != to_check_type)):
raise ValidationException(f'{sample} [{sample_type}] is not the same type as {to_check} [{to_check_type}].')
if... |
(reuse_venv=True)
def format(session):
session.install('black', 'isort', 'flynt')
session.run('python', 'utils/license-headers.py', 'fix', *SOURCE_FILES)
session.run('flynt', *SOURCE_FILES)
session.run('black', '--target-version=py38', *SOURCE_FILES)
session.run('isort', '--profile=black', *SOURCE_F... |
def logger_to_ofp(port_stats):
return {'packets_out': port_stats.tx_packets, 'packets_in': port_stats.rx_packets, 'bytes_out': port_stats.tx_bytes, 'bytes_in': port_stats.rx_bytes, 'dropped_out': port_stats.tx_dropped, 'dropped_in': port_stats.rx_dropped, 'errors_out': port_stats.tx_errors, 'errors_in': port_stats.... |
def adjusted_path(tools_to_activate, system=False, user=False):
path_add = get_required_path(tools_to_activate)
if (WINDOWS and (not MSYS)):
existing_path = win_get_environment_variable('PATH', system=system, user=user, fallback=True).split(ENVPATH_SEPARATOR)
else:
existing_path = os.environ... |
class VerificationMethod():
def get_html(self):
raise NotImplementedError()
def get_javascript(self):
raise NotImplementedError()
def verification_in_request(self, request):
raise NotImplementedError()
def verify_request(self, request):
raise NotImplementedError() |
class WindowsAppLink(AbstractObject):
def __init__(self, api=None):
super(WindowsAppLink, self).__init__()
self._isWindowsAppLink = True
self._api = api
class Field(AbstractObject.Field):
app_id = 'app_id'
app_name = 'app_name'
package_family_name = 'package_famil... |
def test_supports_foundry_schema(spark_session, provide_config):
pc = DiskPersistenceBackedSparkCache(**provide_config)
df = spark_session.createDataFrame(data=[[1, 2]], schema='a: int, b: int')
foundry_schema = {'fieldSchemaList': [{'type': 'INTEGER', 'name': 'a', 'nullable': None, 'userDefinedTypeClass': ... |
class AppHandler(FlexxHandler):
def get(self, full_path):
logger.debug(('Incoming request at %r' % full_path))
ok_app_names = ('__main__', '__default__', '__index__')
parts = [p for p in full_path.split('/') if p]
app_name = None
path = '/'.join(parts)
if parts:
... |
class TestLChProperties(util.ColorAsserts, unittest.TestCase):
def test_lightness(self):
c = Color('color(--lch 90% 50 120 / 1)')
self.assertEqual(c['lightness'], 90)
c['lightness'] = 80
self.assertEqual(c['lightness'], 80)
def test_chroma(self):
c = Color('color(--lch 90... |
def task_setup(function: typing.Callable, *, integration_requests: typing.Optional[List]=None) -> typing.Callable:
integration_requests = (integration_requests or [])
(function)
def wrapper(*args, **kwargs):
print('preprocessing')
output = function(*args, **kwargs)
print('postprocess... |
def delete_old_files(directory: str, age_limit_seconds: int):
files_to_not_delete = _get_files_to_not_delete()
age_limit = (time.time() - age_limit_seconds)
for (dirpath, dirnames, filenames) in os.walk(directory):
if (dirpath.split('/')[(- 1)] not in files_to_not_delete):
for filename i... |
class TopicNotLocked(Requirement):
def __init__(self, topic=None, topic_id=None, post_id=None, post=None):
self._topic = topic
self._topic_id = topic_id
self._post = post
self._post_id = post_id
def fulfill(self, user):
return (not any(self._determine_locked()))
def _... |
class MystWarningsDirective(SphinxDirective):
has_content = False
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
def run(self):
from sphinx.pycode import ModuleAnalyzer
analyzer = ModuleAnalyzer.for_module(MystWarnings.__module__)
qname = Myst... |
def _smsapi_response_adapter(response):
if ((response.status_code == requests.codes.ok) and response.text.startswith('ERROR')):
new_status_code = 406
logger.warning('SMSAPI response got status code %s and contains "%s". Updating SMSAPI response status code to %s!', response.status_code, response.tex... |
(stability='beta')
class StorageInterface(Generic[(T, TDataRepresentation)], ABC):
def __init__(self, serializer: Optional[Serializer]=None, adapter: Optional[StorageItemAdapter[(T, TDataRepresentation)]]=None):
self._serializer = (serializer or JsonSerializer())
self._storage_item_adapter = (adapte... |
class Factory(object):
known_input_types = {'git': Git, 'filesystem': FileSystem}
def create(input_method, input_config):
tracer.info('Called: name [%s]', input_method)
if input_method.startswith('ignore:'):
tracer.info('Ignoring factory entry.')
return None
if (i... |
class TestOFPActionSetTpSrc(unittest.TestCase):
type_ = {'buf': b'\x00\t', 'val': ofproto.OFPAT_SET_TP_SRC}
len_ = {'buf': b'\x00\x08', 'val': ofproto.OFP_ACTION_TP_PORT_SIZE}
tp = {'buf': b'\x07\xf1', 'val': 2033}
zfill = (b'\x00' * 2)
buf = (((type_['buf'] + len_['buf']) + tp['buf']) + zfill)
... |
def extractXianXiaWorld(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if ('www.xianxiaworld.net/A-Thought-Through-Eternity/' in item['linkUrl']):
return buildReleaseMessa... |
def write_version_to_file(filename: str, version: str) -> None:
with open(filename, 'r+') as file:
file_content = file.read()
updated_content = re.sub('version=\\d+\\.\\d+\\.\\d+', f'version={version}', file_content)
updated_content = re.sub('release=\\d+\\.\\d+\\.\\d+', f'release={version}'... |
class SelfAttentionConvBlock(PerceptionBlock):
def __init__(self, in_keys: Union[(str, List[str])], out_keys: Union[(str, List[str])], in_shapes: Union[(Sequence[int], List[Sequence[int]])], embed_dim: int, dropout: Optional[float], add_input_to_output: bool, bias: bool):
super().__init__(in_keys=in_keys, o... |
(scope='function')
def rollbar_connection_config(db: session, rollbar_config, rollbar_secrets) -> Generator:
fides_key = rollbar_config['fides_key']
connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': fides_key, 'connection_type': ConnectionType.saas, 'access': AccessLevel.write, ... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':... |
.django_db
def test_federal_accounts_endpoint_correct_data(client, fixture_data):
resp = client.post('/api/v2/federal_accounts/', content_type='application/json', data=json.dumps({'sort': {'field': 'managing_agency', 'direction': 'asc'}, 'filters': {'fy': '2017'}}))
response_data = resp.json()
assert (respo... |
class MsgServicer(object):
def CreateClient(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def UpdateClient(self, request, context):
context.set_code(grpc... |
def _calculate_correlations(df: pd.DataFrame, num_for_corr, cat_for_corr, kind):
if (kind == 'pearson'):
return df[num_for_corr].corr('pearson')
elif (kind == 'spearman'):
return df[num_for_corr].corr('spearman')
elif (kind == 'kendall'):
return df[num_for_corr].corr('kendall')
e... |
def init(backend='ipy', width=None, height=None, local=True):
from mayavi.core.base import Base
from tvtk.pyface.tvtk_scene import TVTKScene
global _backend, _registry
backends = _registry.keys()
error_msg = ('Backend must be one of %r, got %s' % (backends, backend))
assert (backend in backends)... |
def should_clear_cache(force=False):
if force:
return True
elif (not ParserElement._packratEnabled):
return False
elif (SUPPORTS_INCREMENTAL and ParserElement._incrementalEnabled):
if (not in_incremental_mode()):
return repeatedly_clear_incremental_cache
if ((incr... |
class ClkReg2():
def __init__(self, value=0):
self.unpack(value)
def unpack(self, value):
self.delay_time = ((value >> 0) & ((2 ** 6) - 1))
self.no_count = ((value >> 6) & ((2 ** 1) - 1))
self.edge = ((value >> 7) & ((2 ** 1) - 1))
self.mx = ((value >> 8) & ((2 ** 2) - 1)... |
class TestRedirectStream():
redirect_stream = None
orig_stream = None
def test_no_redirect_in_init(self):
orig_stdout = getattr(sys, self.orig_stream)
self.redirect_stream(None)
self.assertIs(getattr(sys, self.orig_stream), orig_stdout)
def test_redirect_to_string_io(self):
... |
class LogiHead():
dissolved_gas: (bool | None) = None
vaporized_oil: (bool | None) = None
directional: (bool | None) = None
radial: (bool | None) = None
reversible: (bool | None) = None
hysterisis: (bool | None) = None
dual_porosity: (bool | None) = None
end_point_scaling: (bool | None) ... |
('/api/user/edit', methods=['POST'])
_secure
def user_edit():
user_id = int(request.form['user_id'])
is_admin = (request.form['is_admin'] == 'true')
if ((flask.session.get((config.link + '_user_id')) == user_id) and (not is_admin)):
return (jsonify({'message': 'Cannot remove the admin permissions fr... |
def get_pips(tile, pips):
proto_pips = {}
for pip in pips:
name = check_and_strip_prefix(pip['pip'], (tile + '/'))
proto_pips[name] = {'src_wire': (check_and_strip_prefix(pip['src_wire'], (tile + '/')) if (pip['src_wire'] is not None) else None), 'dst_wire': (check_and_strip_prefix(pip['dst_wire... |
def prepareOperatingSystem(config, userPath):
if config['hook32']:
logging.info('placing hook for 32bit processes')
place_hook_in_registry((userPath + config['hook32']), 'SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows')
if config['hook64']:
logging.info('placing ho... |
def strip_non_ecs_options(subset: Dict[(str, Any)]) -> None:
for key in subset:
subset[key] = {x: subset[key][x] for x in subset[key] if (x in ecs_options)}
if (('fields' in subset[key]) and isinstance(subset[key]['fields'], dict)):
strip_non_ecs_options(subset[key]['fields']) |
def execute(wf, mode='light', storage={'s3': {'config': {'s3_bucket': 'dagster-test'}}}):
(task, dep, env) = parse_json(wf)
try:
pipeline_def = PipelineDefinition(name='basic', solid_defs=task, dependencies=dep, mode_defs=[ModeDefinition('light', system_storage_defs=s3_plus_default_storage_defs, resourc... |
def extractPoachedeggsnovelsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('zhanxian', 'Zhanxian', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', '... |
def test_smt256_empty_hashes():
DEPTH = 256
EMPTY_LEAF_NODE_HASH = BLANK_HASH
EMPTY_NODE_HASHES = collections.deque([EMPTY_LEAF_NODE_HASH])
for _ in range((DEPTH - 1)):
EMPTY_NODE_HASHES.appendleft(keccak((EMPTY_NODE_HASHES[0] + EMPTY_NODE_HASHES[0])))
EMPTY_ROOT_HASH = keccak((EMPTY_NODE_HA... |
class MoveJoystick(MoveTank):
def on(self, x, y, radius=100.0):
if ((not x) and (not y)):
self.off()
return
vector_length = math.sqrt(((x * x) + (y * y)))
angle = math.degrees(math.atan2(y, x))
if (angle < 0):
angle += 360
if (vector_length... |
def message_scalar_test(out, version, cls):
(members, member_types) = scalar_member_types_get(cls, version)
length = of_g.base_length[(cls, version)]
v_name = loxi_utils.version_to_name(version)
out.write(('\nstatic int\ntest_%(cls)s_%(v_name)s_scalar(void)\n{\n %(cls)s_t *obj;\n\n obj = %(cls)s_n... |
class Plugin(LedgerPlugin, QtPluginBase):
icon_paired = 'icons8-usb-connected-80.png'
icon_unpaired = 'icons8-usb-disconnected-80.png'
def create_handler(self, window: HandlerWindow) -> QtHandlerBase:
return Ledger_Handler(window)
def show_settings_dialog(self, window: ElectrumWindow, keystore: ... |
.update(GROUP, VERSION, PLURAL)
def updated(spec, status, logger, patch, **kwargs):
description = spec.get('description')
openai.api_key = os.environ['OPENAI_API_KEY']
if (('error' in status) and ('expectedObjects' in spec) and (status['error'] != '')):
expected_objects_yaml = ask_for_help(openai, s... |
class OozieActionSchema(OozieNamedObjectSchema):
ok = ma.fields.Nested(OozieFlowControlSchema, required=True)
error = ma.fields.Nested(OozieFlowControlSchema, required=True)
def _get_action_builder(self, data):
keyed_action_builders = {builder.key: builder for builder in self.context['oozie_plugin']... |
def stop_process(pid, timeout_sec: int=60):
try:
os.kill(pid, signal.SIGTERM)
start_time = time.monotonic()
while check_pid_exist(pid):
if ((time.monotonic() - start_time) > timeout_sec):
raise RuntimeError('pid: {} does not exit after {} seconds.'.format(pid, tim... |
def add_default_axes(plot, orientation='normal', vtitle='', htitle=''):
if (orientation in ('normal', 'h')):
v_mapper = plot.value_mapper
h_mapper = plot.index_mapper
else:
v_mapper = plot.index_mapper
h_mapper = plot.value_mapper
left = PlotAxis(orientation='left', title=vti... |
.parametrize('text,exclusive_classes,response,expected', [('Golden path for exclusive', True, 'Recipe', ['Recipe']), ('Golden path for non-exclusive', False, 'Recipe,Feedback', ['Recipe', 'Feedback']), ('Non-exclusive but responded with a single label', False, 'Recipe', ['Recipe']), ('Exclusive but responded with multi... |
.parametrize(['region_indices', 'items', 'expected_num_shorts', 'expected_regions', 'expected_items'], [([0, 1, 2], [[0, 1, 2], [3, 4, 5], [6, 7, 8]], 0, [0, 1, 2], [[0, 1, 2], [3, 4, 5], [6, 7, 8]]), ([0, 1, 2], [[0, 128, 2], [3, 4, 5], [6, 7, 8]], 1, [1, 0, 2], [[128, 0, 2], [4, 3, 5], [7, 6, 8]]), ([0, 1, 2], [[0, 1... |
def gen_function(func_attrs, exec_cond_template, dim_info_dict, layout, unary_op1, binary_op1, binary_op2, unary_op2):
backend_spec = CUDASpec()
elem_input_type = backend_spec.dtype_to_lib_type(func_attrs['inputs'][0]._attrs['dtype'])
elem_output_type = backend_spec.dtype_to_lib_type(func_attrs['outputs'][0... |
def get_permutation_map(V, W):
perm = numpy.empty((V.dof_count,), dtype=PETSc.IntType)
perm.fill((- 1))
vdat = V.make_dat(val=perm)
offset = 0
wdats = []
for Wsub in W:
val = numpy.arange(offset, (offset + Wsub.dof_count), dtype=PETSc.IntType)
wdats.append(Wsub.make_dat(val=val))... |
def extractAzuureskyBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
titlemap = [('World defying dan god chapter ', 'World defying dan god', 'translated'), ('Tensei Shoujo no Ri... |
class RequestContextManager():
def __init__(self, request_context_holder):
self.ctx_holder = request_context_holder
self.ctx = None
self.token = None
def __enter__(self):
(self.ctx, self.token) = self.ctx_holder.init_request_context()
return self
def request_start(sel... |
class TableArith(TableOperation):
op: str
exprs: List[Sql]
def _compile(self, qb):
tables = [t.compile_wrap(qb) for t in self.exprs]
selects = [([f'SELECT * FROM '] + t.code) for t in tables]
code = join_sep(selects, f' {self.op} ')
if (qb.target == sqlite):
code ... |
_toolkit([ToolkitName.qt, ToolkitName.wx])
class TestSimpleEnumEditor(BaseTestMixin, unittest.TestCase):
def setUp(self):
BaseTestMixin.setUp(self)
def tearDown(self):
BaseTestMixin.tearDown(self)
def check_enum_text_update(self, view):
enum_edit = EnumModel()
tester = UITest... |
class Heightmap():
def __init__(self, params, debug=False):
self.params = params
self.size = params.get('size')
self.grid = np.zeros((self.size, self.size))
self.grid[0][0] = random.randint(0, 255)
self.grid[(self.size - 1)][0] = random.randint(0, 255)
self.grid[0][(s... |
class ManagedPartnerBusiness(AbstractObject):
def __init__(self, api=None):
super(ManagedPartnerBusiness, self).__init__()
self._isManagedPartnerBusiness = True
self._api = api
class Field(AbstractObject.Field):
ad_account = 'ad_account'
catalog_segment = 'catalog_segment... |
class AlignmentDataset(Dataset):
def __init__(self, pairs, tokenizer):
self.tokenizer = tokenizer
self.pairs = pairs
def __iter__(self):
worker_info = torch.utils.data.get_worker_info()
start = 0
end = len(self.pairs)
if (worker_info is None):
for i in... |
class OptionPlotoptionsTreegraphSonification(Options):
def contextTracks(self) -> 'OptionPlotoptionsTreegraphSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionPlotoptionsTreegraphSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionPlotoptionsTreegraphSon... |
def upgrade():
bind = op.get_bind()
existing_history_names: ResultProxy = bind.execute(text('select name from privacynoticehistory;'))
validate_fides_key_suitability(existing_history_names, 'privacynoticehistory')
existing_notice_names: ResultProxy = bind.execute(text('select name from privacynotice;'))... |
def to_wei(number: Union[(int, float, str, decimal.Decimal)], unit: str) -> int:
if (unit.lower() not in units):
raise ValueError(f"Unknown unit. Must be one of {'/'.join(units.keys())}")
if (is_integer(number) or is_string(number)):
d_number = decimal.Decimal(value=number)
elif isinstance(n... |
.parametrize(('ignore_params', 'expected_result', 'flag_name', 'issue_code'), [({'ignore_obsolete': (), 'ignore_unused': (), 'ignore_missing': ('hello', 'goodbye'), 'ignore_transitive': (), 'ignore_misplaced_dev': ()}, {'DEP001': ('goodbye', 'hello', 'package')}, 'ignore-missing', 'DEP001'), ({'ignore_obsolete': ('hell... |
def _cmd_genemetrics(args):
cnarr = read_cna(args.filename)
segarr = (read_cna(args.segment) if args.segment else None)
is_sample_female = verify_sample_sex(cnarr, args.sample_sex, args.male_reference, args.diploid_parx_genome)
table = do_genemetrics(cnarr, segarr, args.threshold, args.min_probes, args.... |
class Config():
def __init__(self, args):
self.iface = args.iface
if (not self.iface):
self.iface = conf.iface
self.verbose = args.verbose
self.collect_hosts = args.collect_hosts
self.filename = args.filename
self.verbose_extra = args.verbose_extra
... |
def populate_filesystem(fst_bytes):
root_dir = GCFSTEntry(bool(fst_bytes[0]), (struct.unpack_from('>I', fst_bytes, 0)[0] & ), struct.unpack_from('>I', fst_bytes, 4)[0], struct.unpack_from('>I', fst_bytes, 8)[0])
string_table_bytes = fst_bytes[(root_dir.length * 12):len(fst_bytes)]
nodes_read = 1
while (... |
class OptionSeriesHeatmapSonificationContexttracksMappingVolume(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 _handle_rgbgradient_dict(colors):
duration = _default_duration
gradient = []
if ('duration' in colors):
duration = colors['duration']
if ('colors' in colors):
for stop in colors['colors']:
color = stop['color']
if isinstance(color, str):
color ... |
def extractYaminatranslationsBlogspotCom(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, ... |
def parentheses_placeholder(text: str):
length = len(text)
key = 0
placeholder = 0
depth = 0
output = parentheses_placeholder_data()
output.list.append('')
while (length > key):
char = text[key]
key += 1
if (char == '('):
depth += 1
if (depth =... |
.EventDecorator('MakeKronCode')
def make_kron_code(Vc, Vf, t_in, t_out, mat_name, scratch):
operator_decl = []
prolong_code = []
restrict_code = []
(_, celems, cshifts) = get_permutation_to_line_elements(Vc)
(_, felems, fshifts) = get_permutation_to_line_elements(Vf)
shifts = fshifts
in_plac... |
def conv2d(x, input_filters, output_filters, kernel_size, strides, relu=True, mode='REFLECT'):
shape = [kernel_size, kernel_size, input_filters, output_filters]
weight = tf.Variable(tf.truncated_normal(shape, stddev=WEIGHT_INIT_STDDEV), name='weight')
padding = (kernel_size // 2)
x_padded = tf.pad(x, [[... |
class TestAdvancedSearch(TestCase):
fixtures = ['dmd-objs']
def test_advanced_search(self):
bnf_codes = ['0204000C0AAAAAA', '0204000C0BBAAAA', '0204000D0AAAAAA']
factory = DataFactory()
factory.create_prescribing_for_bnf_codes(bnf_codes)
search = ['nm', 'contains', 'acebutolol']
... |
def select_cats_range(save_stats: dict[(str, Any)]) -> list[int]:
ids = user_input_handler.get_range(user_input_handler.colored_input('Enter cat ids (Look up cro battle cats to find ids)(You can enter &all& to get all, a range e.g &1&-&50&, or ids separate by spaces e.g &5 4 7&):'), length=len(save_stats['cats']))
... |
class OptionPlotoptionsFunnel3dOnpoint(Options):
def connectorOptions(self) -> 'OptionPlotoptionsFunnel3dOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionPlotoptionsFunnel3dOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id(self, text:... |
class OptionPlotoptionsColumnpyramidLabel(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):
... |
class RecognitionService(Service):
def __init__(self, api_key: str, domain: str, port: str, options: AllOptionsDict={}):
super().__init__(api_key, options)
self.available_services = []
self.recognize_face_from_images: RecognizeFaceFromImage = RecognizeFaceFromImage(domain=domain, port=port, ... |
def validate(config: Dict[(str, Any)], instance_id: str, logger: logging.Logger, expected_result_path: str, aggregated_result_path: Optional[str]=None) -> None:
pc_service = build_private_computation_service(config['private_computation'], config['mpc'], config['pid'], config.get('post_processing_handlers', {}), con... |
def check_file(filename: str) -> List[LintMessage]:
with open(filename, 'rb') as f:
original = f.read().decode('utf-8')
try:
path = Path(filename)
usort_config = UsortConfig.find(path)
black_config = make_black_config(path)
replacement = ufmt_string(path=path, content=ori... |
def test_get_contract_factory_raises_insufficient_assets_error(w3):
insufficient_owned_manifest = get_ethpm_spec_manifest('owned', 'v3.json')
owned_package = w3.pm.get_package_from_manifest(insufficient_owned_manifest)
with pytest.raises(InsufficientAssetsError):
owned_package.get_contract_factory('... |
.parametrize('typ', [str, int, float])
def test_aliases_grib_paramid_mutiple_false(typ):
_131 = typ(131)
aliases_grib_paramid = normalize('x', type=typ, aliases={'u': typ(131), 'v': typ(132)}, multiple=False)(func_x)
assert (aliases_grib_paramid('u') == _131)
assert (aliases_grib_paramid(131) == _131)
... |
def test_default():
score = scores.MaskPercent(band)
newimg = score.compute(image, geometry=pol, scale=30)
maskpercent_prop = newimg.get(score.name).getInfo()
maskpercent_pix = tools.image.getValue(newimg, p, side='client')[score.name]
assert (maskpercent_prop == 0), 5625
assert (maskpercent_pix... |
def g2p(norm_text):
(sep_text, sep_kata, acc) = text2sep_kata(norm_text)
sep_tokenized = []
for i in sep_text:
if (i not in punctuation):
sep_tokenized.append(tokenizer.tokenize(i))
else:
sep_tokenized.append([i])
sep_phonemes = handle_long([kata2phoneme(i) for i ... |
def test_dev_dependency_getter(tmp_path: Path) -> None:
fake_pyproject_toml = '[project]\n# PEP 621 project metadata\n# See = [\n "qux",\n "bar>=20.9",\n "optional-foo[option]>=0.12.11",\n "conditional-bar>=1.1.0; python_version < 3.11",\n]\n[tool.pdm.dev-dependencies]\ntest = [\n "qux",\n "bar; ... |
def extractHainemakorutranslationsBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('news' in item['tags']):
return None
tagmap = [('10000 STEPS', 'Level Up Just ... |
def test_custom_help(tmpdir: Path) -> None:
(result, _err) = run_python_script(['examples/configure_hydra/custom_help/my_app.py', ('hydra.run.dir=' + str(tmpdir)), 'hydra.job.chdir=True', '--help'])
expected = dedent(' == AwesomeApp ==\n\n This is AwesomeApp!\n You can choose a ... |
def reshape(array, operation):
operation = _normalize(operation)
if ('*' in operation.split('->')[0]):
raise NotImplementedError('Unflatten operation not supported by design. Actual values for dimensions are not available to this function.')
squeeze_operation = operation.split('->')[0].split()
f... |
class Choices(metaclass=ChoicesMeta):
def choices(cls):
for attr_name in dir(cls):
if attr_name.startswith('_'):
continue
if (attr_name in ['keys', 'choices']):
continue
value = cls.__dict__[attr_name]
if (not callable(value)):
... |
class InputCheckbox(Html.Html):
name = 'Checkbox'
def __init__(self, page: primitives.PageModel, flag, label, group_name, width, height, html_code, options, attrs, profile):
if (html_code in page.inputs):
page.inputs[html_code] = (True if (page.inputs[html_code] == 'true') else False)
... |
class ExaSQLImportThread(ExaSQLThread):
def __init__(self, connection, compression, table, import_params):
super().__init__(connection, compression)
self.table = table
self.params = import_params
def run_sql(self):
table_ident = self.connection.format.default_format_ident(self.ta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.