code
stringlengths
281
23.7M
def test_prepare_transaction_replacement_not_higher_gas_price_raises(w3): current_transaction = SIMPLE_CURRENT_TRANSACTION new_transaction = {'value': 1, 'gasPrice': 5} with pytest.raises(ValueError): prepare_replacement_transaction(w3, current_transaction, new_transaction) new_transaction['gasP...
def benchmark_only_pipeline(): test_pipeline_name = 'benchmark-only' original = racecontrol.pipelines[test_pipeline_name] pipeline = racecontrol.Pipeline(test_pipeline_name, 'Pipeline intended for unit-testing', mock.Mock()) (yield pipeline) racecontrol.pipelines[test_pipeline_name] = original
class StockFinanceReportEventSpider(scrapy.Spider): name = 'stock_finance_report_event' custom_settings = {'DOWNLOAD_DELAY': 2, 'CONCURRENT_REQUESTS_PER_DOMAIN': 8, 'SPIDER_MIDDLEWARES': {'fooltrader.middlewares.FoolErrorMiddleware': 1000}} def start_requests(self): security_item = self.settings.get...
def extractMarcell13BlogWordpressCom(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_t...
class OptionPlotoptionsFunnelSonificationDefaultspeechoptionsPointgrouping(Options): def algorithm(self): return self._config_get('last') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: boo...
def erase_flash(esp, args): if ((not args.force) and (esp.CHIP_NAME != 'ESP8266') and (not esp.secure_download_mode)): if (esp.get_flash_encryption_enabled() or esp.get_secure_boot_enabled()): raise FatalError('Active security features detected, erasing flash is disabled as a safety measure. Use...
('function_length') def function_length(node): assert isinstance(node, (Function_Definition, Script_File)) if isinstance(node, Script_File): return None elif node.t_end: return ((node.t_end.location.line - node.t_fun.location.line) + 1) else: n_cu = node.n_parent if (not ...
_ocx_not_available _not_currently_in_session def test_GetCodeListByConditionAsStream(entrypoint): entrypoint.EnsureConditionLoaded() conditions = entrypoint.GetConditionNameListAsList() condition_name = ' ' assert (condition_name in [item[1] for item in conditions]) stream = entrypoint.GetCodeListBy...
def run(): segmk = Segmaker('design.bits') print('Loading tags') f = open('params.jl', 'r') f.readline() for l in f: j = json.loads(l) ps = j['params'] assert (j['module'] == 'my_XADC') site = verilog.unquote(ps['LOC']) bus_tags(segmk, ps, site) segmk.comp...
def send_verification_code_to_user(db: Session, request: (ConsentRequest | PrivacyRequest), to_identity: (Identity | None)) -> str: config_proxy = ConfigProxy(db) verification_code = generate_id_verification_code() request.cache_identity_verification_code(verification_code) messaging_action_type = Messa...
def downgrade(): with op.batch_alter_table('Budgets', schema=None) as batch_op: batch_op.drop_column('parent_id') with op.batch_alter_table('BudgetEntries', schema=None) as batch_op: batch_op.drop_column('unit') batch_op.drop_column('realized_total') batch_op.drop_column('price')...
(st.floats(allow_nan=False, allow_infinity=False), valid_derrf_parameters()) def test_that_derrf_corresponds_scaled_binned_normal_cdf(x, arg): (_steps, _min, _max, _skew, _width) = arg q_values = np.linspace(start=0, stop=1, num=_steps) q_checks = np.linspace(start=0, stop=1, num=(_steps + 1))[1:] p = n...
def init_embedded(level, sentry_dsn, release): patch_gevent_hub_print_exception() root = logging.getLogger() root.setLevel(0) hdlr: Any logging.getLogger('sentry.errors').setLevel(1000) if sentry_dsn: hdlr = SentryHandler(raven.Client(sentry_dsn, transport=GeventedHTTPTransport, release=...
class WafRuleRevisionAttributes(ModelNormal): allowed_values = {('state',): {'LATEST': 'latest', 'OUTDATED': 'outdated'}} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def...
def extractTaxingcorn117StranslationsCom(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 parse_ip_address_and_port(addr, default_port=22): for regexp in _IP_ADDRESS_RE: match = regexp.search(addr) if (not match): continue ip_addr = netaddr.IPAddress(match.group('ip_addr')) try: port = match.group('port') except IndexError: ...
class DoraConfig(): dir: Path = Path('./outputs') exclude: tp.List[str] = field(default_factory=list) git_save: bool = False shared: tp.Optional[Path] = None grid_package: tp.Optional[str] = None history: str = 'history.json' xps: str = 'xps' shep: ShepConfig = field(default_factory=Shep...
class PresidentialCoverage(db.Model): __table_args__ = {'schema': 'public'} __tablename__ = 'ofec_presidential_coverage_date_vw' idx = db.Column(db.Integer, primary_key=True) candidate_id = db.Column(db.String, doc=docs.CANDIDATE_ID_PRESIDENTIAL) coverage_end_date = db.Column(db.DateTime, doc=docs.C...
class TaskService(): def get(pk: str) -> (AsyncResult | None): try: result = celery_app.AsyncResult(pk) except (BackendGetMetaError, NotRegistered): raise NotFoundError(msg='') if result.failed(): return None return result def gets() -> dict: ...
class CapabilityHeader(QHeaderView): description_requested_signal = Signal(str, str) def __init__(self, orientation, parent=None): QHeaderView.__init__(self, orientation, parent) self._data = [] if (orientation == Qt.Horizontal): self.setDefaultAlignment((Qt.AlignHCenter | Qt...
class OptionSeriesVariwideDatalabels(Options): def align(self): return self._config_get('undefined') def align(self, text: str): self._config(text, js_type=False) def allowOverlap(self): return self._config_get(False) def allowOverlap(self, flag: bool): self._config(flag,...
def extractMionlineWordpressCom(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) ...
class Demo(lg.Graph): WS_SERVER_NODE: WSAPIServerNode SERIALIZER: Serializer NOISE_GENERATOR: NoiseGenerator ROLLING_AVERAGER: RollingAverager AMPLIFIER: Amplifier ATTENUATOR: Attenuator def set_topology(self, topology: SerializedGraph, sub_pub_map: Dict) -> None: self._topology = to...
def extractWhitehemlocktranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Male God is Chasing My Brother', 'Male God is Chasing My Brother', 'translated')...
(('reconf' in cfgdiff.supported_formats), 'requires reconfigure') class ReconfigureDiffTestCase(CfgDiffTestCase): def setUp(self): self.configs = __import__('reconfigure.configs', fromlist=['reconfigure']) def test_reconf_same(self): self._test_same(cfgdiff.ReconfigureDiff, './tests/test_same_1-...
def render() -> None: global FACE_SWAPPER_MODEL_DROPDOWN global FACE_ENHANCER_MODEL_DROPDOWN global FACE_ENHANCER_BLEND_SLIDER global FRAME_ENHANCER_MODEL_DROPDOWN global FRAME_ENHANCER_BLEND_SLIDER global FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP FACE_SWAPPER_MODEL_DROPDOWN = gradio.Dropdown(label...
_control_type class ControlFormatI(stringify.StringifyMixin): TYPE = 0 _PACK_STR = '!H' _PACK_LEN = struct.calcsize(_PACK_STR) def __init__(self, send_sequence_number=0, pf_bit=0, receive_sequence_number=0): super(ControlFormatI, self).__init__() self.send_sequence_number = send_sequence...
def tex_Cases(head, args, **kwargs): in_small = kwargs.get('in_small', False) s = '\\begin{cases} ' displaystyle = False for arg in args: assert (arg.head() == Tuple) (v, c) = arg.args() v = v.latex(in_small=in_small) if (c == Otherwise): c = '\\text{otherwise...
def setup_temp_env(tmp_path: Path): cfg_file = (tmp_path / 'jobs.json') results_repo_root = (tmp_path / 'ideas') github_target = _utils.GitHubTarget.from_url(IDEAS_GIT_URL) github_target.ensure_local(str(results_repo_root)) content = json.loads(CONFIG_FILENAME.read_text()) content['data_dir'] = ...
class OptionSeriesColumnrangeSonificationDefaultspeechoptionsMappingPitch(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('undefined') def mapTo(self, tex...
class MyBuddySocket(MyBuddyCommandGenerator): _write = write _read = read def __init__(self, ip, netport=9000): super(MyBuddySocket, self).__init__() self.calibration_parameters = calibration_parameters self.SERVER_IP = ip self.SERVER_PORT = netport self.rasp = False ...
.parametrize('plugin_name', KNOWN_PLUGINS) def test_smoke_extract(plugin_name): codes = extract(plugin_name) assert codes for (code, msg) in codes.items(): assert (type(code) is str), 'bad code type' assert (type(msg) is str), 'bad message type' assert code[0].isalpha(), 'code must s...
def test_gso_coherence_gram_matrix(): EPSILON = 0.0001 for (m, n) in dimensions: for int_type in int_types: if ((m > 20) and (int_type == 'long')): continue A = make_integer_matrix(m, n, int_type=int_type).transpose() G = tools.compute_gram(A) ...
.django_db def test_RkAdjustRanking(Q, auth_header): import system.models system.models.Setting(key='ranking-season', value='1').save() from player.tests import PlayerFactory from game.tests import GameFactory PlayerFactory.create() PlayerFactory.create() g = GameFactory.create() return ...
def visualize_tokens(doc: spacy.tokens.Doc, *, attrs: List[str]=TOKEN_ATTRS, title: Optional[str]='Token attributes', key: Optional[str]=None) -> None: if title: st.header(title) exp = st.expander('Select token attributes') selected = exp.multiselect('Token attributes', options=attrs, default=list(a...
def select_jobs(jobs: ToJobsType, criteria: Optional[Union[(str, Sequence[str])]]=None) -> Iterator[_job.Job]: if isinstance(jobs, Jobs): jobs = list(jobs.iter_all()) if (not criteria): (yield from jobs) return if isinstance(criteria, str): criteria = [criteria] else: ...
class VirtualRoot(InputDefault): def is_virtual(self) -> bool: return True def is_self(self) -> bool: return False def is_optional(self) -> bool: raise NotImplementedError() def get_group_path(self) -> str: raise NotImplementedError() def get_config_path(self) -> str:...
class Navs(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32, verbose_name='') abstract = models.CharField(max_length=128, verbose_name='', null=True) href = models.URLField(verbose_name='') icon_href = models.URLField(verbose_name='', help_text='', null=...
() ('--config', default='configs/exp_cn_hubert_soft_finetune.py') ('--checkpoint', default='logs/DiffSVC/oonzyobz/checkpoints/epoch=1249-step=5000-valid_loss=0.31.ckpt') def main(config: str, checkpoint: str): Path('exported').mkdir(exist_ok=True) device = 'cpu' config = Config.fromfile(config) model = ...
def data_over_ftp(server, fname): package_path = str(((Path(__file__).parent / 'data') / fname)) server_path = os.path.join(server.anon_root, fname) try: shutil.copyfile(package_path, server_path) url = f'ftp://localhost/{fname}' (yield url) finally: if os.path.exists(ser...
def get_line_context(line: str) -> (tuple[(str, None)] | tuple[(str, str)]): (last_level, sections) = get_paren_level(line) lev1_end = sections[(- 1)].end test_match = read_var_def(line) if (test_match is not None): if (test_match[0] == 'var'): if ((test_match[1].var_names is None) a...
def try_update(latest_version: str): success = update(latest_version, 'py') if success: return success = update(latest_version, 'python3') if success: return success = update(latest_version, 'python') if success: return helper.colored_text('Update failed\nYou may need...
class PlanetStats(Base): __tablename__ = 'planetstats' planet_stats_id = Column(Integer, primary_key=True) countrydata_id = Column(ForeignKey(CountryData.country_data_id), index=True) planet_id = Column(ForeignKey(Planet.planet_id)) pop_count = Column(Integer) happiness = Column(Float) power...
class OptionPlotoptionsVennSonificationDefaultinstrumentoptionsMappingPitch(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('y') def mapTo(self, text: str...
class TraceParent(object): __slots__ = ('version', 'trace_id', 'span_id', 'trace_options', 'tracestate', 'tracestate_dict', 'is_legacy') def __init__(self, version: int, trace_id: str, span_id: str, trace_options: 'TracingOptions', tracestate: Optional[str]=None, is_legacy: bool=False) -> None: self.ver...
def test_finding_functions_with_literals(): program = cleandoc("\n mdl = ref('model_a')\n ref('model_b')\n ref('package', 'model_c')\n src = source('db', 'table_a')\n source('db', 'table_b')\n ") module = ast.parse(program) results = generate_dbt_dependencies(module...
def main(page: ft.Page): page.title = 'Autocomplete search names' def textbox_changed(string): str_lower = string.control.value.lower() list_view.controls = ([list_items.get(n) for n in NAMES if (str_lower in n.lower())] if str_lower else []) page.update() list_items = {name: ft.List...
(name='api.node.image.tasks.node_img_sources_sync', base=InternalTask) _lock(timeout=3600, wait_for_release=True) def node_img_sources_sync(task_id, sender, **kwargs): new_img_sources = ImageVm().sources for node in Node.all(): if (not node.is_online()): logger.warn('Excluding node %s from u...
def summary_by_id(event_id): sales_summary = Order.query.filter_by(event_id=event_id).with_entities(Order.status, func.sum(Order.amount)).group_by(Order.status).all() tickets_summary = TicketHolder.query.join(Order).filter((Order.event_id == event_id)).with_entities(Order.status, func.count()).group_by(Order.st...
class OptionPlotoptionsDependencywheelSonificationDefaultinstrumentoptionsMappingNoteduration(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 ma...
class FaucetRouterConfigReloadTest(FaucetConfigReloadTestBase): def test_router_config_reload(self): conf = self._get_faucet_conf() conf['routers'] = {'router-1': {'vlans': [100, 200]}} self.reload_conf(conf, self.faucet_config_path, restart=True, cold_start=True, change_expected=True)
def _run_timeit(func, number): gc.collect() manager = getattr(func, '_benchmark_manager', None) try: if (manager is not None): with manager(number) as ctx: return timeit.Timer((lambda : func(ctx))).timeit(number=number) else: return timeit.Timer(func)....
class FmtNumber(): def __init__(self, page: primitives.PageModel, selector: str, value): (self.page, self._val) = (page, value) self.selector = selector def toFixed(self, value: Optional[int]=None): if (value is None): return JsObjects.JsObjects.get(('%s = %s.toFixed()' % (se...
def _replace_contraction_with_cast(instruction: Instruction): for expr in _find_cast_subexpressions(instruction): if expr.contraction: expr.contraction = False if (_is_cast(expr.operand) and (expr.operand.type == expr.type)): instruction.substitute(expr, expr.operand)
('config_name,overrides,expected', [param('legacy_override_hydra2', [], DefaultsTreeNode(node=VirtualRoot(), children=[DefaultsTreeNode(node=ConfigDefault(path='hydra/config'), children=[GroupDefault(group='help', value='custom1'), GroupDefault(group='output', value='disabled'), ConfigDefault(path='_self_')]), Defaults...
def upgrade(): op.create_table('classified_traces', sa.Column('classified_at', sa.TIMESTAMP, server_default=sa.func.now()), sa.Column('transaction_hash', sa.String(66), nullable=False), sa.Column('block_number', sa.Numeric, nullable=False), sa.Column('classification', sa.String(256), nullable=False), sa.Column('tra...
class OFPGroupStats(StringifyMixin): def __init__(self, length=None, group_id=None, ref_count=None, packet_count=None, byte_count=None, duration_sec=None, duration_nsec=None, bucket_stats=None): super(OFPGroupStats, self).__init__() self.length = length self.group_id = group_id self....
def main(): parser = OptionParser() parser.add_option('-v', '--verbosity', action='store', dest='verbosity', default='1', type='choice', choices=['0', '1', '2', '3'], help='Verbosity level; 0=minimal output, 1=normal output, 2=all output') parser.add_option('--noinput', action='store_false', dest='interacti...
('resourceclosing_container') def test_closing_resource_bypass_marker_injection(): resourceclosing.Service.reset_counter() result_1 = resourceclosing.test_function(service=Closing[Provide['service']]) assert isinstance(result_1, resourceclosing.Service) assert (result_1.init_counter == 1) assert (re...
class InfosReceiptParserDataClass(BaseModel): invoice_number: Optional[StrictStr] = None invoice_total: Optional[float] = None invoice_subtotal: Optional[float] = None barcodes: Sequence[BarCode] = Field(default_factory=list) category: Optional[StrictStr] = None date: Optional[StrictStr] = None ...
def to_file(self, pfile, fformat='roff', name=None, append=False, dtype=None, fmt=None): logger.info('Export property to file %s as %s', pfile, fformat) fobj = xtgeo._XTGeoFile(pfile, mode='rb') if (not fobj.memstream): fobj.check_folder(raiseerror=OSError) if (name is None): name = self...
class TransactionReceipt(): block_number = None contract_address: Optional[str] = None contract_name = None fn_name = None gas_used = None logs: Optional[List] = None nonce = None sender = None txid: str txindex = None type: int def __init__(self, txid: Union[(str, bytes)...
class FixUncleanShutdownComponent(Application): logger = logging.getLogger('trinity.components.fix_unclean_shutdown.FixUncleanShutdown') def configure_parser(cls, arg_parser: ArgumentParser, subparser: _SubParsersAction) -> None: attach_parser = subparser.add_parser('fix-unclean-shutdown', help='close a...
class OptionPlotoptionsHeatmapSonificationTracksMappingNoteduration(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 InputShapeBaseInformationError(ErsiliaError): def __init__(self): self.message = 'Wrong Ersilia input shape' self.hints = 'Only one of the following shapes is allowed: {}'.format(', '.join(_read_default_fields('Input Shape'))) ErsiliaError.__init__(self, self.message, self.hints)
class OptionSeriesOrganizationSonificationContexttracksMappingLowpassResonance(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text:...
class TestGenerateProtocolFailsWhenDirectoryAlreadyExists(): def setup_class(cls): cls.runner = CliRunner() cls.agent_name = 'myagent' cls.protocol_name = 't_protocol' cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() dir_path = Path('packages') tmp_dir = (cls....
def extractShinSekaiYori(item): chStr = '' for tag in item['tags']: if ('chapter' in tag.lower()): chStr = ((chStr + ' ') + tag) chStr += (' ' + item['title']) (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(chStr) if ((not (chp or vol)) or ('preview' in item['title'...
class Command(BaseRevisionCommand): help = 'Creates initial revisions for a given app [and model].' def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument('--comment', action='store', default='Initial version.', help="Specify the comment to add to the revisions. Defau...
def _get_active_updates(request): query = models.Update.query update_status = [models.UpdateStatus.pending, models.UpdateStatus.testing] query = query.filter(sa.sql.or_(*[(models.Update.status == s) for s in update_status])) user = models.User.get(request.identity.name) query = query.filter((models....
_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) check_topic_owner(topic, request.user) if (request.method != 'POST'): form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False...
def _run_make_cmds(cmds, timeout, build_dir, allow_cache=True): _LOGGER.debug(f'make cmds={cmds!r}') if allow_cache: (cached_results_available, store_cache_key) = build_cache.BUILD_CACHE.retrieve_build_cache(cmds, build_dir) else: (cached_results_available, store_cache_key) = (False, None) ...
_processor def context_get_head_injects(): async def get_head_injects(): for plugin in PluginHandler.get_loaded_plugin_values(): if plugin.meta.get_injected_head: (yield (await plugin.meta.get_injected_head())) return dict(get_head_injects=get_head_injects)
class OptionSonificationGlobaltracksMappingPan(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._config(text...
class System(Base, FidesBase): __tablename__ = 'ctl_systems' meta = Column(JSON) fidesctl_meta = Column(JSON) system_type = Column(String) administrating_department = Column(String) egress = Column(JSON) ingress = Column(JSON) vendor_id = Column(String) previous_vendor_id = Column(St...
class IGUI(Interface): busy = Bool(False) started = Bool(False) state_location = Str() def __init__(self, splash_screen=None): def allow_interrupt(): def invoke_after(cls, millisecs, callable, *args, **kw): def invoke_later(cls, callable, *args, **kw): def set_trait_after(cls, millisecs,...
def test_onnx_pytorch(): def train() -> Annotated[(PyTorch2ONNX, PyTorch2ONNXConfig(args=torch.randn(1, 1, 224, 224, requires_grad=True), export_params=True, opset_version=10, do_constant_folding=True, input_names=['input'], output_names=['output'], dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_siz...
def parse_timedelta(s: Optional[str]) -> datetime.timedelta: s = (s or DEFAULT_EVENT_DURATION) try: parts = s.split(':') hours = int(parts[0]) minutes = (int(parts[1]) if (len(parts) > 1) else 0) seconds = (int(parts[2]) if (len(parts) > 2) else 0) except: raise Value...
class OwnerTestSerializer(ExtensionsModelSerializer): class Meta(): model = test_models.Owner fields = ('id', 'name') expandable_fields = dict(organization=OrganizationTestSerializer, cars=dict(serializer=SkuTestSerializer, many=True), identity=dict(serializer=OwnerIdentityTestSerializer, id...
class OptionPlotoptionsBarDragdropDraghandle(Options): def className(self): return self._config_get('highcharts-drag-handle') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('#fff') def color(self, text: str): sel...
class ScannerIndexTest(ForsetiTestCase): def setUp(self): ForsetiTestCase.setUp(self) (self.engine, self.dbfile) = create_test_engine_with_file() scanner_dao.ScannerIndex.__table__.create(bind=self.engine) session_maker = sessionmaker() self.session = session_maker(bind=self....
def test_libp2pconnection_mixed_ip_address(): assert (_ip_all_private_or_all_public([]) is True) assert (_ip_all_private_or_all_public(['127.0.0.1', '127.0.0.1']) is True) assert (_ip_all_private_or_all_public(['localhost', '127.0.0.1']) is True) assert (_ip_all_private_or_all_public(['10.0.0.1', '127.0...
class OptionSeriesVariwideStatesSelectHalo(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def opacity(self): return self._config_get(0.25) def opacity(self, num: float): self._config(num, ...
class SioConnection(): async def emit(self, msg_type: str, msg: str, user_id: str, session_id: str, message_id: str): raise Exception('Not implemented!') async def safe_emit(self, msg_type: str, msg: str, user_id: str, session_id: str, msg_id: str): try: (await self.emit(msg_type, ms...
def _raise_contract_error(response_error_data: str) -> None: if response_error_data.startswith('Reverted '): reason_string = _parse_error_with_reverted_prefix(response_error_data) raise ContractLogicError(f'execution reverted: {reason_string}', data=response_error_data) elif (response_error_data...
class FloatTypeConverter(DataTypeConverter[float]): def __init__(self) -> None: super().__init__(name='float', empty_val=0.0) def to_value(self, other: Any) -> Optional[float]: try: return float(other) except (ValueError, TypeError): return None
class ScheduleMixinTester(unittest.TestCase): def setUp(self): super(ScheduleMixinTester, self).setUp() self.kwargs = {'name': 'ozgur', 'start': datetime.datetime(2013, 3, 20, 4, 0, tzinfo=pytz.utc), 'end': datetime.datetime(2013, 3, 30, 4, 0, tzinfo=pytz.utc), 'duration': datetime.timedelta(10)} ...
class Events(object): def __init__(self, core: Core) -> None: self.core = core self.core_initialized = EventHub[Core]() self.server_command = _ServerCommandMapping(core) self.server_connected = EventHub[bool]() self.server_refused = EventHub[bool]() self.server_droppe...
('{dst_data} = _mm512_maskz_loadu_ps(((1 << {N}) - 1), &{src_data});') def mm512_maskz_loadu_ps(N: size, dst: ([f32][16] AVX512), src: ([f32][N] DRAM)): assert (stride(src, 0) == 1) assert (stride(dst, 0) == 1) assert (N <= 16) for i in seq(0, 16): if (i < N): dst[i] = src[i]
def test_hic_transfer_covariance(): outfile = NamedTemporaryFile(suffix='covariance_.h5', delete=False) outfile.close() args = '--matrix {} --outFileName {} --method covariance'.format(original_matrix, outfile.name).split() compute(hicTransform.main, args, 5) test = hm.hiCMatrix((ROOT + 'hicTransfor...
def test_transaction_metrics(django_elasticapm_client, client): with override_settings(**middleware_setting(django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware'])): assert (len(django_elasticapm_client.events[TRANSACTION]) == 0) client.get(reverse('elasticapm-no-error')) ...
def _setup_locale() -> None: try: locale.textdomain('exaile') except AttributeError: pass gettextmod.textdomain('exaile') locale_path = _get_locale_path() if (locale_path is not None): try: locale.bindtextdomain('exaile', locale_path) except AttributeError...
class OpenIdCredentialManager(CredentialManager): def __init__(self, service_information: ServiceInformation, proxies: Optional[dict]=None): super().__init__(service_information, proxies) self.refresh_callbacks = [] def _grant_password_request_realm(self, login: str, password: str, realm: str) -...
('ner.match', dataset=('The dataset to use', 'positional', None, str), spacy_model=('The base model', 'positional', None, str), source=('The source data as a JSONL file', 'positional', None, str), patterns=('Optional match patterns', 'option', 'p', str), exclude=('Names of datasets to exclude', 'option', 'e', split_str...
class IDHelperTestCase(unittest.TestCase): def test_object_counter(self): from traits.api import WeakRef class Bogus(object): weak = WeakRef class Foo(object): foo = 3 foo = Foo() self.assertEqual(object_counter.get_count(Bogus), 0) self.assert...
def draw_result_img(img_disp, ith_img, humans, dict_id2skeleton, skeleton_detector, multiperson_classifier): (r, c) = img_disp.shape[0:2] desired_cols = int(((1.0 * c) * (img_disp_desired_rows / r))) img_disp = cv2.resize(img_disp, dsize=(desired_cols, img_disp_desired_rows)) skeleton_detector.draw(img_...
class ASMStarPC(ASMPatchPC): _prefix = 'pc_star_' def get_patches(self, V): mesh = V._mesh mesh_dm = mesh.topology_dm if mesh.cell_set._extruded: warning('applying ASMStarPC on an extruded mesh') depth = PETSc.Options().getInt((self.prefix + 'construct_dim'), default=...
class UI_MT_op_color_dropdown_convert_to(Menu): bl_idname = 'UI_MT_op_color_dropdown_convert_to' bl_label = 'To' bl_description = 'Convert Color IDs into ...' def draw(self, context): layout = self.layout layout.operator(op_color_convert_texture.op.bl_idname, text='Texture Atlas', icon_v...
def mark_range_as_read(nid: int, start: int, end: int, pages_total: int): now = _date_now_str() conn = _get_connection() res = conn.execute(f'select page from read where nid={nid} and page > -1').fetchall() res = [r[0] for r in res] to_insert = [] for p in range(start, (end + 1)): if (no...
.parametrize('enum_member, code', [(TypeOfGrid.CORNER_POINT, 0), (TypeOfGrid.UNSTRUCTURED, 1), (TypeOfGrid.COMPOSITE, 2), (TypeOfGrid.BLOCK_CENTER, 3)]) def test_type_of_grid_alternate_values(enum_member, code): assert (enum_member.alternate_value == code) assert (TypeOfGrid.alternate_code(code) == enum_member)