code
stringlengths
281
23.7M
class TestWeightedMinHashGenerator(unittest.TestCase): def test_init(self): mg = WeightedMinHashGenerator(2, 4, 1) self.assertEqual(len(mg.rs), 4) self.assertEqual(len(mg.ln_cs), 4) self.assertEqual(len(mg.betas), 4) self.assertEqual(mg.seed, 1) self.assertEqual(mg.sa...
class table_stats_request(stats_request): version = 2 type = 18 stats_type = 3 def __init__(self, xid=None, flags=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags else: sel...
def clients(api_settings: Dict) -> Dict: return {'speech': boto3.client('transcribe', region_name=api_settings['region_name'], aws_access_key_id=api_settings['aws_access_key_id'], aws_secret_access_key=api_settings['aws_secret_access_key']), 'texttospeech': boto3.client('polly', region_name=api_settings['ressource_...
class OptionPlotoptionsColumnrangeSonificationDefaultinstrumentoptionsMappingLowpass(Options): def frequency(self) -> 'OptionPlotoptionsColumnrangeSonificationDefaultinstrumentoptionsMappingLowpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsColumnrangeSonificationDefaultinstrument...
class CardGamesTest(unittest.TestCase): .task(taskno=1) def test_get_rounds(self): input_data = [0, 1, 10, 27, 99, 666] result_data = [[0, 1, 2], [1, 2, 3], [10, 11, 12], [27, 28, 29], [99, 100, 101], [666, 667, 668]] for (variant, (number, expected)) in enumerate(zip(input_data, result_...
class TCPSocketChannel(IPCChannel): def __init__(self, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None) -> None: self.logger = logger self._loop = loop self._server = None self._connected = None self._sock = None s = socket.socket(socket...
class _BoundingBoxDistanceGraphicMatcherInstance(NamedTuple): graphic_bounding_box_ref_list: Sequence[BoundingBoxRef] candidate_bounding_box_ref_list: Sequence[BoundingBoxRef] max_distance: float def create(semantic_graphic_list: Sequence[SemanticGraphic], candidate_semantic_content_list: Sequence[Seman...
def extractWwwNekoseireiCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Godly Alchemist', 'Godly Alchemist', 'translated'), ('Kein no Zenkou', 'Kein no Zenkou', 'translated...
def save_user_config(filename: Optional[Union[(PathLike, str)]]=None, user_config: Optional[Config]=None, compact: bool=False, indent: int=4, encoding: Optional[str]=None): if (filename is None): filename = default_user_config_filepath if (user_config is None): user_config = get_user_config() ...
class OptionSeriesSankeyDataEvents(Options): def click(self): return self._config_get(None) def click(self, value: Any): self._config(value, js_type=False) def drag(self): return self._config_get(None) def drag(self, value: Any): self._config(value, js_type=False) def...
class OptionPlotoptionsNetworkgraphZones(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=Fa...
(scope='function') def postgres_integration_db(postgres_integration_session): postgres_integration_session = seed_postgres_data(postgres_integration_session, './src/fides/data/sample_project/postgres_sample.sql') (yield postgres_integration_session) drop_database(postgres_integration_session.bind.url)
_pytree_node_class class JaxStructureStaticMedium(AbstractJaxStructure, JaxObject): geometry: JaxGeometryType = pd.Field(..., title='Geometry', description='Geometry of the structure, which is jax-compatible.', jax_field=True, discriminator=TYPE_TAG_STR) medium: MediumType = pd.Field(..., title='Medium', descri...
class OptionSeriesTimelineSonificationContexttracksMappingTremoloSpeed(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 show_task_info(task): log.log(26, '') set_logindent(1) log.log(28, ('(%s) %s' % (color_status(task.status), task))) logindent(2) st_info = ', '.join([('%d(%s)' % (v, k)) for (k, v) in task.job_status.items()]) log.log(26, ('%d jobs: %s' % (len(task.jobs), st_info))) tdir = task.taskid ...
class PrivateKey(BaseKey, LazyBackend): public_key = None def __init__(self, private_key_bytes: bytes, backend: 'Union[BaseECCBackend, Type[BaseECCBackend], str, None]'=None) -> None: validate_private_key_bytes(private_key_bytes) self._raw_key = private_key_bytes self.public_key = self.b...
def parse_color(tokens: dict[(str, Any)], space: Space) -> (tuple[(Vector, float)] | None): num_channels = len(space.CHANNELS) values = len(tokens['func']['values']) if tokens['func']['slash']: values -= 1 if (values != num_channels): return None alpha = (norm_alpha_channel(tokens['f...
class BasicBlockEdge(GraphEdgeInterface, ABC): def __init__(self, source: BasicBlock, sink: BasicBlock): self._source = source self._sink = sink def source(self) -> BasicBlock: return self._source def sink(self) -> BasicBlock: return self._sink def __eq__(self, other): ...
def render_geom(geom_type, geom_size, color=[0.5, 0.5, 0.5, 1.0], T=constants.EYE_T): if (geom_type == pybullet.GEOM_SPHERE): gl_render.render_sphere(T, geom_size[0], color=color, slice1=16, slice2=16) elif (geom_type == pybullet.GEOM_BOX): gl_render.render_cube(T, size=[geom_size[0], geom_size[...
def fixpoint_graph_fixer(fixer: GraphFixer) -> GraphFixer: def fixpoint(bmg: BMGraphBuilder) -> GraphFixerResult: current = bmg while True: (current, made_progress, errors) = fixer(current) if ((not made_progress) or errors.any()): return (current, made_progre...
class OptionSeriesLollipopStatesSelect(Options): def animation(self) -> 'OptionSeriesLollipopStatesSelectAnimation': return self._config_sub_data('animation', OptionSeriesLollipopStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): se...
class CarModelTestSerializer(ExpandableFieldsMixin, serializers.ModelSerializer): class Meta(): fields = ('id', 'name') model = models.CarModel expandable_fields = dict(manufacturer=ManufacturerTestSerializer, skus=dict(serializer='{0}.SkuTestSerializer'.format(MODULE), many=True))
def _re_wrap_quantifier(q, xp, lazy=False): if (q is None): return xp if (lazy and (q not in (_ONE_PLUS, _ZERO_PLUS))): raise ValueError if (q not in _WRAP_Q_LOOKUP): keys = ', '.join(_WRAP_Q_LOOKUP.keys()) raise ValueError(Errors.E011.format(op=q, opts=keys)) xpq = _WRAP...
class MappedParameter(parser.ParameterWithValue): def __init__(self, list_name, values, case_sensitive, **kwargs): super(MappedParameter, self).__init__(**kwargs) self.list_name = list_name self.case_sensitive = case_sensitive self.values = values def _uncase_values(self, values)...
class SearchService(): def __init__(self, github_client: Github): self._github_client = github_client def search_repositories(self, query, limit): repositories = self._github_client.search_repositories(query=query, **{'in': 'name'}) return [self._format_repo(repository) for repository in...
def upgrade(): op.create_table('access_codes_tickets', sa.Column('access_code_id', sa.Integer(), nullable=False), sa.Column('ticket_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['access_code_id'], ['access_codes.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ondelet...
class OptionSeriesVectorSonification(Options): def contextTracks(self) -> 'OptionSeriesVectorSonificationContexttracks': return self._config_sub_data('contextTracks', OptionSeriesVectorSonificationContexttracks) def defaultInstrumentOptions(self) -> 'OptionSeriesVectorSonificationDefaultinstrumentoption...
def div_polys(a, b): assert (len(a) >= len(b)) a = [x for x in a] o = [] apos = (len(a) - 1) bpos = (len(b) - 1) diff = (apos - bpos) while (diff >= 0): quot = gexptable[((glogtable[a[apos]] - glogtable[b[bpos]]) + two_to_the_degree_m1)] o.insert(0, quot) for i in ran...
def get_user_by_payload(payload): username = jwt_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER(payload) if (not username): raise exceptions.JSONWebTokenError(_('Invalid payload')) user = jwt_settings.JWT_GET_USER_BY_NATURAL_KEY_HANDLER(username) if ((user is not None) and (not getattr(user, 'is_acti...
def add_kid(kid_b64, key_b64): kid = b64decode(kid_b64) asn1data = b64decode(key_b64) pub = serialization.load_der_public_key(asn1data) if isinstance(pub, RSAPublicKey): kids[kid_b64] = CoseKey.from_dict({KpKty: KtyRSA, KpAlg: Ps256, RSAKpE: int_to_bytes(pub.public_numbers().e), RSAKpN: int_to_b...
class CleanupPayload(Payload): def __init__(self, *args, **kwargs): super(CleanupPayload, self).__init__(*args, **kwargs) self.files_to_clean = [] self.to_drop = [] self.sqls_to_execute = [] self._current_db = kwargs.get('db') self._current_table = kwargs.get('table')...
.django_db def test_fabs_old_submission(client, monkeypatch, fabs_award_with_old_submission, helpers, elasticsearch_award_index): setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) helpers.patch_datetime_now(monkeypatch, 2022, 12, 31) resp = helpers.post_for_count_endpoint(client, url, ['M'], ...
class NursingTask(Document): def before_insert(self): self.set_task_schedule() self.title = '{} - {}'.format(_(self.patient), _(self.activity)) self.age = frappe.get_doc('Patient', self.patient).get_age() def validate(self): if (self.status == 'Requested'): self.docst...
class Player(models.Model): class Meta(): verbose_name = '' verbose_name_plural = '' permissions = (('change_credit', ''),) id = models.AutoField(**_('ID'), primary_key=True) user = models.OneToOneField(authext.models.User, models.CASCADE, **_(''), unique=True) name = models.Char...
.parametrize('with_spiders', [True, pytest.param(False, marks=pytest.mark.slow)]) def test_tmt_aperture(with_spiders): name = 'tmt/pupil' name += ('_without_spiders' if (not with_spiders) else '') check_aperture(make_tmt_aperture, 30.0, name, check_normalization=True, check_segmentation=True, with_spiders=w...
class HeaderDB(HeaderDatabaseAPI): def __init__(self, db: AtomicDatabaseAPI) -> None: self.db = db def get_header_chain_gaps(self) -> ChainGaps: return self._get_header_chain_gaps(self.db) def _get_header_chain_gaps(cls, db: DatabaseAPI) -> ChainGaps: try: encoded_gaps = ...
def check_on_disk_config(fw): fw_config = FirewallConfig(fw) try: _firewalld_conf = firewalld_conf(config.FIREWALLD_CONF) _firewalld_conf.read() except FirewallError as error: raise FirewallError(error.code, ("'%s': %s" % (config.FIREWALLD_CONF, error.msg))) except IOError: ...
class ExtractGrid(FilterBase): __version__ = 0 x_min = Range(value=0, low='_x_low', high='_x_high', enter_set=True, auto_set=False, desc='minimum x value of the domain') x_max = Range(value=10000, low='_x_low', high='_x_high', enter_set=True, auto_set=False, desc='maximum x value of the domain') y_min =...
class OptionSeriesAreasplineSonificationTracksMappingPlaydelay(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): s...
class PreProcessingObservationConversion(ObservationConversion): def space(self) -> gym.spaces.space.Space: return gym.spaces.Dict({'observation_0_feature_series': gym.spaces.Box(low=np.float32(0), high=np.float32(1), shape=(64, 24), dtype=np.float32), 'observation_0_image': gym.spaces.Box(low=0.0, high=1.0...
class ModelTest(unittest.TestCase): def setUp(self): x = torch.randn(3, 1) y = torch.randn(3) mean = ConstantMean(constant_prior=UniformPrior((- 1), 1)) kernel = kernels.MaternKernel(lengthscale_prior=GammaPrior(0.5, 0.5)) lik = likelihoods.GaussianLikelihood() self.m...
class LogThread(threading.Thread): def __init__(self, interval, device, attributes): super(LogThread, self).__init__() self.interval = interval self.device = device self.attributes = attributes self.done = threading.Event() def run(self): tic = time.time() ...
def get_classes(module_label, classnames): app_label = module_label.split('.')[0] app_module_path = _get_app_module_path(module_label) if (not app_module_path): raise AppNotFoundError("No app found matching '{}'".format(module_label)) module_path = app_module_path if ('.' in app_module_path)...
.parametrize(['operation', 'result'], [(BinaryOperation(OperationType.plus, [var, con_0]), [var]), (BinaryOperation(OperationType.minus, [var, con_0]), [var]), (BinaryOperation(OperationType.multiply, [var, con_0]), [con_0]), (BinaryOperation(OperationType.multiply_us, [var, con_0]), [con_0]), (BinaryOperation(Operatio...
def module_combined(output, param, subtree_parameters, module_idx): return Module(_module_combined, render_kwds=dict(output=output, VALUE_NAME=VALUE_NAME, shape=param.annotation.type.shape, module_idx=module_idx, disassemble=_snippet_disassemble_combined, connector_ctype=param.annotation.type.ctype, nq_indices=inde...
(scope='function') def privacy_experience_privacy_center(db: Session, experience_config_privacy_center) -> Generator: privacy_experience = PrivacyExperience.create(db=db, data={'component': ComponentType.privacy_center, 'region': PrivacyNoticeRegion.us_co, 'experience_config_id': experience_config_privacy_center.id...
class _MemberSpec(object): __slots__ = ('name', 'idlflags', 'restype') def __init__(self, name, idlflags, restype): self.name = name self.idlflags = idlflags self.restype = restype def is_prop(self): propflags = ('propget', 'propput', 'propputref') return any(((f in p...
_meta(characters.alice.LittleLegionDollControlCard) class LittleLegionDollControlCard(): name = '' custom_ray = True def effect_string(self, act): (controllee, victim) = act.target_list return f'{N.char(act.source)}......,{N.char(controllee)},{N.char(victim)}!' def sound_effect(self, act...
def get_serializable_flyte_workflow(entity: 'FlyteWorkflow', settings: SerializationSettings) -> FlyteControlPlaneEntity: def _mutate_task_node(tn: workflow_model.TaskNode): tn.reference_id._project = settings.project tn.reference_id._domain = settings.domain def _mutate_branch_node_task_ids(bn:...
_register_exp_type(ofproto_common.ONF_EXPERIMENTER_ID, ofproto.ONF_ET_BUNDLE_CONTROL) class ONFBundleCtrlMsg(OFPExperimenter): def __init__(self, datapath, bundle_id=None, type_=None, flags=None, properties=None): super(ONFBundleCtrlMsg, self).__init__(datapath, ofproto_common.ONF_EXPERIMENTER_ID, ofproto.O...
def test_unsigned_to_signed_transaction(txn_fixture, transaction_class): key = keys.PrivateKey(decode_hex(txn_fixture['key'])) unsigned_txn = transaction_class.create_unsigned_transaction(nonce=txn_fixture['nonce'], gas_price=txn_fixture['gasPrice'], gas=txn_fixture['gas'], to=(to_canonical_address(txn_fixture[...
class Example(flx.HFix): def init(self): with flx.VBox(): self.b1 = flx.Button(text='apple') self.b2 = flx.Button(text='banana') self.b3 = flx.Button(text='pear') self.buttonlabel = flx.Label(text='...') with flx.VBox(): self.r1 = flx.Radio...
(tags=['disbursements'], description=docs.SCHEDULE_B_BY_RECIPIENT) class ScheduleBByRecipientView(AggregateResource): model = models.ScheduleBByRecipient schema = schemas.ScheduleBByRecipientSchema page_schema = schemas.ScheduleBByRecipientPageSchema query_args = args.schedule_b_by_recipient filter_...
def check_ipaddr(ip, prefix, is_ipv6=False): import socket if is_ipv6: fa = socket.AF_INET6 else: fa = socket.AF_INET try: socket.inet_pton(fa, ip) except: return False if (prefix < 0): return False if (is_ipv6 and (prefix > 128)): return False...
class ContourGridPlane(Module): __version__ = 0 grid_plane = Instance(GridPlane, allow_none=False, record=True) enable_contours = Bool(True, desc='if contours are generated') contour = Instance(Contour, allow_none=False, record=True) actor = Instance(Actor, allow_none=False, record=True) input_i...
def load_schema_files(files: List[str]) -> Dict[(str, FieldNestedEntry)]: fields_nested: Dict[(str, FieldNestedEntry)] = {} for f in files: new_fields: Dict[(str, FieldNestedEntry)] = read_schema_file(f) fields_nested = ecs_helpers.safe_merge_dicts(fields_nested, new_fields) return fields_ne...
class OptionSeriesStreamgraphSonificationTracksMappingTime(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 ContextMock(): cwd = 'cwd' def __init__(self, *args, **kwargs): self.invoke = Mock() self.agent_config = AgentConfigMock(*args, **kwargs) self.config: dict = {} self.connection_loader = ConfigLoaderMock() self.agent_loader = ConfigLoaderMock() self.clean_pat...
def parse_block_2021(lines): chain1_name = lines[7].split(':')[1].rstrip().lstrip().split(' ')[0] chain2_name = lines[8].split(':')[1].rstrip().lstrip().split(' ')[0] print(chain1_name, chain2_name) tmscore1 = float(lines[13].lstrip().split(' ')[1]) tmscore2 = float(lines[14].lstrip().split(' ')[1])...
def check_dangling_end(read, dangling_sequences): ds = dangling_sequences if (('pat_forw' not in ds) or ('pat_rev' not in ds)): return False if ((not read.is_reverse) and read.seq.upper().startswith(ds['pat_forw'])): return True if (read.is_reverse and read.seq.upper().endswith(ds['pat_r...
def register_bigquery_handlers(): try: from .bigquery import ArrowToBQEncodingHandlers, BQToArrowDecodingHandler, BQToPandasDecodingHandler, PandasToBQEncodingHandlers StructuredDatasetTransformerEngine.register(PandasToBQEncodingHandlers()) StructuredDatasetTransformerEngine.register(BQToPa...
class OptionPlotoptionsGaugeDatalabelsTextpath(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._config(...
class NewsArticle(object): authors = [] date_download = None date_modify = None date_publish = None description = None filename = None image_url = None language = None localpath = None source_domain = None maintext = None text = None title = None title_page = None...
.parametrize('raw_data, encoded_data', ethtest_fixtures_as_pytest_fixtures('RandomRLPTests/example.json')) def test_ethtest_fixtures_for_successfull_rlp_decoding(raw_data: Bytes, encoded_data: Bytes) -> None: decoded_data = rlp.decode(encoded_data) assert (rlp.encode(decoded_data) == encoded_data)
class ElectionDate(db.Model, FecAppMixin): __tablename__ = 'trc_election' trc_election_id = db.Column(db.Integer, primary_key=True) election_state = db.Column(db.String, index=True, doc=docs.STATE) election_district = db.Column(db.String, index=True, doc=docs.DISTRICT) election_party = db.Column(db....
def get_line_objs_from_lines(input_lines: List[str], validate_file_exists: bool=True, all_input: bool=False) -> Dict[(int, LineBase)]: line_objs: Dict[(int, LineBase)] = {} for (index, line) in enumerate(input_lines): line = line.replace('\t', (' ' * 4)) line = line.replace('\n', '') for...
def test_local_storage_makedirs_permissionerror(monkeypatch): def mockmakedirs(path, exist_ok=False): raise PermissionError('Fake error') data_cache = os.path.join(os.curdir, 'test_permission') assert (not os.path.exists(data_cache)) monkeypatch.setattr(os, 'makedirs', mockmakedirs) with pyt...
def Follow_path(path): global final_goal_location, goal_reached cpath = path goal_point = cpath[(- 1)] print('Following Path -->', cpath) for loc in cpath: while (Distance_compute(robot_location, loc) > 0.1): goal_location_marker(final_goal_location) points_publisher(...
def get_adr_citations(case_id): citations = [] with db.engine.connect() as conn: rs = conn.execute(ADR_CITATIONS, case_id) for row in rs: citations = parse_statutory_citations(row['statutory_citation'], case_id, row['name']) citations.extend(parse_regulatory_citations(row...
class Tor(): TOR_PATH_WIN = '.\\torbundle\\Tor\\tor.exe' TOR_PATH_LINUX = './tor_linux/tor' def __init__(self): self.tor_process = self.start() socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', 9050) socket.socket = socks.socksocket def start(self): try: if (...
def parse_color(base, string, start=0, second=False): length = len(string) more = None ratio = None color = base.match(string, start=start, fullmatch=False) if color: start = color.end if (color.end != length): more = True m = tools.RE_RATIO.match(string, star...
class LCSTSProcessor(DataProcessor): def get_examples(self, data_path): return self._create_examples(self._read_tsv(data_path)) def _create_examples(self, lines): examples = [] for data in lines: guid = data[0] src = convert_to_unicode(data[2]) tgt = c...
class TestNormaliseBarcode(unittest.TestCase): def test_normalise_barcode(self): self.assertEqual(normalise_barcode('CGATGT'), 'CGATGT') self.assertEqual(normalise_barcode('CGTGTAGG-GACCTGTA'), 'CGTGTAGGGACCTGTA') self.assertEqual(normalise_barcode('CGTGTAGG+GACCTGTA'), 'CGTGTAGGGACCTGTA') ...
_tag('forum_conversation/topic_pages_inline_list.html') def topic_pages_inline_list(topic): data_dict = {'topic': topic} pages_number = (((topic.posts_count - 1) // machina_settings.TOPIC_POSTS_NUMBER_PER_PAGE) + 1) if (pages_number > 5): data_dict['first_pages'] = range(1, 5) data_dict['las...
class Config(): def __init__(self, path): self.path = path self.cf = configparser.ConfigParser() self.cf.read(self.path) def get(self, field, key): result = '' try: result = self.cf.get(field, key) except: result = '' return result ...
class RunPython(): def __init__(self, strip_newlines: bool=False, return_err_output: bool=False, workdir: str='.'): self.strip_newlines = strip_newlines self.return_err_output = return_err_output self.workdir = workdir def run(self, commands: str) -> str: if (not commands.strip()...
_renderer(wrap_type=ColumnInteractionPlot) class ColumnInteractionPlotRenderer(MetricRenderer): def render_html(self, obj: ColumnInteractionPlot) -> List[BaseWidgetInfo]: metric_result = obj.get_result() agg_data = (not obj.get_options().render_options.raw_data) if ((metric_result.x_type == ...
def update_wav_lab_pairs(): wav_count = tot_count = 0 for (root, _, files) in os.walk('./raw'): for file in files: file_path = os.path.join(root, file) if file.lower().endswith('.wav'): lab_file = (os.path.splitext(file_path)[0] + '.lab') if os.pat...
class OptionSeriesBellcurveStatesHoverMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): self._co...
def test_complicated_schema(): foundry_schema = {'fieldSchemaList': [{'type': 'STRUCT', 'name': 'url', 'nullable': True, 'userDefinedTypeClass': None, 'customMetadata': {}, 'arraySubtype': None, 'precision': None, 'scale': None, 'mapKeyType': None, 'mapValueType': None, 'subSchemas': [{'type': 'STRING', 'name': 'va...
def get_110900_data() -> list[dict[(str, int)]]: data: list[dict[(str, int)]] = [] data.append(next_int_len(4)) data.append(next_int_len(2)) data.append(next_int_len(1)) data.append(next_int_len(1)) data.append(next_int_len(1)) data.append(next_int_len(1)) ivar_14 = next_int_len(1) d...
def extractSporadictranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('muscle magic', 'Magic? Muscle Is Much More Important Than Such A Thing!', 'translate...
def unregisterMethodCallback(path): with _web_lock: try: del _web_methods[path] except KeyError: _logger.error("'{}' is not registered".format(path)) return False else: _logger.debug('Unregistered method {}'.format(path)) return Tru...
class CustomerResponse(ModelComposed): allowed_values = {('billing_network_type',): {'PUBLIC': 'public', 'PRIVATE': 'private'}} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable =...
def main(args=None): args = parse_arguments().parse_args(args) mpl.rcParams['pdf.fonttype'] = 42 log.warning('This tool is deprecated. Please use chicViewpoint, chicViewpointBackgroundModel and chicPlotViewpoint.') if args.region: args.region = args.region.replace(',', '') args.region = ...
_os(*metadata.platforms) def main(): nslookup = 'C:\\Windows\\System32\\nslookup.exe' common.execute([nslookup, '-q=aaaa', 'google.com'], timeout=10) common.execute([nslookup, '-q=aaaa', 'google.com'], timeout=10) common.execute([nslookup, '-q=aaaa', 'google.com'], timeout=10) common.execute([nslook...
class OptionSeriesAreasplinerangeMarkerStatesSelect(Options): def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._config(flag, js_type=False) def fillColor(self): return self._config_get('#cccccc') def fillColor(self, text: str): self._co...
class OptionSeriesColumnSonificationDefaultinstrumentoptions(Options): def activeWhen(self) -> 'OptionSeriesColumnSonificationDefaultinstrumentoptionsActivewhen': return self._config_sub_data('activeWhen', OptionSeriesColumnSonificationDefaultinstrumentoptionsActivewhen) def instrument(self): re...
def get_app_display_name(app): if app.get('Name'): return app['Name'] if app.get('localized'): localized = app['localized'].get(DEFAULT_LOCALE) if (not localized): for v in app['localized'].values(): localized = v break if localized.get...
class Body(Attrs): def __init__(self, component: primitives.HtmlModel, page: primitives.PageModel=None): super(Body, self).__init__(component, page=page) self.font_size = component.style.globals.font.normal() self.font_family = component.style.globals.font.family self.margin = 0
class Collision(object): swagger_types = {'created_at': 'datetime', 'embedded': 'object', 'front': 'CollisionObjFront', 'id': 'str', 'lateral': 'CollisionObjFront', 'pedestrian': 'bool', 'rear': 'CollisionObjFront', 'roll_over': 'bool', 'updated_at': 'datetime', 'links': 'CollisionLinks'} attribute_map = {'crea...
class TestGenericOefSearchHandler(BaseSkillTestCase): path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'generic_seller') is_agent_to_agent_messages = False def setup(cls): super().setup() cls.oef_search_handler = cast(GenericOefSearchHandler, cls._skill.skill_context.handlers....
def test_comp7(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = (test_dir / 'test_block.f08') string += comp_request(file_path, 2, 2) string += comp_request(file_path, 5, 4) string += comp_request(file_path, 8, 6) (errcode, results) = run_request(string, ['...
def _log_summary(ep_len, ep_ret, ep_num): ep_len = str(round(ep_len, 2)) ep_ret = str(round(ep_ret, 2)) print(flush=True) print(f' Episode #{ep_num} ', flush=True) print(f'Episodic Length: {ep_len}', flush=True) print(f'Episodic Return: {ep_ret}', flush=True) print(f'', flush=True) print...
class PyperfComparisons(): _table: 'PyperfTable' def parse_table(cls, text: str, filenames: Optional[Iterable[str]]=None) -> 'PyperfComparisons': table = PyperfTable.parse(text, filenames) if (table is None): raise ValueError('Could not parse table') return cls.from_table(tab...
class TestSequenceFunctions(unittest.TestCase): def __init__(self, *args, **kwargs): logSetup.initLogging() super().__init__(*args, **kwargs) def setUp(self): self.buildTestTree() def buildTestTree(self): self.tree = hamDb.BkHammingTree() for (nodeId, nodeHash) in TES...
class ExpandFqcnCommand(sublime_plugin.TextCommand): def run(self, edit, leading_separator=False): view = self.view self.region = view.word(view.sel()[0]) symbol = view.substr(self.region) if (re.match('\\w', symbol) is None): return sublime.status_message(('Not a valid s...
def home(request, room_id=None): user = request.GET.get('user') if user: if (not room_id): return redirect(('/default?' + request.GET.urlencode())) last_id = get_current_event_id(['room-{}'.format(room_id)]) try: room = ChatRoom.objects.get(eid=room_id) ...
def relax(): selection = pm.ls(sl=1) if (not selection): return verts = pm.ls(pm.polyListComponentConversion(tv=1)) if (not verts): return shape = verts[0].node() dup = shape.duplicate()[0] dup_shape = dup.getShape() pm.polyAverageVertex(verts, i=1, ch=0) ta_node = pm...
class CollectionEntity(db.BaseModel): local_user = pw.ForeignKeyField(User, backref='collections', on_delete='CASCADE') uid = pw.CharField(null=False, index=True) eb_col = pw.BlobField() new = pw.BooleanField(null=False, default=False) dirty = pw.BooleanField(null=False, default=False) deleted =...