code
stringlengths
281
23.7M
def fetch_git_repo(git_url: str, commit: str) -> str: repo_dir = git_url.replace('://', '_').replace('/', '_') cache_dir = os.environ.get('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) clone_dir = os.path.join(cache_dir, 'flatpak-cargo', repo_dir) if (not os.path.isdir(os.path.join(clone_dir, '.git')...
def test_kafka_poll_unsampled_transaction(instrument, elasticapm_client, consumer, topics): transaction_object = elasticapm_client.begin_transaction('transaction') transaction_object.is_sampled = False consumer.poll(timeout_ms=50) elasticapm_client.end_transaction('foo') spans = elasticapm_client.ev...
def extractToastytranslationsCom(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)...
.parametrize('test_case', TEST_CASES, ids=['al-non-empty-list', 'al-empty-list', 'al-many-lists', 'al-no-explicit-type', 'df-1', 'df-2-int-values-and-access-list', 'df-no-explicit-type']) def test_hash(test_case): expected = test_case['expected_hash'] transaction = TypedTransaction.from_dict(test_case['transact...
class DeviceDiscovery(): def __init__(self, context, inventory): self._discoverers = [] self._discoverers.append(LocalhostDiscoverer(context, inventory)) self._discoverers.append(StaticDeviceDiscoverer(context, inventory)) self._discoverers.append(VMWareDeviceDiscoverer(context, inve...
def extractFreewinxtranslationWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (item['tags'] == ['Uncategorized']): titlemap = [('COYSE Chapter ', 'Congratulations o...
class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--filename') def handle(self, *args, **kwargs): with open(kwargs['filename']) as f: for row in csv.reader(f): if (row[0][0] != 'Y'): continue (team, _...
class TrioBackend(ConcurrencyBackend): def create_event(self) -> BaseEvent: return TrioEvent() def create_queue(self, capacity: int) -> BaseQueue: return TrioQueue(capacity=capacity) async def run_and_fail_after(self, seconds: typing.Optional[float], coroutine: typing.Callable[([], typing.Aw...
def extractBaixingheiyueTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return False if ('Flash Marriage' in item['tags']): return buildReleaseMessageWithType(item, 'Flash Marriag...
class TestOrders(Orders, TestSPAPI): def get_orders(self, created_after: str, created_before: str=None, last_updated_after: str=None, last_updated_before: str=None, order_statuses: list=None, marketplace_ids: list=None, fulfillment_channels: list=None, payment_methods: list=None, buyer_email: str=None, seller_order...
def global_enum(cls, update_str=False): if issubclass(cls, Flag): cls.__repr__ = global_flag_repr else: cls.__repr__ = global_enum_repr if ((not issubclass(cls, ReprEnum)) or update_str): cls.__str__ = global_str _sys.modules[cls.__module__].__dict__.update(cls.__members__) r...
def que_monitor(app, _info=print, _debug=print): def _log(fun, msg, *args): fun(('[sio.monitor] ' + (msg % args))) def log(msg, *args): _log(_info, msg, *args) def debug(msg, *args): _log(_debug, msg, *args) log('Starting dedicated que event monitor') internal_id = app.conf.E...
def cart_gto3d_2(ax, da, A, R): result = numpy.zeros((6,), dtype=float) x0 = (A[0] - R[0]) x1 = (x0 ** 2) x2 = (A[1] - R[1]) x3 = (x2 ** 2) x4 = (A[2] - R[2]) x5 = (x4 ** 2) x6 = (da * numpy.exp(((- ax) * ((x1 + x3) + x5)))) x7 = (0. * x6) x8 = (x0 * x6) result[0] = numpy.sum...
class TaskMetadata(_common.FlyteIdlEntity): def __init__(self, discoverable, runtime, timeout, retries, interruptible, discovery_version, deprecated_error_message, cache_serializable, pod_template_name): self._discoverable = discoverable self._runtime = runtime self._timeout = timeout ...
class MainWindow(Gtk.ApplicationWindow): def __init__(self, app): Gtk.ApplicationWindow.__init__(self, application=app, title=APPLICATION_NAME, icon=GdkPixbuf.Pixbuf.new_from_file(data_helpers.find_data_path('images/icon_64.png')), default_width=700, default_height=600, resizable=True) self._updatin...
def generate_zone_capacity_config(capacity_config: dict[(str, Any)], data: dict[(str, Any)]) -> dict[(str, Any)]: existing_capacity_modes = [mode for mode in data if (mode in capacity_config)] updated_capacity_config = deepcopy(capacity_config) for mode in existing_capacity_modes: if isinstance(capa...
class InputFileNotFoundError(ErsiliaError): def __init__(self, file_name): self.file_name = file_name self.message = 'Input file {0} does not exist'.format(self.file_name) self.hints = 'Please be make sure that you are passing a valid input file. Accepted formats are .csv, .tsv and .json\n' ...
def build_model(env, num_procs, timesteps_per_actorbatch, optim_batchsize, output_dir): policy_kwargs = {'net_arch': [{'pi': [512, 256], 'vf': [512, 256]}], 'act_fun': tf.nn.relu} timesteps_per_actorbatch = int(np.ceil((float(timesteps_per_actorbatch) / num_procs))) optim_batchsize = int(np.ceil((float(opti...
class DecisionTaskFailedCause(IntEnum): UNHANDLED_DECISION = 0 BAD_SCHEDULE_ACTIVITY_ATTRIBUTES = 1 BAD_REQUEST_CANCEL_ACTIVITY_ATTRIBUTES = 2 BAD_START_TIMER_ATTRIBUTES = 3 BAD_CANCEL_TIMER_ATTRIBUTES = 4 BAD_RECORD_MARKER_ATTRIBUTES = 5 BAD_COMPLETE_WORKFLOW_EXECUTION_ATTRIBUTES = 6 BA...
.parametrize(('username', 'user_id', 'status'), (('annedoe', '', 200), ('wronguser', '', 404), ('', '1', 200), ('', '200', 404), ('', '', 404))) def test_get_user(username, user_id, status): if username: response = client.get(('/users/user?username=' + username)) elif user_id: response = client....
class RelationshipWafRuleRevision(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_i...
def _allow_deprecated_default_init(func): (func) def wrapper(cls, *args, **kwargs): _deprecation_msg = 'X is a required argument, will no longer be defaulted in xtgeo version 4.0' if (len(args) != 4): if (('ncol' not in kwargs) and (len(args) != 1)): warnings.warn(_de...
class action(loxi.OFObject): subtypes = {} def __init__(self, type=None): if (type != None): self.type = type else: self.type = 0 return def pack(self): packed = [] packed.append(struct.pack('!H', self.type)) packed.append(struct.pack('...
class StdoutReporter(Reporter): def report(self, suite: Suite, results: List[TestCaseResult]): for case in results: color = ('\x1b[32m' if (case.status == TestStatus.PASSED) else '\x1b[31m') print(f'{case.name}: {color}{case.status.name}') if case.details: ...
def build_layout(layout): full_layout = {k.lower(): v for (k, v) in layout.layout.items()} for (alias, ref) in layout.aliases.items(): if (ref not in layout.layout): raise ValueError(("Wrong alias: '%s' aliases '%s' but '%s' is not in the layout" % (alias, ref, ref))) full_layout[ali...
def create_notebook_for_items(content, ui, parent, group, item_handler=None, is_dock_window=False): if is_dock_window: nb = parent else: dw = DockWindow(parent, handler=ui.handler, handler_args=(ui.info,), id=ui.id) if (group is not None): dw.theme = group.dock_theme ...
class DummyMatchFunc(): def __init__(self, return_value): self.return_value = return_value def __call__(self, name, trait): return self.return_value def __eq__(self, other): return (self.return_value == other.return_value) def __hash__(self): return hash(self.return_value...
class BusinessUser(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isBusinessUser = True super(BusinessUser, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): business = 'business' business_role_request = 'business_role_re...
def _iptables_parse_supported_icmp_types_4(): iptables_output = "iptables v1.8.9 (nf_tables)\n\nUsage: iptables -[ACD] chain rule-specification [options]\n iptables -I chain [rulenum] rule-specification [options]\n iptables -R chain rulenum rule-specification [options]\n iptables -D chain rulenum ...
def read_mod_def(line: str): keywords = re.findall(FRegex.SUB_MOD, line) line = re.sub(FRegex.SUB_MOD, '', line) mod_match = FRegex.MOD.match(line) if (mod_match is None): return None name = mod_match.group(1) if (name.lower() == 'procedure'): trailing_line = line[mod_match.end(1...
class TestNestedWriteErrors(TestCase): def test_nested_serializer_error(self): class ProfileSerializer(serializers.ModelSerializer): class Meta(): model = NestedWriteProfile fields = ['address'] class NestedProfileSerializer(serializers.ModelSerializer): ...
def jwt_brute(url, headers, body, jwt_token, jwt_alg, scanid=None): with open('secret.txt') as sign_keys: for sign_key in sign_keys: try: jwt.decode(jwt_token, sign_key.rstrip(), algorithms=[jwt_alg]) print(('%s[+]Weak JWT sign key found:{0}%s'.format(sign_key.rst...
def print_classes(f, outdir): outdir = os.path.relpath(outdir, os.path.dirname(f.name)) classes = inspect.getmembers(fnss, predicate=inspect.isclass) for (cls_name, cls_type) in classes: mod_name = cls_type.__module__ f.write(('.. currentmodule:: %s\n.. autoclass:: %s.%s\n.. autosummary::\n ...
class DAAPTrack(): attrmap = {'name': 'minm', 'artist': 'asar', 'album': 'asal', 'id': 'miid', 'type': 'asfm', 'time': 'astm', 'size': 'assz'} def __init__(self, database, atom): self.database = database self.atom = atom def __getattr__(self, name): if (name in self.__dict__): ...
class TestAddCliOption(object): def cli(self): cli = argparse.ArgumentParser() choice.add_cli_option(cli, 'light_effect0', {'label': 'Light effect', 'description': 'Set the light effect', 'cli': ['-e', '--light-effect', '--foobar'], 'command': [7, 0], 'value_type': 'choice', 'choices': {'steady': 1,...
def extractPeachpittingCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('There Will Always Be Protagonists With Delusions of Starting a Harem', 'There Will Always Be Protagon...
(scope='function') def mailchimp_connection_config(db: session, mailchimp_config, mailchimp_secrets) -> Generator: fides_key = mailchimp_config['fides_key'] connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': fides_key, 'connection_type': ConnectionType.saas, 'access': AccessLevel...
class OptionSeriesWordcloudAccessibilityPoint(Options): def dateFormat(self): return self._config_get(None) def dateFormat(self, text: str): self._config(text, js_type=False) def dateFormatter(self): return self._config_get(None) def dateFormatter(self, value: Any): self....
def update_camera_player_bounds_push(camera, player, env_items, delta, width, height): bbox = pyray.Vector2(0.2, 0.2) bbox_world_min = pyray.get_world_to_screen_2d(pyray.Vector2((((1 - bbox.x) * 0.5) * width), (((1 - bbox.y) * 0.5) * height)), camera) bbox_world_max = pyray.get_world_to_screen_2d(pyray.Vect...
.django_db def test_category_district_subawards(geo_test_data): test_payload = {'category': 'district', 'subawards': True, 'page': 1, 'limit': 50} spending_by_category_logic = DistrictViewSet().perform_search(test_payload, {}) expected_response = {'category': 'district', 'limit': 50, 'page_metadata': {'page...
def delete_note(id: int): update_priority_list(id, 0) conn = _get_connection() conn.executescript(f''' delete from read where nid ={id}; delete from marks where nid ={id}; delete from notes where id={id}; delete from queue_p...
def desktop_environment() -> DesktopEnvironment: kde_full_session = os.environ.get('KDE_FULL_SESSION', '').lower() xdg_current_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower() desktop_session = os.environ.get('DESKTOP_SESSION', '').lower() gnome_desktop_session_id = os.environ.get('GNOME_DESK...
def get_preview_config(config: Config) -> Config: user_config = dict((config.user_config or {})) user_config['max_repeat'] = 200 preview_config = Config(user_config, get_settings('config')) preview_config.options.update(config.options) preview_config.options['output.field'] = field_preview previ...
class PopStatsByStratum(Base): __tablename__ = 'popstats_stratum' pop_stats_stratum_id = Column(Integer, primary_key=True) country_data_id = Column(ForeignKey(CountryData.country_data_id), index=True) stratum_description_id = Column(ForeignKey(SharedDescription.description_id)) pop_count = Column(In...
class Flow_Del_4(base_tests.SimpleProtocol): def runTest(self): logging.info('Flow_Del_4 TEST BEGIN') logging.info('Deleting all flows from switch') delete_all_flows(self.controller) sw = Switch() self.assertTrue(sw.connect(self.controller), 'Failed to connect to switch') ...
('/offline_list') def offline_list(): msg_st = {'-1': '', '0': '', '1': '', '2': ''} task = xl.offline_list() uid = xl.getcookieatt('UID') uid = uid[:uid.index('_')] items = [] clearcomplete = {'time': str(int(time.time())), 'uid': uid} clearfaile = {'time': str(int(time.time())), 'uid': uid...
.parametrize('reference_data, current_data', ((pd.Series([1, 0, 1]), pd.Series([1, 0, 1, 0])), (pd.Series([1, 1, 1, 1]), pd.Series([0])))) def test_input_data_length_check_generate_fisher2x2_contingency_table(reference_data: pd.Series, current_data: pd.Series): with pytest.raises(ValueError, match='reference_data a...
class OptionPlotoptionsBulletSonification(Options): def contextTracks(self) -> 'OptionPlotoptionsBulletSonificationContexttracks': return self._config_sub_data('contextTracks', OptionPlotoptionsBulletSonificationContexttracks) def defaultInstrumentOptions(self) -> 'OptionPlotoptionsBulletSonificationDef...
.parametrize('matrix', [matrix]) .parametrize('outFileName', [outfile]) .parametrize('chromosomes', ['chr10', 'chr11']) .parametrize('action', ['keep', 'remove', 'mask']) .xfail def test_trivial_run_xfail_multichromosomes(matrix, outFileName, chromosomes, action): args = '--matrix {} --outFileName {} --chromosomes ...
class bsn_generic_stats_reply(bsn_stats_reply): version = 6 type = 19 stats_type = 65535 experimenter = 6035143 subtype = 16 def __init__(self, xid=None, flags=None, entries=None): if (xid != None): self.xid = xid else: self.xid = None if (flags !=...
def extractDeusexmachinetranslationsWordpressCom(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...
class Ttype(Node): total = 0 known = 0 unknown = 0 inf = 0 tp_1p = 0 fp_1p = 0 tn_1p = 0 fn_1p = 0 correct = 0 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.owner = kwargs['owner'] self.binary = self.owner.binary self....
class OptionSeriesDependencywheelSonificationDefaultinstrumentoptionsMappingHighpass(Options): def frequency(self) -> 'OptionSeriesDependencywheelSonificationDefaultinstrumentoptionsMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesDependencywheelSonificationDefaultinstrumento...
def test_scale_velocities_to_temperatue(): atoms = 5 masses = np.ones(atoms) T = 298.15 E_ref = kinetic_energy_for_temperature(atoms, T) v_unscaled = (2 * (np.random.rand(atoms, 3) - 0.5)) v_scaled = scale_velocities_to_temperatue(masses, v_unscaled, T) E_scaled = kinetic_energy_from_velocit...
.parametrize('pattern,text', [([{'IS_ALPHA': True}], 'a'), ([{'IS_ASCII': True}], 'a'), ([{'IS_DIGIT': True}], '1'), ([{'IS_LOWER': True}], 'a'), ([{'IS_UPPER': True}], 'A'), ([{'IS_TITLE': True}], 'Aaaa'), ([{'IS_PUNCT': True}], '.'), ([{'IS_SPACE': True}], '\n'), ([{'IS_BRACKET': True}], '['), ([{'IS_QUOTE': True}], ...
.parametrize('examples_file', ['ner.json', 'ner.yml', 'ner.jsonl']) def test_jinja_template_rendering_with_label_definitions(examples_dir: Path, examples_file: str): labels = 'PER,ORG,LOC' nlp = spacy.blank('en') doc = nlp.make_doc('Alice and Bob went to the supermarket') examples = fewshot_reader((exam...
def check_random_sampling(config_module: str, config: str, overrides: Dict[(str, str)]) -> None: env = make_env_from_hydra(config_module, config, **overrides) if isinstance(env, ObservationNormalizationWrapper): normalization_statistics = obtain_normalization_statistics(env=env, n_samples=100) e...
class Solution(): def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: if (not nums): return [] q = deque() for index in range(0, k): while (q and (nums[index] >= q[0][0])): q.popleft() while (q and (nums[index] >= q[(- 1)][0])...
class OptionPlotoptionsBubbleMarkerStates(Options): def hover(self) -> 'OptionPlotoptionsBubbleMarkerStatesHover': return self._config_sub_data('hover', OptionPlotoptionsBubbleMarkerStatesHover) def normal(self) -> 'OptionPlotoptionsBubbleMarkerStatesNormal': return self._config_sub_data('normal...
class Callabike(DB): unifeed = True meta = dict({'name': 'Call-A-Bike'}, **DB.meta) provider = 'CallABike' cache = TSTCache(delta=60) def __init__(self, *args, **kwargs): super(Callabike, self).__init__(*args, provider=Callabike.provider, **kwargs) def update(self, scraper=None): ...
class Plot(Subplot, Frame, RecordMixin): def __init__(self, canvas: Union[(str, WgpuCanvas)]=None, renderer: pygfx.WgpuRenderer=None, camera: Union[(str, pygfx.PerspectiveCamera)]='2d', controller: Union[(str, pygfx.Controller)]=None, size: Tuple[(int, int)]=(500, 300), **kwargs): super(Plot, self).__init__...
def exposed_validate_feed_url_mimetypes(): wg = WebMirror.API.WG_POOL[0] rules = WebMirror.rules.load_rules() feed_urls = [tmp for item in rules for tmp in item['feedurls']] for url in feed_urls: try: (_, _, mime) = wg.getFileNameMime(url) print(("Type: '%s' for url: '%s'...
class Migration(migrations.Migration): dependencies = [('sites', '0023_auto__2034')] operations = [migrations.AddField(model_name='site', name='onion_address', field=models.URLField(blank=True, help_text='The Onion address for this site. This field takes precedence over the Onion-Location header from scan resul...
class GoogleSearch(BaseTool): def __init__(self, num_results=8, start_page=1): super(GoogleSearch, self).__init__() self.google_api_key = os.getenv('GOOGLE_API_KEY') self.google_cx_id = os.getenv('GOOGLE_CX_ID') self.num = num_results self.start = ((num_results * (start_page ...
() ('input', type=click.Path(), required=True) ('--type', default='files', show_default=True, help='Type of file to sync') ('--all', is_flag=True, help='Sync all the things?') ('--debug', is_flag=True, default=False, help='Enable debug mode') def cli(input, type, all, debug): print(f"Debug mode is {('on' if debug e...
def get_scope_level(level_selection, level): if (level_selection == 'BASE_ONLY'): return 0 elif (level_selection == 'BASE_NTH_LEVEL'): return level elif (level_selection == 'BASE_SUBTREE'): return (level + 1) elif (level_selection == 'BASE_ALL'): return 10
class Solution(): def longestValidParentheses(self, s: str) -> int: (count, start, mm) = (0, 0, 0) for (i, c) in enumerate(s): if (c == '('): count += 1 else: count -= 1 if (count < 0): count = 0 star...
def progressive_test(state, s, test_partial=False): total = 1 start = time.time() (s, d) = _parse_autocomplete_requirements(s) for i in range(1, len(s)): ps = s[:i] if ((i in d) or test_partial): names = autocomplete(state, ps) total += 1 if (i in d): ...
class ExternalProjectAccessRuleBook(bre.BaseRuleBook): ancestor_pattern = re.compile('^organizations/\\d+$|^folders/\\d+$') email_pattern = re.compile('(^[a-zA-Z0-9_.+-]+[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)') def __init__(self, rule_defs=None): super(ExternalProjectAccessRuleBook, self).__init__() ...
def main(): logging.basicConfig(filename=os.path.join(get_user_path(), 'roamer.log'), format='%(asctime)-15s %(levelname)-7s %(module)s.%(funcName)s(): %(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser(description='RoAMer Unpacker Module.') parser.add_argument('--local', action='store_true...
def require_fastapi_mvc_project() -> Dict[(str, Any)]: project_data = load_answers_file() keys = ['_commit', '_src_path', 'project_name', 'package_name'] if (not project_data): log.error("Not a fastapi-mvc project. Try 'fastapi-mvc new --help' for details how to create one.") raise SystemExi...
class PileWidget(Static): top_card = reactive(None) can_focus = True def __init__(self, pile: list[Card], **kwargs) -> None: super().__init__(**kwargs) self.pile = pile self.update(card_render.draw_empty_card()) self.refresh_contents() self.last_time_clicked = None ...
def validate_type(func): (func) def wrapper(*args, **kwargs): sig = inspect.signature(func) annotated_types = {k: v.annotation for (k, v) in sig.parameters.items() if (v.annotation != inspect._empty)} bound_args = sig.bind(*args, **kwargs) bound_args.apply_defaults() for ...
def test_get_executable_stats(backend_db, stats_updater): for (i, file_str) in enumerate(['ELF 64-bit LSB executable, x86-64, dynamically linked, for GNU/Linux 2.6.32, not stripped', 'ELF 32-bit MSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), statically linked, not stripped', 'ELF 64-bit LSB executable, x86-64,...
(urls.DRP_STATUS, dependencies=[Security(verify_oauth_client, scopes=[scopes.PRIVACY_REQUEST_READ])], response_model=PrivacyRequestDRPStatusResponse) def get_request_status_drp(*, db: Session=Depends(deps.get_db), request_id: str) -> PrivacyRequestDRPStatusResponse: logger.info('Finding request for DRP with ID: {}'...
def main(): parser = argparse.ArgumentParser(description='Take control of your ColorLight FPGA board with LiteX/LiteEth :)') parser.add_argument('--build', action='store_true', help='Build bitstream') parser.add_argument('--load', action='store_true', help='Load bitstream') parser.add_argument('--flash'...
def test_invalid_geographic_coordinates(): boundaries = [0, 360, (- 90), 90] spacing = 10 region = [(- 20), 20, (- 20), 20] (longitude, latitude) = grid_coordinates(boundaries, spacing=spacing) longitude[0] = (- 200) with pytest.raises(ValueError): longitude_continuity([longitude, latitu...
def crawl_headers(url_list, output_file, custom_settings=None): if isinstance(url_list, str): url_list = [url_list] if (output_file.rsplit('.')[(- 1)] != 'jl'): raise ValueError(f'''Please make sure your output_file ends with '.jl'. For example: {output_file.rsplit('.', maxsplit=1)[0]}.jl''') ...
def get_admin_details(): _username = admin match = False email = input('Enter admin email: ') while (match is False): password1 = getpass('Enter password: ') password2 = getpass('Re-enter password: ') if (password1 != password2): print('Passwords do not match, please ...
class _ContextWrapper(): def __init__(self, func, args): self._func = func self._args = args self._context = func(*args) def __enter__(self): return self._context.__enter__() def __exit__(self, exc_type, exc_value, traceback): return self._context.__exit__(exc_type, e...
class OptionSeriesBarTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionSeriesBarTooltipDatetimelabelformats': ...
.script('os.write(fd, b\'{"authtoken": "test123", "urls": ["url"]}\')\nos.close(fd)\ntime.sleep(10)\nsys.exit(1)\n') def test_long_lived(server, tmp_path): assert (server.fetch_conn_info() == {'authtoken': 'test123', 'urls': ['url']}) assert (server.shutdown() == (- signal.SIGTERM)) assert (not (tmp_path / ...
def create_optimizer_for_async_aggregator(config: AsyncAggregatorConfig, model: Model): if (config._target_ in {FedAvgWithLRAsyncAggregatorConfig._target_, FedAvgWithLRFedBuffAggregatorConfig._target_, FedAvgWithLRWithMomentumAsyncAggregatorConfig._target_}): return torch.optim.SGD(model.parameters(), lr=co...
class N64SegImg(N64Segment): def parse_dimensions(yaml: Union[(Dict, List)]) -> Tuple[(int, int)]: if isinstance(yaml, dict): return (yaml['width'], yaml['height']) else: if (len(yaml) < 5): log.error(f'Error: {yaml} is missing width and height parameters') ...
class DeletionCandidateTestCase(unittest.TestCase): def setUp(self): self.contig = 'chr1' self.start = 1000 self.end = 2000 self.members = [SignatureDeletion(self.contig, self.start, self.end, 'cigar', 'read1')] self.score = 2 self.std_span = 10.2346 self.std_...
def partial_project_query(): inner_tasks = aliased(Task.__table__) subquery = DBSession.query(inner_tasks.c.id).filter((inner_tasks.c.project_id == Project.id)) query = DBSession.query(Project.id, Project.name, Project.entity_type, Project.status_id, subquery.exists().label('has_children')) query = quer...
class benedict_keyattr_test_case(unittest.TestCase): def test_getitem(self): d = {'a': {'b': {'c': 'ok', 'd': [0, 1, 2, 3], 'e': [{'f': 4}, {'g': [5]}]}}} b = benedict(d, keyattr_enabled=True, keyattr_dynamic=True) self.assertEqual(b.a.b.c, 'ok') self.assertEqual(b.a.b.d[(- 1)], 3) ...
class NDArrayExtension(Extension): name = 'ndarray' def __init__(self): if ('numpy' in sys.modules): import numpy as np self.cls = np.ndarray def match(self, s, v): return (hasattr(v, 'shape') and hasattr(v, 'dtype') and hasattr(v, 'tobytes')) def encode(self, s, ...
class ComponentBase(): def __init__(self, app, db: FrontendDatabase, intercom: InterComFrontEndBinding, status: RedisStatusInterface, api=None): self._app = app self._api = api self.db = db self.intercom = intercom self.status = status self._init_component() def _...
class FileTar(BaseTest): folders_rel = ['test_file_tar/dir1', 'test_file_tar/dir1/dir2', 'test_file_tar/dir1/dir2/dir3', 'test_file_tar/dir1/dir2/dir3/dir4'] folders_abs = [os.path.join(config.base_folder, f) for f in folders_rel] files_rel = ['test_file_tar/dir1/f1', 'test_file_tar/dir1/dir2/f2', 'test_fil...
class OptionSeriesPyramidSonificationContexttracksMapping(Options): def frequency(self) -> 'OptionSeriesPyramidSonificationContexttracksMappingFrequency': return self._config_sub_data('frequency', OptionSeriesPyramidSonificationContexttracksMappingFrequency) def gapBetweenNotes(self) -> 'OptionSeriesPyr...
def decimalDate(date, fmt='%Y-%m-%d', variable=False): if (fmt == ''): return date delimiter = re.search('[^0-9A-Za-z%]', fmt) delimit = None if (delimiter is not None): delimit = delimiter.group() if (variable == True): if (delimit is not None): dateL = len(date....
class PlotTool(Tool): def __init__(self, config_file, main_window): super().__init__('Create plot', QIcon('img:timeline.svg')) self._config_file = config_file self.main_window = main_window def trigger(self): plot_window = PlotWindow(self._config_file, self.main_window) p...
class RegReplaceDeleteRegexCommand(sublime_plugin.WindowCommand): def delete_rule(self, value): if (value >= 0): if sublime.ok_cancel_dialog(("Are you sure you want to delete the rule: '%s'?" % self.keys[value])): del self.regex_rules[self.keys[value]] sublime.loa...
class ReferenceData(sdict): def __init__(self, model_class, **kwargs): self.model_class = model_class super(ReferenceData, self).__init__(**kwargs) def dbset(self): if self.method: return self.method(self.model_class) return self.model_class.db def model_instance(...
class Test_icmpv6_nd_option_pi(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_default_args(self): pi = icmpv6.nd_option_pi() buf = pi.serialize() res = struct.unpack(icmpv6.nd_option_pi._PACK_STR, six.binary_type(buf)) eq_(res[0], ...
_os(*metadata.platforms) def main(): winword = 'C:\\Users\\Public\\winword.exe' posh = 'C:\\Users\\Public\\posh.exe' common.copy_file(EXE_FILE, winword) common.copy_file(EXE_FILE, posh) cmd = "New-ItemProperty -Path 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' -Name Test -PropertyType ...
class ModeBasis(object): def __init__(self, transformation_matrix, grid=None): if scipy.sparse.issparse(transformation_matrix): sparse = True is_list = False elif scipy.sparse.issparse(transformation_matrix[0]): sparse = np.all([(transformation_matrix[i].shape[0] ...
(scope='function') def yotpo_loyalty_erasure_data(yotpo_loyalty_test_client: YotpoLoyaltyTestClient, yotpo_loyalty_erasure_identity_email) -> None: response = yotpo_loyalty_test_client.create_customer(yotpo_loyalty_erasure_identity_email) assert response.ok poll_for_existence(yotpo_loyalty_test_client.get_c...
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.') .skipif((MID_MEMORY > memory), reason='Travis has too less memory to run it.') def test_hicPlotMatrix_region_region2_log1p_and_bigwig(): outfile = NamedTemporaryFile(suffix='.png', prefix='hicexplorer_test_h5_', del...