code
stringlengths
281
23.7M
('config_type', ['strict']) def test_option_missing_envs_strict_mode(config, json_config_file_3): with open(json_config_file_3, 'w') as file: file.write(json.dumps({'section': {'undefined': '${UNDEFINED}'}})) with raises(ValueError, match='Missing required environment variable "UNDEFINED"'): con...
def extractPerpetuallyperennialCarBlog(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('please don't eat me', 'Please Dont Eat Me', 'translated'), ('the villainess needs a ...
def merge_file_level(config: MdParserConfig, topmatter: Dict[(str, Any)], warning: Callable[([MystWarnings, str], None)]) -> MdParserConfig: updates: Dict[(str, Any)] = {} myst = topmatter.get('myst', {}) if (not isinstance(myst, dict)): warning(MystWarnings.MD_TOPMATTER, f"'myst' key not a dict: {t...
def extractLazycatnovelsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Mighty Female Official', 'Mighty Female Official', 'translated'), ("Xiaobei's Life as a Pro...
class WorkflowExecutionStatus(betterproto.Enum): WORKFLOW_EXECUTION_STATUS_UNSPECIFIED = 0 WORKFLOW_EXECUTION_STATUS_RUNNING = 1 WORKFLOW_EXECUTION_STATUS_COMPLETED = 2 WORKFLOW_EXECUTION_STATUS_FAILED = 3 WORKFLOW_EXECUTION_STATUS_CANCELED = 4 WORKFLOW_EXECUTION_STATUS_TERMINATED = 5 WORKFL...
class ScrubberEditor(BasicEditorFactory): klass = Property() low = Float() high = Float() increment = Float() alignment = Alignment('center') color = Color(None) hover_color = Color(None) active_color = Color(None) border_color = Color(None) text_color = Color('black') def _g...
def test_transaction_request_response_data(django_elasticapm_client, client): client.cookies = SimpleCookie({'foo': 'bar'}) with override_settings(**middleware_setting(django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware'])): client.get(reverse('elasticapm-no-error')) transaction...
def extractKscansWordpressCom(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 test_insert_aliased_variable_more_dominators_same_block(): (list_instructions, aliased_variables, task) = construct_graph_aliased(2) InsertMissingDefinitions().run(task) assert ([node.instructions for node in task.graph.nodes] == [((([list_instructions[0], Assignment(aliased_variables[0], Variable('x', ...
def test_duplicated_param_names(): with pytest.raises(ValueError, match='Duplicated param name id at path /{id}/{id}'): Route('/{id}/{id}', user) with pytest.raises(ValueError, match='Duplicated param names id, name at path /{id}/{name}/{id}/{name}'): Route('/{id}/{name}/{id}/{name}', user)
('fides.api.service.storage.storage_uploader_service.upload_to_s3') def test_uploader_s3_success_automatic_auth(mock_upload_to_s3: Mock, db: Session, privacy_request: PrivacyRequest) -> None: request_id = privacy_request.id mock_config = {'name': 'test dest', 'key': 'test_dest_key', 'type': StorageType.s3.value...
def test2(): typer = {'reduced set': [{'smarts': '[#1]', 'atype': 'H_MERGE'}, {'smarts': '[#1][#6]([#7,#8])[#7,#8]', 'atype': 'HC'}, {'smarts': '[#1][#8]', 'atype': 'HD'}, {'smarts': '[C]', 'atype': 'C'}, {'smarts': '[c]', 'atype': 'A'}, {'smarts': '[#7]', 'atype': 'NA'}, {'smarts': '[#8]', 'atype': 'OA'}]} pre...
class OptionPlotoptionsBarTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): self._...
('INT') class IntOp(Node): def forward(self, x, final=None, **kwargs): if (x is None): return None if (x == ''): return None if ((final is not None) and all(((f == 'fin') for f in final))): return True if x.startswith(' '): x = x[1:] ...
class Solution(): def longestPalindrome(self, s: str) -> str: def helper(s, l, r): while ((l >= 0) and (r < len(s)) and (s[l] == s[r])): l -= 1 r += 1 return s[(l + 1):r] res = '' for i in range(len(s)): tmp = helper(s, i, i...
def fortios_log_syslogd3(data, fos): fos.do_member_operation('log.syslogd3', 'filter') if data['log_syslogd3_filter']: resp = log_syslogd3_filter(data, fos) else: fos._module.fail_json(msg=('missing task body: %s' % 'log_syslogd3_filter')) return ((not is_successful_status(resp)), (is_su...
class OptionSeriesVariwideSonificationContexttracksMappingNoteduration(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 mock_core_dumps_pass(self, cmd): if ('limits.conf' in cmd): stdout = ['* hard core 0'] stderr = [''] returncode = 0 elif ('sysctl' in cmd): stdout = ['fs.suid_dumpable = 0'] stderr = [''] returncode = 0 return SimpleNamespace(returncode=returncode, stderr=...
def extractThenewdevilBlogspotCom(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...
def filter_firewall_vip_data(json): option_list = ['add_nat46_route', 'arp_reply', 'color', 'comment', 'dns_mapping_ttl', 'extaddr', 'extintf', 'extip', 'extport', 'gratuitous_arp_interval', 'h2_support', 'h3_support', ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'id', 'ipv6_mappedip', 'ipv6_mappedport', 'ldb_method', 'mapped_add...
class ClassificationDummyMetric(ThresholdClassificationMetric[ClassificationDummyMetricResults]): _quality_metric: ClassificationQualityMetric def __init__(self, probas_threshold: Optional[float]=None, k: Optional[int]=None, options: AnyOptions=None): self.probas_threshold = probas_threshold sel...
(scope='function') def fresh_log_file(): cfg = ConfigFile(config_name=None) log_file = os.path.join(cfg.rally_home, 'logs', 'rally.log') if os.path.exists(log_file): bak = os.path.join(tempfile.mkdtemp(), 'rally.log') shutil.move(log_file, bak) (yield log_file) with open(log_...
class Buffer(object): def __init__(self, str_buffer_size=1000): self.i = 0 self.str_buffer = [] self.file_str = StringIO() self.file_str_write = self.file_str.write self.str_buffer_append = self.str_buffer.append self.str_buffer_size = str_buffer_size def flush(se...
def extractNanodesuBibliaKoshodouNoJikenTechou(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, ...
class VideoMedia(DatClass): time: str = None city: str = None country: str = None address_line: str = None district: str = None duration: str = None height: int = None location: str = None province: str = None township: str = None video_media_audio_stream: List[VideoMediaAudi...
class FormParser(BaseParser): media_type = 'application/x-www-form-urlencoded' def parse(self, stream, media_type=None, parser_context=None): parser_context = (parser_context or {}) encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) return QueryDict(stream.read(), encodi...
def test_no_cse_for_listoperation(): cfg = ControlFlowGraph() cfg.add_nodes_from((nodes := [BasicBlock(0, [Branch(Condition(OperationType.equal, [expr1, Constant(1)]))]), BasicBlock(1, []), BasicBlock(2, []), BasicBlock(3, instructions=[Phi(Variable('a', ssa_label=1), [Variable('x', ssa_label=0), Variable('y', ...
def add_binary_feature(feature, n1, n2): if (type(n1) in (GivReg, Reg, Flag)): n1_info = coarse(n1) else: n1_info = fine(n1) if (type(n2) in (GivReg, Reg, Flag)): n2_info = coarse(n2) else: n2_info = fine(n2) if isinstance(n1, Reg): n1.features.add(('L' + feat...
class CFG_Context(): def __init__(self, v_entry=None): assert ((v_entry is None) or isinstance(v_entry, Vertex_Root)) self.v_entry = v_entry self.l_exits = [] self.l_loop_breaks = [] self.l_loop_continues = [] def merge_loops(self, other): assert isinstance(other,...
class hash_algorithm(bsn_tlv): type = 145 def __init__(self, value=None): if (value != None): self.value = value else: self.value = 0 return def pack(self): packed = [] packed.append(struct.pack('!H', self.type)) packed.append(struct.pa...
class TestExtractReadsForLane(unittest.TestCase): def setUp(self): self.wd = tempfile.mkdtemp() self.fastq_data_l2 = u':43:HL3LWBBXX:2:1101:21440:1121 1:N:0:CNATGT\nGCCNGACAGCAGAAAT\n+\nAAF#FJJJJJJJJJJJ\:43:HL3LWBBXX:2:1101:21460:1121 1:N:0:CNATGT\nGGGNGTCATTGATCAT\n+\nAAF#FJJJJJJJJJJJ\:43:HL3LWBBXX...
class TestDataWifi(MultimachineTestCase): def test(self): L.describe('Open and connect the VPN application') self.target_device['vpn_application'].open_and_connect() L.describe('Capture traffic') self.capture_device['packet_capturer'].start() L.describe('Generate whatever tra...
class OptionPlotoptionsScatter3dZones(Options): def className(self): return self._config_get(None) def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get(None) def color(self, text: str): self._config(text, js_type=False...
def download_node_src(node_url, src_dir, args): logger.info('.', extra=dict(continued=True)) dl_contents = _download_node_file(node_url) logger.info('.', extra=dict(continued=True)) if (is_WIN or is_CYGWIN): ctx = zipfile.ZipFile(dl_contents) members = operator.methodcaller('namelist') ...
class EvCell(): def __init__(self, data, **kwargs): self.formatted = None padwidth = kwargs.get('pad_width', None) padwidth = (int(padwidth) if (padwidth is not None) else None) self.pad_left = int(kwargs.get('pad_left', (padwidth if (padwidth is not None) else 1))) self.pad_...
(name=TCP_CONN_TIMEOUT) def validate_tcp_conn_timeout(tcp_conn_timeout): if (not isinstance(tcp_conn_timeout, numbers.Integral)): raise ConfigTypeError(desc=('Invalid tcp connection timeout configuration value %s' % tcp_conn_timeout)) if (tcp_conn_timeout < 10): raise ConfigValueError(desc=('Inv...
class ModifyL3Src(base_tests.SimpleDataPlane): def runTest(self): logging.info('Running Modify_L3_Src test') of_ports = config['port_map'].keys() of_ports.sort() self.assertTrue((len(of_ports) > 1), 'Not enough ports for test') delete_all_flows(self.controller) loggin...
class RateLimitExceptionTests(unittest.TestCase): def test_reset_time(self): time = '2018-08-24T09:36:15Z' exp = arrow.get(time) e = exceptions.RateLimitException(time) self.assertEqual(exp, e.reset_time) def test_str(self): time = '2018-08-24T09:36:15Z' exp = 'Ra...
def cfg_with_single_aliased_variable_3(x, z_aliased) -> Tuple[(ControlFlowGraph, ControlFlowGraph)]: cfg = ControlFlowGraph() (_, mem1, mem2, mem3, mem4, mem5, mem6, mem7, mem8) = generate_mem_phi_variables(9) n1 = BasicBlock(1, [MemPhi(mem3, [mem1, mem2]), Assignment(x[2], z_aliased[3])]) n2 = BasicBlo...
def CreateGroupNormOperator(manifest, rank=5): operation_kind = library.OperationKind.GroupNorm in_dtype = library.DataType.f16 out_dtype = library.DataType.f16 tile_descriptions = [groupnorm.TileDesc(256, 8, 32, 1, 8, 1, 1, 1, 1, 1, 1, 1), groupnorm.TileDesc(256, 8, 32, 1, 8, 1, 2, 1, 2, 1, 2, 2), grou...
def main(args=sys.argv[1:]): cli_parser = argparse.ArgumentParser(prog='nautilus-terminal', epilog=_EPILOG) cli_parser.add_argument('--version', action='version', version=VERSION) cli_parser.add_argument('--print-debug', help='Prints debug informations and exit', nargs=0, action=PrintDebugAction) cli_pa...
def extractRomanticmanfantasyWordpressCom(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,...
class CRUDOperaLogDao(CRUDBase[(OperaLog, CreateOperaLog, UpdateOperaLog)]): async def get_all(self, username: (str | None)=None, status: (int | None)=None, ip: (str | None)=None) -> Select: se = select(self.model).order_by(desc(self.model.created_time)) where_list = [] if username: ...
def test_tac_message_instantiation(): assert TacMessage(performative=TacMessage.Performative.REGISTER, agent_name='some_name') assert TacMessage(performative=TacMessage.Performative.UNREGISTER) assert TacMessage(performative=TacMessage.Performative.TRANSACTION, transaction_id='some_id', ledger_id='some_ledg...
_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestSimpleCheckListEditor(BaseTestMixin, unittest.TestCase): def setUp(self): BaseTestMixin.setUp(self) def tearDown(self): BaseTestMixin.tearDown(self) def setup_gui(self, model, view): with create_ui(model, dict(view=view)) as ui: ...
.usefixtures('use_tmpdir') def test_run_one_job_with_an_integer_arg_is_actually_a_fractional(): executable = 'echo' job_0 = {'name': 'JOB_1', 'executable': executable, 'stdout': 'outfile.stdout.1', 'stderr': None, 'argList': ['a_file', '5.12'], 'min_arg': 1, 'max_arg': 2, 'arg_types': ['STRING', 'RUNTIME_INT']}...
class ResourceWithSuffixRoutes(): def __init__(self): self.get_called = False self.post_called = False self.put_called = False def on_get(self, req, resp, collection_id, item_id): self.collection_id = collection_id self.item_id = item_id self.get_called = True ...
def jit_class(cls, jit_methods, backend): if (not has_to_replace): return cls cls_name = cls.__name__ mod_name = cls.__module__ module = sys.modules[mod_name] if (mod_name == '__main__'): mod_name = find_module_name_from_path(module.__file__) path_jit_class = mpi.Path(backend.jit...
.parametrize('degree', [1, 2, 3]) def test_facet_avg_extruded(mesh, degree): Vt = FunctionSpace(mesh, 'DGT', degree) ft = Function(Vt, name='f_trace') (x, y, z) = SpatialCoordinate(mesh) source = ((((2 * x) + z) - (y * 10)) ** degree) test = TestFunction(Vt) trial = TrialFunction(Vt) a = ((i...
def set_flytekit_log_properties(handler: typing.Optional[logging.Handler]=None, filter: typing.Optional[logging.Filter]=None, level: typing.Optional[int]=None): global logger if (handler is not None): logger.handlers.clear() logger.addHandler(handler) if (filter is not None): logger....
def get_s3_sts_token(resource_id: str, file_name: str, extra_arguments: Mapping[(str, str)]=None) -> _S3STSToken: cache_key = f'{resource_id}:{file_name}' if ((cache_key not in _s3_sts_tokens) or _s3_sts_tokens[cache_key].is_expired()): method = f'tidy3d/py/tasks/{resource_id}/file?filename={file_name}'...
def _check_toy_tokenizer(pieces): assert isinstance(pieces, PiecesWithIds) assert (len(pieces.ids) == 3) assert (len(pieces.pieces) == 3) assert (pieces.ids == [[2, 41, 818, 61, 67, 193, 88, 204, 61, 251, 909, 682, 102, 95, 17, 3], [2, 824, 98, 189, 311, 417, 65, 155, 1, 416, 117, 88, 15, 844, 91, 100, ...
class DataSim(Module, AutoCSR): def __init__(self, pads, cmd_info, latency_ready, mode_regs, ck_freq, wck_ck_ratio, *, log_level, logger_kwargs, nrows=32768, ncols=1024, nbanks=16): self.submodules.log = SimLogger(log_level=log_level('data'), **logger_kwargs) self.submodules.cmd_buf = stream.PipeVal...
class OptionXaxisPlotbands(Options): def borderColor(self): return self._config_get(None) def borderColor(self, text: str): self._config(text, js_type=False) def borderWidth(self): return self._config_get(0) def borderWidth(self, num: float): self._config(num, js_type=Fal...
class LabelledVPNIP6AddrPrefix(_LabelledAddrPrefix, _VPNAddrPrefix, _IP6AddrPrefix): ROUTE_FAMILY = RF_IPv6_VPN def prefix(self): masklen = ((self.length - (struct.calcsize(self._RD_PACK_STR) * 8)) - ((struct.calcsize(self._LABEL_PACK_STR) * 8) * len(self.addr[:(- 2)]))) return (self.addr[(- 1)]...
def ovlp3d_01(ax, da, A, bx, db, B): result = numpy.zeros((1, 3), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = ((ax * bx) * x0) x2 = ((((5. * da) * db) * (x0 ** 1.5)) * numpy.exp(((- x1) * ((((A[0] - B[0]) ** 2) + ((A[1] - B[1]) ** 2)) + ((A[2] - B[2]) ** 2))))) result[(0, 0)] = numpy.sum((x2 * ((x...
class DisablePlugin(MethodView): decorators = [allows.requires(IsAdmin, on_fail=FlashAndRedirect(message=_('You are not allowed to modify plugins'), level='danger', endpoint='management.overview'))] def post(self, name): validate_plugin(name) plugin = PluginRegistry.query.filter_by(name=name).fi...
.slow .parametrize('block_file_name', ['block_1.json', 'block_1234567.json', 'block_.json']) def test_pow_validation_block_headers(block_file_name: str) -> None: block_str_data = cast(bytes, pkgutil.get_data('ethereum', f'assets/blocks/{block_file_name}')).decode() block_json_data = json.loads(block_str_data) ...
def _pack_string(x, write): x = x.encode('utf-8') sz = len(x) if (sz <= 31): write(_struct_pack('B', (160 | sz))) write(x) elif (sz <= ((2 ** 8) - 1)): write(b'\xd9') write(_struct_pack('B', sz)) write(x) elif (sz <= ((2 ** 16) - 1)): write(b'\xda') ...
def add_to_excluded_apps_txt(app, bench_path='.'): if (app == 'frappe'): raise ValueError('Frappe app cannot be excluded from update') if (app not in os.listdir('apps')): raise ValueError(f'The app {app} does not exist') apps = get_excluded_apps(bench_path=bench_path) if (app not in apps...
class HJKRingDetection(): def __init__(self, mgraph, max_iterations=8000000): self.mgraph = {key: [x for x in values] for (key, values) in mgraph.items()} self.rings = [] self._iterations = 0 self._max_iterations = max_iterations self._is_failed = False def scan(self, kee...
_options ('--database-engine', '--database', type=click.Choice([DBType.SQLITE, DBType.MEMORY]), default=DBType.SQLITE, help='database engine to use') ('--tool', type=click.Choice(list(PARSERS.keys())), default='pysa', help='tool the data is coming from') _context def cli(ctx: click.Context, repository: str, database_na...
def get_unique_slug(model_instance, slugable_field_name, slug_field_name): slug = slugify(getattr(model_instance, slugable_field_name)) unique_slug = slug extension = 1 ModelClass = model_instance.__class__ while ModelClass._default_manager.filter(**{slug_field_name: unique_slug}).exists(): ...
def _record_buffer(records, buffer_size=DEFAULT_BUFFER_SIZE): with tempfile.SpooledTemporaryFile(buffer_size, mode='wb+') as tf: pickler = pickle.Pickler(tf) for record in records: pickler.dump(record) def record_iter(): tf.seek(0) unpickler = pickle.Unpic...
class MagicProxy(): def __init__(self, name, parent): self.name = name self.parent = parent def __call__(self, *args, **kwargs): m = self.create_mock() return m(*args, **kwargs) def create_mock(self): entry = self.name parent = self.parent m = parent._...
_app.callback(Output(component_id='galaxy-tab-ui', component_property='style'), [Input('tabs-container', 'value')]) def show_hide_galaxy_tab_ui(tab_value): style_dict = {'display': 'none', 'width': f'{config.CONFIG.plot_width}px', 'margin': 'auto', 'text-align': 'center', 'padding-left': '1%', 'padding-right': '1%'...
class Test_Datapath(unittest.TestCase): def _test_ports_accessibility(self, ofproto_parser, msgs_len): with mock.patch('ryu.controller.controller.Datapath.set_state'): with warnings.catch_warnings(record=True) as msgs: warnings.simplefilter('always') sock_mock = m...
class ConvNet(nn.Module): def __init__(self, height: int, width: int, channels: int, use_combined_linear=False): super(ConvNet, self).__init__() self.conv = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.activation = nn.ReLU() self.linear = nn.Linear((math.prod...
.integrationtest .skipif((not has_postgres_configured), reason='PostgresSQL not configured') def test_psycopg_select_LIKE(instrument, postgres_connection, elasticapm_client): cursor = postgres_connection.cursor() query = "SELECT * FROM test WHERE name LIKE 't%'" try: elasticapm_client.begin_transact...
_os(*metadata.platforms) def main(): import os from os import path import win32file if Path(DLL).is_file(): tempc = path.expandvars('%localappdata%\\Temp\\oversized.dll') rta_dll = path.expandvars('%localappdata%\\Temp\\faultrep.dll') rta_pe = path.expandvars('%localappdata%\\Tem...
class ReadFromFolder(object): def __init__(self, folder_path): fnames = [] for ext in ['.jpg', '.png', '.jpeg', '.bmp']: fnames.extend(glob.glob(((folder_path + '/*') + ext))) self.fnames = sorted(fnames) if (len(self.fnames) == 0): raise IOError(('The folder ...
class SKLearnTransformer(ModelTransformer): def __init__(self, model: Any, feature_names: Sequence[str], classification_labels: Optional[Sequence[str]]=None, classification_weights: Optional[Sequence[float]]=None): super().__init__(model, feature_names, classification_labels, classification_weights) ...
def stability_digest_payload_from_ce_payload(payload: dict): from firebase_functions.alerts.crashlytics_fn import StabilityDigestPayload return StabilityDigestPayload(digest_date=_util.timestamp_conversion(payload['digestDate']), trending_issues=[trending_issue_details_from_ce_payload(issue) for issue in payloa...
def timed_wait(cv, fn, timeout=(- 1)): if (timeout == (- 1)): timeout = default_timeout end_time = (time.time() + timeout) while True: val = fn() if (val != None): return val remaining_time = (end_time - time.time()) cv.wait(remaining_time) if (tim...
def test_passing_enum_to_choice(): class Something(TestSetup): favorite_color: Color = field(default=Color.green) colors: List[Color] = field(default_factory=[Color.green].copy) s = Something.setup('') assert (s.favorite_color == Color.green) assert (s.colors == [Color.green]) s = So...
class WeakCache(WeakKeyDictionary): def __init__(self): self._tuple_dict = WeakKeyDictionary() self._dict = WeakKeyDictionary() def __contains__(self, key): if isinstance(key, (tuple, list)): lookup = self._tuple_dict for k in key: if (k not in loo...
def read_file(fd): key_dat = pkt_dat = None header = fd.readline().strip() a = header.split(':', 1) if (not (a[0].startswith('Filetype') and (a[1].strip() == SUBGHZ_KEY_FILE_TYPE))): print('invalid filetype') sys.exit(0) for line in fd: a = line.split(':', 1) if a[0]....
def reg_or_not(): google_calendar_service_address = os.getenv('DEMO_GOOGLE_CALENDAR_SERVICE_ADDRESS') if ((google_calendar_service_address is None) or (google_calendar_service_address.strip() == '')): logger.warn("'DEMO_GOOGLE_CALENDAR_SERVICE_ADDRESS' is not provided, google calendar function will not ...
def upload_task_input_files(task): storage_client = StorageClient() bucket = storage_client.get_bucket() for path in task.input_paths(): assert (path[0] == '/') assert (settings.PIPELINE_DATA_BASEDIR[(- 1)] == '/') name = ('hscic' + path.replace(settings.PIPELINE_DATA_BASEDIR, '/')) ...
class ShopKeeper(TalkativeNPC): upsell_factor = AttributeProperty(1.0, autocreate=False) miser_factor = AttributeProperty(0.5, autocreate=False) common_ware_prototypes = AttributeProperty([], autocreate=False) def at_damage(self, damage, attacker=None): attacker.msg(f'{self.key} brushes off the ...
class Choropleth(GraphPlotly.Chart): requirements = ('plotly.js',) __reqJs = ['plotly.js'] def chart(self) -> JsPlotly.Pie: if (self._chart is None): self._chart = JsPlotly.Pie(component=self, page=self.page, js_code=self.js_code) return self._chart def layout(self) -> Layout...
def fetch_production(zone_key: str, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: if (target_datetime is not None): raise NotImplementedError('This parser is not yet able to parse past dates') r = (session or requests.session()) ...
class Mxp(): def __init__(self, protocol): self.protocol = protocol self.protocol.protocol_flags['MXP'] = False if settings.MXP_ENABLED: self.protocol.will(MXP).addCallbacks(self.do_mxp, self.no_mxp) def no_mxp(self, option): self.protocol.protocol_flags['MXP'] = Fals...
def resize_all_icons(repodirs): for repodir in repodirs: for density in screen_densities: icon_dir = get_icon_dir(repodir, density) icon_glob = os.path.join(icon_dir, '*.png') for iconpath in glob.glob(icon_glob): resize_icon(iconpath, density)
_event class PeopleAdded(ThreadEvent): thread = attr.ib(type='_threads.Group') added = attr.ib(type=Sequence['_threads.User']) at = attr.ib(type=datetime.datetime) def _parse(cls, session, data): (author, thread, at) = cls._parse_metadata(session, data) added = [_threads.User(session=ses...
def annotate(obj, owner, **kwargs): if hasattr(obj, '_metadata'): _annotate_pandas(obj, owner, **kwargs) return obj if hasattr(obj, 'climetlab'): _annotate_xarray(obj, owner, **kwargs) return obj raise NotImplementedError('Cannot annotate object of type', type(obj))
class ParameterDescription(object): def __init__(self, name, msg_type, value=None, widget=None): self._name = str(name) self._type = msg_type self._value = None self._value_org = None self.read_only = False self.path_type = '' self.hint = '' self._min ...
class TabSetHtmlTransform(SphinxPostTransform): default_priority = 200 formats = ('html',) def run(self) -> None: tab_set_id_base = 'sd-tab-set-' tab_set_id_num = 0 tab_item_id_base = 'sd-tab-item-' tab_item_id_num = 0 for tab_set in findall(self.document)((lambda nod...
class HasAdLabels(object): def add_labels(self, labels=None): return self.get_api_assured().call('POST', (self.get_id_assured(), 'adlabels'), params={'adlabels': [{'id': label} for label in labels]}) def remove_labels(self, labels=None): return self.get_api_assured().call('DELETE', (self.get_id_...
class OptionSeriesPyramid3dSonificationContexttracksMappingRate(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 generate_sleep_modal_summary(days=7): date = (datetime.now().date() - timedelta(days=days)) df = pd.read_sql(sql=app.session.query(ouraSleepSummary.report_date, ouraSleepSummary.score, ouraSleepSummary.total, ouraSleepSummary.bedtime_end_local).filter((ouraSleepSummary.report_date > date)).statement, con=en...
def test_set_pod_security_context(): config = '' r = helm_template(config) assert (r['statefulset'][name]['spec']['template']['spec']['securityContext']['fsGroup'] == 1000) assert (r['statefulset'][name]['spec']['template']['spec']['securityContext']['runAsUser'] == 1000) config = '\n podSecurity...
def main(me, args): parser = optparse.OptionParser('%prog [options] <executable_path>') parser.add_option('--executable-heap', action='store_false', dest='no_heap_execution', default=True, help='Clear the MH_NO_HEAP_EXECUTION bit') parser.add_option('--no-pie', action='store_false', dest='pie', default=True...
class CmdInventory(EvAdventureCommand): key = 'inventory' aliases = ('i', 'inv') def func(self): loadout = self.caller.equipment.display_loadout() backpack = self.caller.equipment.display_backpack() slot_usage = self.caller.equipment.display_slot_usage() self.caller.msg(f'''{...
def print_output(p): from select import select while (p.poll() is None): readx = select([p.stdout.fileno(), p.stderr.fileno()], [], [])[0] send_buffer = [] for fd in readx: if (fd == p.stdout.fileno()): while 1: buf = p.stdout.read(1) ...
class MergeFind(): def __init__(self): self.db = dict() def merge(self, a, b): a = self.find(a) b = self.find(b) if (a != b): self.db[a] = b def find(self, a): if (a in self.db): c = self.find(self.db[a]) self.db[a] = c ...
.parametrize('key,num_tokens,etype', [('', 1, ValueError), ('', 0, ValueError), ('x', 0, ValueError), ('x', (- 1), ValueError), ('x', (- 2), ValueError), ((- 1), None, (ValueError, TypeError)), (None, (- 1), (ValueError, TypeError)), (None, 1, TypeError), (1, None, TypeError)]) def test_input_validation_on_consume(key,...
def reference_launch_plan(project: str, domain: str, name: str, version: str) -> Callable[([Callable[(..., Any)]], ReferenceLaunchPlan)]: def wrapper(fn) -> ReferenceLaunchPlan: interface = transform_function_to_interface(fn) return ReferenceLaunchPlan(project, domain, name, version, interface.input...
def test_hydrate_registration_parameters__task_already_set(): task = _task_pb2.TaskSpec(template=_core_task_pb2.TaskTemplate(id=_identifier_pb2.Identifier(resource_type=_identifier_pb2.TASK, project='project2', domain='domain2', name='name', version='abc'))) (identifier, entity) = hydrate_registration_parameter...
_visible def detect_joomla(source_file, regexp): if (not (os.path.isfile(source_file) and regexp)): return logging.debug('Dectecting Joomla from: %s', source_file) release_version = grep_from_file(source_file, regexp[0]) if (not release_version): logging.debug('Could not find release ver...