code
stringlengths
281
23.7M
class NullSecretHandler(SecretHandler): def __init__(self, logger: logging.Logger, source_root: Optional[str], cache_dir: Optional[str], version: str) -> None: if (not source_root): self.tempdir_source = tempfile.TemporaryDirectory(prefix='null-secret-', suffix='-source') source_root...
class TupleExpression(PrimaryExpression, TupleMixin, LValueMixin): components: List[Expression] flattened_expressions = synthesized() flattened_expression_values = synthesized() flattened_assignment_generators = synthesized() def variables_map(self) -> (Statement.variables_pre components): ...
class ThreeCenterTwoElectronBase(Function): def eval(cls, ia, ja, ka, ib, jb, kb, ic, jc, kc, N, a, b, c, A, B, C): ang_moms = np.array((ia, ja, ka, ib, jb, kb, ic, jc, kc), dtype=int) ang_moms2d = ang_moms.reshape((- 1), 3) if any([(am < 0) for am in ang_moms]): return 0 ...
class Images(): def __init__(self, ui): self.page = ui.page def img(self, image: str=None, path: str=None, width: types.SIZE_TYPE=(100, '%'), height: types.SIZE_TYPE=(None, 'px'), align: str='center', html_code: str=None, profile: types.PROFILE_TYPE=None, tooltip: str=None, options: types.OPTION_TYPE=No...
def can_delete_topic(user, topic=None): kwargs = {} if isinstance(topic, int): kwargs['topic_id'] = topic elif isinstance(topic, Topic): kwargs['topic'] = topic return Permission(Or(IsAtleastSuperModerator, And(IsModeratorInForum(), Has('deletetopic')), And(IsSameUser(), Has('deletetopic...
def main(): curr_lexicon = dict() ap = argparse.ArgumentParser(description='Convert Finnish dictionary TSV data into xerox/HFST lexc format') ap.add_argument('--quiet', '-q', action='store_false', dest='verbose', default=False, help='do not print output to stdout while processing') ap.add_argument('--ve...
def backup(*, volume: str, pool: str, namespace: str='', image: str, version_labels: Dict[(str, str)]={}, version_uid: str=None, source_compare: bool=False, context: Any=None): signal_backup_pre.send(SIGNAL_SENDER, volume=volume, pool=pool, namespace=namespace, image=image, version_labels=version_labels, context=co...
class BoundFunction(BoundFunctionBase): def setup_impl(self, call_info: FunctionCallInfo): returns = [ir.Argument(call_info.ast_node) for _ in range(call_info.result_arity)] continuation = ir.Block(call_info.ast_node, returns, info='CONTINUATION') destination = ir.CallTarget(self.member_acce...
class WhoosheeQuery(BaseQuery): def whooshee_search(self, search_string, group=whoosh.qparser.OrGroup, whoosheer=None, match_substrings=True, limit=None, order_by_relevance=10): if (not whoosheer): entities = set() for cd in self.column_descriptions: entities.add(cd['...
def convert(color: 'Color', space: str) -> Tuple[('Space', Vector)]: chain = color._get_convert_chain(color._space, space) coords = alg.no_nans(color[:(- 1)]) last = color._space for (a, b, direction, adapt) in chain: if (direction and adapt): coords = color.chromatic_adaptation(a.WH...
def add_apks_to_per_app_repos(repodir, apks): apks_per_app = dict() for apk in apks: apk['per_app_dir'] = os.path.join(apk['packageName'], 'fdroid') apk['per_app_repo'] = os.path.join(apk['per_app_dir'], 'repo') apk['per_app_icons'] = os.path.join(apk['per_app_repo'], 'icons') ap...
def _parse_file(parser_class: Type[BaseParser], path: str) -> Tuple[(str, Dict[(str, List[int])])]: parser = parser_class() entries = defaultdict(list) with open(path) as handle: for position in parser.get_json_file_offsets(AnalysisOutput.from_handle(handle)): entries[position.callable]....
class initialize_config_dir(): def __init__(self, config_dir: str, job_name: str='app') -> None: from hydra import initialize_config_dir as real_initialize_config_dir message = 'hydra.experimental.initialize_config_dir() is no longer experimental. Use hydra.initialize_config_dir().' if versi...
class TableFeaturesStats(base_tests.SimpleProtocol): def runTest(self): logging.info('Sending table features stats request') stats = get_stats(self, ofp.message.table_features_stats_request()) logging.info('Received %d table features stats entries', len(stats)) for entry in stats: ...
def generate_logic_condition_class(base) -> Type[LOGICCLASS]: class BLogicCondition(base[LOGICCLASS]): _cnf def __init__(self, condition, tmp: bool=False): super().__init__(condition, tmp) def simplify_to_shortest(self, complexity_bound: int) -> BLogicCondition: if (s...
class OptionPlotoptionsTreegraphTooltipDatetimelabelformats(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): ...
.signal_handling def test_cleanup_second_try_succeeds_after_killing_worker_with_retry(fake_sqs_queue): logger = logging.getLogger(((__name__ + '.') + inspect.stack()[0][3])) logger.setLevel(logging.DEBUG) msg_body = randint(1111, 9998) queue = fake_sqs_queue queue.send_message(MessageBody=msg_body) ...
def show_speed(hash_file=None, session=None, wordlist=None, hash_mode=1000, speed_session=None, attack_mode=None, mask=None, rules=None, pot_path=None, brain=False, username=False, name=None, wordlist2=None): started = rq.registry.StartedJobRegistry(queue=redis_q) cur_list = started.get_job_ids() speed_job ...
def test_suggested_deprecated_model_config_run_path(tmpdir): runpath = 'simulations/realization-%d/iter-%d' suggested_path = 'simulations/realization-<IENS>/iter-<ITER>' mc = ModelConfig(num_realizations=1, runpath_format_string=runpath) assert (mc.runpath_format_string == suggested_path)
class Dissertation(GraphObject): __primarykey__ = 'title' title = Property() consists = RelatedTo('Dissertation') def __init__(self, title): self.title = title def find(self): dissertation = self.match(graph, self.title).first() return dissertation def register(self): ...
.parametrize('path, test_input, expected', [(None, {'accounts': [{'id': '10'}]}, TypeError), ([], {'accounts': [{'id': '10'}]}, TypeError), (['csp', 'accounts'], {'csp': {'accts': [{'id': '10'}]}}, ValueError)]) def test_load_with_invalid_path(path, test_input, expected): with pytest.raises(expected): acctl...
class SalesFormsPrefs(QuickbooksBaseObject): class_dict = {'DefaultTerms': Ref, 'SalesEmailBcc': EmailAddress, 'SalesEmailCc': EmailAddress} detail_dict = {'CustomField': PreferencesCustomFieldGroup} def __init__(self): super().__init__() self.ETransactionPaymentEnabled = False self....
class OptionSeriesColumnSonificationDefaultinstrumentoptionsMappingTremoloDepth(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...
def runserver(): manager = make_server_manager(PORTNUM, AUTHKEY) shared_job_q = manager.get_job_q() shared_result_q = manager.get_result_q() N = 999 nums = make_nums(N) chunksize = 43 for i in range(0, len(nums), chunksize): shared_job_q.put(nums[i:(i + chunksize)]) numresults = ...
def main(unused_argv): if (len(sys.argv) == 1): flags._global_parser.print_help() sys.exit(0) m = model.load_model(FLAGS.dragnn_spec, FLAGS.resource_path, FLAGS.checkpoint_filename, enable_tracing=FLAGS.enable_tracing, tf_master=FLAGS.tf_master) sess = m['session'] graph = m['graph'] ...
def generate_encoded_user_data(env='dev', region='us-east-1', generated=None, group_name='', pipeline_type='', canary=False): if (env in ['prod', 'prodp', 'prods']): (env_c, env_p, env_s) = ('prod', 'prodp', 'prods') else: (env_c, env_p, env_s) = (env, env, env) user_data = get_template(temp...
class OptionSeriesPyramid3dSonificationTracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): se...
class Raw(object): def __init__(self, stream): import termios import tty self.stream = stream self.fd = self.stream.fileno() def __enter__(self): self.original_stty = termios.tcgetattr(self.stream) tty.setcbreak(self.stream) def __exit__(self, type, value, tra...
def create_custom_rgb(gamut): cs = Color.CS_MAP[gamut] class RGB(type(Color.CS_MAP['srgb-linear'])): NAME = '-rgb-{}'.format(gamut) BASE = gamut GAMUT_CHECK = gamut CLIP_SPACE = None WHITE = cs.WHITE DYAMIC_RANGE = cs.DYNAMIC_RANGE INDEXES = cs.indexes() ...
def test_return_record_name_with_named_type_in_union(): schema = {'type': 'record', 'name': 'my_record', 'fields': [{'name': 'my_1st_union', 'type': [{'name': 'foo', 'type': 'record', 'fields': [{'name': 'some_field', 'type': 'int'}]}, {'name': 'bar', 'type': 'record', 'fields': [{'name': 'some_field', 'type': 'int...
def node_game_index_fields(wizard, status=None): if (not hasattr(wizard, 'game_index_listing')): wizard.game_index_listing = settings.GAME_INDEX_LISTING status_default = wizard.game_index_listing['game_status'] text = f''' What is the status of your game? - pre-alpha: a game in its very ...
class ZipReader(AbstractReader): useIndexFile = False def __init__(self, path, ignoreErrors=True): self._name = path self._members = {} self._pendingError = None try: self._members = self._readZipDirectory(fileObj=open(path, 'rb')) except Exception: ...
def test_django_ignore_transaction_urls(client, django_elasticapm_client): with override_settings(**middleware_setting(django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware'])): client.get('/no-error') assert (len(django_elasticapm_client.events[TRANSACTION]) == 1) django_...
class DataFactory(Factory): class Meta(): model = Data _id = Sequence((lambda n: n)) first_name = Faker('first_name') last_name = Faker('last_name') email = LazyAttribute(randon_email_factor) ultimo_pagamento = LazyFunction(randon_date_factor) status = FuzzyChoice(((['ativo', 'inativ...
def match_icmp_code(self, of_ports, priority=None): pkt_match = simple_icmp_packet(icmp_code=3) match = parse.packet_to_flow_match(pkt_match) self.assertTrue((match is not None), 'Could not generate flow match from pkt') match.wildcards = (((ofp.OFPFW_ALL ^ ofp.OFPFW_DL_TYPE) ^ ofp.OFPFW_NW_PROTO) ^ ofp...
def test_prep_steps(): df = load_df() df = prep_df(df) (train, test) = split_df(df) (X_train, y_train) = get_feats_and_labels(train) (X_test, y_test) = get_feats_and_labels(test) assert (X_train.shape == (712, 8)) assert (y_train.shape == (712,)) assert (X_test.shape == (179, 8)) ass...
class ThreadedDataLoader(): def __init__(self, model_class, processes=None, field_map={}, value_map={}, collision_field=None, collision_behavior='update', pre_row_function=None, post_row_function=None, post_process_function=None, loghandler='console'): self.logger = logging.getLogger(loghandler) sel...
class OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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...
class QRateLimitedExecutorRunnable(Logging): def __init__(self, future: Future, fn: Callable, args: Optional[Sequence[Any]]=None, kwargs: Optional[Dict[(str, Any)]]=None): self._future = future self._fn = fn self._args = () self._kwargs = {} if args: self._args = ...
('google.auth.compute_engine._metadata') def test_persist_ss(mock_gcs): default_img = Image(name='default', fqn='test', tag='tag') ss = SerializationSettings(project='proj1', domain='dom', version='version123', env=None, image_config=ImageConfig(default_image=default_img, images=[default_img])) ss_txt = ss....
class MerchantInformation(BaseModel): merchant_name: Optional[StrictStr] = None merchant_address: Optional[StrictStr] = None merchant_phone: Optional[StrictStr] = None merchant_url: Optional[StrictStr] = None merchant_siret: Optional[StrictStr] = None merchant_siren: Optional[StrictStr] = None ...
class bsn_table_set_buckets_size(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 61 def __init__(self, xid=None, table_id=None, buckets_size=None): if (xid != None): self.xid = xid else: self.xid = None if (table_id != None): ...
class Solution(): def maxCoins(self, iNums: List[int]) -> int: nums = (([1] + [i for i in iNums if (i > 0)]) + [1]) n = len(nums) dp = [([0] * n) for _ in range(n)] for k in range(2, n): for left in range(0, (n - k)): right = (left + k) for...
def extraRouteProgress(routes): bestGain = max(routes, key=(lambda route: route.gainCr)).gainCr worstGain = min(routes, key=(lambda route: route.gainCr)).gainCr if (bestGain != worstGain): gainText = '{:n}-{:n}cr gain'.format(worstGain, bestGain) else: gainText = '{:n}cr gain'.format(bes...
class OptionPlotoptionsHistogramSonificationTracksMappingTremoloSpeed(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
class UserDataDumper(object): def __init__(self, user): self.user = user def dumps(self, pretty=False): app.logger.info("Dumping all user data for '%s'", self.user.name) if pretty: return json.dumps(self.data, indent=2) return json.dumps(self.data) def data(self):...
def __create_playlist_context_menu(): smi = menu.simple_menu_item sep = menu.simple_separator items = [] items.append(menuitems.EnqueueMenuItem('enqueue', [])) items.append(SPATMenuItem('toggle-spat', [items[(- 1)].name])) def rating_get_tracks_func(menuobj, parent, context): return [row...
class CreditCardExpires(FormValidator): validate_partial_form = True cc_expires_month_field = 'ccExpiresMonth' cc_expires_year_field = 'ccExpiresYear' __unpackargs__ = ('cc_expires_month_field', 'cc_expires_year_field') datetime_module = None messages = dict(notANumber=_('Please enter numbers on...
def _create_ofp_msg_ev_class(msg_cls): name = _ofp_msg_name_to_ev_name(msg_cls.__name__) if (name in _OFP_MSG_EVENTS): return cls = type(name, (EventOFPMsgBase,), dict(__init__=(lambda self, msg: super(self.__class__, self).__init__(msg)))) globals()[name] = cls _OFP_MSG_EVENTS[name] = cls
class _ErtDocumentation(SphinxDirective): has_content = True _CATEGORY_DEFAULT = 'other' _SOURCE_PACKAGE_DEFAULT = 'PACKAGE NOT PROVIDED' _DESCRIPTION_DEFAULT = '' _CONFIG_FILE_DEFAULT = 'No config file provided' _EXAMPLES_DEFAULT = '' _PARSER_DEFAULT = None def _divide_into_categories(j...
def arrays_to_strings(measure_json): converted = {} fields_to_convert = ['title', 'description', 'why_it_matters', 'numerator_columns', 'numerator_where', 'denominator_columns', 'denominator_where'] for (k, v) in measure_json.items(): if ((k in fields_to_convert) and isinstance(v, list)): ...
class OptionSeriesTreegraphSonificationDefaultinstrumentoptionsActivewhen(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, ...
class FigureModelTrainingDataGenerator(AbstractDocumentModelTrainingDataGenerator): def get_main_model(self, document_context: TrainingDataDocumentContext) -> Model: return document_context.fulltext_models.figure_model def iter_model_layout_documents(self, layout_document: LayoutDocument, document_conte...
class Solution(): def findMaximumXOR(self, nums): root = TrieNode() for num in nums: node = root for j in range(31, (- 1), (- 1)): tmp = (num & (1 << j)) if tmp: if (not node.one): node.one = TrieNode...
class DummyPolicyWrapper(Policy, TorchModel): def __init__(self, torch_policy: TorchPolicy): self.torch_policy = torch_policy super().__init__(device=torch_policy.device) (Policy) def seed(self, seed: int) -> None: (Policy) def needs_state(self) -> bool: return False (Pol...
_register_parser _set_msg_type(ofproto.OFPT_FLOW_MOD) class OFPFlowMod(MsgBase): def __init__(self, datapath, cookie=0, cookie_mask=0, table_id=0, command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=0, buffer_id=ofproto.OFP_NO_BUFFER, out_port=0, out_group=0, flags=0, match=None, instructions=None):...
class OutdatedChrootMessage(Message): def __init__(self, copr_chroots): self.subject = '[Copr] upcoming deletion of outdated chroots in your projects' self.text = "You have been notified because you are an admin of projects, that have some builds in outdated chroots\n\nAccording to the 'Copr outdate...
class Item(metaclass=ItemType): def parse(cls, html: str): if cls._list: result = HTMLParsing(html).list(cls._selector, cls.__fields__) result = [cls._clean(item) for item in result] else: result = HTMLParsing(html).detail(cls.__fields__) result = cls....
class FirewallTransaction(): def __init__(self, fw): self.fw = fw self.rules = {} self.pre_funcs = [] self.post_funcs = [] self.fail_funcs = [] self.modules = [] def clear(self): self.rules.clear() del self.pre_funcs[:] del self.post_funcs[...
def validate_EIP712Domain_schema(structured_data): if ('EIP712Domain' not in structured_data['types']): raise ValidationError('`EIP712Domain struct` not found in types attribute') EIP712Domain_data = structured_data['types']['EIP712Domain'] header_fields = used_header_fields(EIP712Domain_data) i...
('aea.cli.registry.fetch.open_file', mock.mock_open()) ('aea.cli.utils.decorators._cast_ctx') ('aea.cli.registry.fetch.PublicId', PublicIdMock) ('aea.cli.registry.fetch.os.rename') ('aea.cli.registry.fetch.os.makedirs') ('aea.cli.registry.fetch.try_to_load_agent_config') ('aea.cli.registry.fetch.download_file', return_...
class TestsUtilsTest(LogCaptureTestCase): def testmbasename(self): self.assertEqual(mbasename('sample.py'), 'sample') self.assertEqual(mbasename('/long/path/sample.py'), 'sample') self.assertEqual(mbasename('/long/path/__init__.py'), 'path.__init__') self.assertEqual(mbasename('/long...
class NotificationReceiver(object): SUPPORTED_PDU_TYPES = (v1.TrapPDU.tagSet, v2c.SNMPv2TrapPDU.tagSet, v2c.InformRequestPDU.tagSet) def __init__(self, snmpEngine, cbFun, cbCtx=None): snmpEngine.msgAndPduDsp.registerContextEngineId(null, self.SUPPORTED_PDU_TYPES, self.processPdu) self.__snmpTrap...
def migrate_cluster(cluster): for (old, new) in [('_user_key_public', 'user_key_public'), ('_user_key_private', 'user_key_private'), ('_user_key_name', 'user_key_name')]: if hasattr(cluster, old): setattr(cluster, new, getattr(cluster, old)) delattr(cluster, old) for (kind, nodes...
def extractYeboisnovelsWordpressCom(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_ty...
.parametrize(('words', 'score_expected'), [((' 85.0), (('www.github,com',), 100.0), (('some random words',), 0.0)]) def test_url_magic_score(ocr_result, words, score_expected): ocr_result.words = [{'text': w} for w in words] magic = UrlMagic() score = magic.score(ocr_result) assert (score == score_expec...
class OptionSeriesDumbbellSonificationDefaultspeechoptions(Options): def activeWhen(self) -> 'OptionSeriesDumbbellSonificationDefaultspeechoptionsActivewhen': return self._config_sub_data('activeWhen', OptionSeriesDumbbellSonificationDefaultspeechoptionsActivewhen) def language(self): return sel...
def check_updates_expected(app): if ((app.get('NoSourceSince') or (app.get('ArchivePolicy') == 0)) and (not all(((app.get(key, 'None') == 'None') for key in ('AutoUpdateMode', 'UpdateCheckMode'))))): (yield _('App has NoSourceSince or ArchivePolicy "0 versions" or 0 but AutoUpdateMode or UpdateCheckMode are...
def select_outgroups(target, n2content, splitterconf): name2dist = {'min': _min, 'max': _max, 'mean': _mean, 'median': _median} out_topodist = tobool(splitterconf['_outgroup_topology_dist']) optimal_out_size = int(splitterconf['_max_outgroup_size']) out_min_support = float(splitterconf['_outgroup_min_su...
def _get_apk_icons_src(apkfile, icon_name): icons_src = dict() density_re = re.compile('^res/(.*)/{}\\.png$'.format(icon_name)) with zipfile.ZipFile(apkfile) as zf: for filename in zf.namelist(): m = density_re.match(filename) if m: folder = m.group(1).split('...
class hw_at_t0(object): def uOfXT(self, X, t): hTilde = solitary_wave(X[0], 0) h = max((hTilde - bathymetry_function(X)), 0.0) hTildePrime = ((((- 2.0) * z) * hTilde) * np.tanh((z * ((X[0] - x0) - (c * t))))) hw = ((- (h ** 2)) * (((c * h0) * hTildePrime) / ((h0 + hTilde) ** 2))) ...
class OptionSeriesDumbbellLabel(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): self._...
class FailTicket(Ticket): def __init__(self, ip=None, time=None, matches=None, data={}, ticket=None): self._firstTime = None self._retry = 1 Ticket.__init__(self, ip, time, matches, data, ticket) if (not isinstance(ticket, FailTicket)): self._firstTime = (time if (time is...
_request def after_request_func(response): origin = request.headers.get('Origin') if (request.method == 'OPTIONS'): response = make_response() response.headers.add('Access-Control-Allow-Credentials', 'true') response.headers.add('Access-Control-Allow-Headers', 'Content-Type') res...
def iter_entities_including_other(seq: List[str]) -> Iterable[Tuple[(str, int, int)]]: prev_tag = 'O' prev_start = 0 for (index, prefixed_tag) in enumerate(seq): (prefix, tag) = get_split_prefix_label(prefixed_tag) if ((prefix == 'B') or (tag != prev_tag)): if (prev_start < index...
class bad_request_error_msg(error_msg): version = 1 type = 1 err_type = 1 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: s...
class Environment(): def __init__(self, target: str, project_dir: str): self.dbt_runner = dbt_project.get_dbt_runner(target, project_dir) def clear(self): self.dbt_runner.run_operation('elementary_tests.clear_env') def init(self): self.dbt_runner.run(selector='init') self.dbt...
class OptionPlotoptionsVariablepieAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str): ...
('ecs_deploy.ecs.logger') (EcsClient, '__init__') def test_is_not_deployed_with_failed_tasks(client, logger, service_with_failed_tasks): client.list_tasks.return_value = RESPONSE_LIST_TASKS_0 action = EcsAction(client, CLUSTER_NAME, SERVICE_NAME) action.is_deployed(service_with_failed_tasks) logger.warn...
class Command(BaseCommand): help = _('Connect with client as subscriber, for real time update proposed') client_db = None create_if_not_exist = False use_update = False def add_arguments(self, parser): parser.add_argument('topic', action='store', type=str, default=None, help=_('Subcribe topi...
class AmazonImageApi(ImageInterface): def image__object_detection(self, file: str, model: str=None, file_url: str='') -> ResponseType[ObjectDetectionDataClass]: with open(file, 'rb') as file_: file_content = file_.read() payload = {'Image': {'Bytes': file_content}, 'MinConfidence': 70} ...
def load_mapping(name, filename, mapping_is_raw): raw_regexp = re.compile(b'^([^=]+)[ ]*=[ ]*(.+)$') string_regexp = b'"(((\\.)|(\\")|[^"])*)"' quoted_regexp = re.compile(((((b'^' + string_regexp) + b'[ ]*=[ ]*') + string_regexp) + b'$')) def parse_raw_line(line): m = raw_regexp.match(line) ...
class ILAgent(nn.Module): def __init__(self, model: nn.Module, num_envs: int, num_mini_batch: int, lr: Optional[float]=None, encoder_lr: Optional[float]=None, eps: Optional[float]=None, max_grad_norm: Optional[float]=None, wd: Optional[float]=None) -> None: super().__init__() self.model = model ...
def linear_poisson(solver_parameters, mesh_num, porder): mesh = UnitSquareMesh(mesh_num, mesh_num) V = FunctionSpace(mesh, 'CG', porder) u = TrialFunction(V) v = TestFunction(V) f = Function(V) (x, y) = SpatialCoordinate(mesh) f.interpolate((((((- 8.0) * pi) * pi) * cos(((x * pi) * 2))) * co...
def all_are_valid_links(links): for link in links: try: res = requests.get(link) res.raise_for_status() return True except: st.warning(f'''The following link does not respond. Please check if it is correct and try again. {link}''', i...
.django_db def test_spending_by_transaction_count(monkeypatch, transaction_type_data, elasticsearch_transaction_index): setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index) request_data = {'filters': {'keywords': ['pop tart']}} results = spending_by_transaction_count(request_data) expe...
def action_to_str(act): action_type = act.cls_action_type if (action_type == ofproto_v1_2.OFPAT_OUTPUT): port = UTIL.ofp_port_to_user(act.port) buf = ('OUTPUT:' + str(port)) elif (action_type == ofproto_v1_2.OFPAT_COPY_TTL_OUT): buf = 'COPY_TTL_OUT' elif (action_type == ofproto_v...
.parametrize('uri, expected', (('eth://block/byhash/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080?score=11', ('0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080', 78, 11)), ('eth://block/byhash/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080?score=1,1', ('0x113f0...
class RuleEngineTest(ForsetiTestCase): def setUp(self): project0 = fre.resource_util.create_resource(resource_id='test_project', resource_type='project') project1 = fre.resource_util.create_resource(resource_id='project1', resource_type='project') project2 = fre.resource_util.create_resource...
_grad() def demo_clip_features(text_query: str) -> None: device = (torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')) clip_embs = extract_clip_features(image_paths, device) clip_embs /= clip_embs.norm(dim=(- 1), keepdim=True) (model, _) = clip.load(CLIPArgs.model_name, device=de...
class OptionPlotoptionsStreamgraphStatesSelect(Options): def animation(self) -> 'OptionPlotoptionsStreamgraphStatesSelectAnimation': return self._config_sub_data('animation', OptionPlotoptionsStreamgraphStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self,...
class OptionSeriesPackedbubbleSonificationDefaultinstrumentoptionsPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, fl...
.parametrize('val, expected', (('0', 0), ('-1', (- 1)), ('255', 255), ('0x0', ValueError), ('0x1', ValueError), ('1.1', ValueError), ('a', ValueError))) def test_to_int_text(val, expected): if isinstance(expected, type): with pytest.raises(expected): to_int(text=val) else: assert (to...
class ParanoidSyncHandler(THBEventHandler): interested = ['action_after'] def handle(self, evt_type, arg): g = self.game if hasattr(g, 'players'): me = [len(ch.cards) for ch in g.players] svr = sync_primitive(me, g.players) assert (me == svr), (me, svr) ...
def data(curve, surface, request): if (request.param == 'univariate'): (x, y) = curve xi = np.linspace(x[0], x[(- 1)], 150) return (x, y, xi, 0.85, CubicSmoothingSpline) elif (request.param == 'ndgrid'): (x, y) = surface return (x, y, x, [0.85, 0.85], NdGridCubicSmoothing...
def _get_unique_build_json(output_evm: Dict, contract_node: Any, stmt_nodes: Dict, branch_nodes: Dict, has_fallback: bool) -> Dict: paths = {str(i.contract_id): i.parent().absolutePath for i in ([contract_node] + contract_node.dependencies)} bytecode = _format_link_references(output_evm) without_metadata = ...
def _merge_splits(splits: Iterable[str], separator: str, chunk_size: int, chunk_overlap: int, length_function: Callable[([str], int)]) -> List[str]: separator_len = length_function(separator) docs = [] current_doc: List[str] = [] total = 0 for d in splits: _len = length_function(d) i...
class DispatchProxyServiceServicer(object): def GetDispatch(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetAttr(self, request, context): context.se...
class OptionZaxisPlotbandsLabel(Options): def align(self): return self._config_get('center') def align(self, text: str): self._config(text, js_type=False) def rotation(self): return self._config_get(0) def rotation(self, num: float): self._config(num, js_type=False) d...
def prepare_timestamp_micros(data, schema): if isinstance(data, datetime.datetime): if (data.tzinfo is not None): delta = (data - epoch) return (((((delta.days * 24) * 3600) + delta.seconds) * MCS_PER_SECOND) + delta.microseconds) if is_windows: delta = (data - ep...