code
stringlengths
281
23.7M
def create_callback(): global CALLBACK_CREATED if (not CALLBACK_CREATED): _app.callback(Output(EMPTY_DIV, 'children'), [Input('battery-table', 'data_timestamp')], [State('battery-table', 'data'), State('battery-table', 'data_previous')]) def capture_diffs_in_battery_table(timestamp, data, data_p...
class MapCSSWriter(): def __init__(self, scheme: Scheme, icon_directory_name: str, add_icons: bool=True, add_ways: bool=True, add_icons_for_lifecycle: bool=True) -> None: self.add_icons: bool = add_icons self.add_ways: bool = add_ways self.add_icons_for_lifecycle: bool = add_icons_for_lifecy...
.unit class TestCredentials(): def test_valid_credentials(self): credentials = Credentials(username='test', password='password', user_id='some_id', access_token='some_token') assert (credentials.username == 'test') assert (credentials.password == 'password') assert (credentials.user_...
def _geth_command_arguments(rpc_port, base_geth_command_arguments, geth_version): (yield from base_geth_command_arguments) if (geth_version.major == 1): (yield from ('-- '-- rpc_port, '-- 'admin,eth,net,web3,personal,miner,txpool', '--ipcdisable', '--allow-insecure-unlock', '--miner.etherbase', COINBASE...
_test def test_lsl_poller_node() -> None: class LSLPollerGraphConfig(Config): output_filename: str class LSLPollerGraph(Graph): MY_SOURCE: LSLPollerNode MY_SINK: MySink config: LSLPollerGraphConfig def setup(self) -> None: self.MY_SOURCE.configure(LSLPollerCon...
def test_from_file_double_dimensions(simple_roff_parameter_contents): buff = io.BytesIO() simple_roff_parameter_contents.append(('dimensions', {'nX': 2, 'nY': 2, 'nZ': 2})) roffio.write(buff, simple_roff_parameter_contents) buff.seek(0) with pytest.raises(ValueError, match='Multiple tag'): R...
('MXNetWrapper.v1') def MXNetWrapper(mxnet_model, convert_inputs: Optional[Callable]=None, convert_outputs: Optional[Callable]=None, model_class: Type[Model]=Model, model_name: str='mxnet') -> Model[(Any, Any)]: if (convert_inputs is None): convert_inputs = convert_mxnet_default_inputs if (convert_outpu...
class TestDPRoundReducer(TestRoundReducerBase): def test_dp_off(self) -> None: ref_model = create_ref_model(ref_model_param_value=3.0) dp_rr = get_dp_round_reducer(ref_model, clipping_value=float('inf'), noise_multiplier=0) assertFalse(dp_rr.privacy_on) dp_rr = get_dp_round_reducer(r...
def upgrade(): op.create_table('message_settings', sa.Column('id', sa.Integer(), nullable=False), sa.Column('action', sa.String(), nullable=True), sa.Column('mail_status', sa.Integer(), nullable=True), sa.Column('notif_status', sa.Integer(), nullable=True), sa.Column('user_control_status', sa.Integer(), nullable=Tr...
def tensorflow2xp(tf_tensor: 'tf.Tensor', *, ops: Optional['Ops']=None) -> ArrayXd: from .api import NumpyOps assert_tensorflow_installed() if is_tensorflow_gpu_array(tf_tensor): if isinstance(ops, NumpyOps): return tf_tensor.numpy() else: dlpack_tensor = tf.experimen...
class WindowsOpenIntent(hass.Hass): def initialize(self): self.listService = self.get_app('listService') return def getIntentResponse(self, slots, devicename): try: windows_dict = self.listService.getWindow() doors_dict = self.listService.getDoor() doo...
class ListWallpapers(SimpleDirectiveMixin, Directive): required_arguments = 0 optional_arguments = 0 def make_rst(self): wps = [] for wpname in dir(wallpapers): wpaper = getattr(wallpapers, wpname) wps.append((wpname, wpaper)) rst = list_wallpapers_template.re...
('/status/<wf_unique_id>', methods=['GET']) def status(wf_unique_id): global old_wf run_records = read_status(wf_unique_id) if (not run_records): return jsonify({'ERROR:': 'ID does not exist'}) records = [] for i in run_records: if (i[1].split('_')[0] == 'STEP'): step = j...
class UniqueForYearValidator(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" year.') def filter_queryset(self, attrs, queryset, field_name, date_field_name): value = attrs[self.field] date = attrs[self.date_field] filter_kwargs = {} filter_k...
class aggregate_stats_reply(stats_reply): version = 3 type = 19 stats_type = 2 def __init__(self, xid=None, flags=None, packet_count=None, byte_count=None, flow_count=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): ...
def test_verify_different_author_and_chat(patch_chat, patch_chat_member, master_channel): msg = Message(chat=patch_chat, author=patch_chat_member, text='Message', deliver_to=master_channel) msg.verify() patch_chat.verify.assert_called_once() patch_chat_member.verify.assert_called_once()
def block_ranges(start_block: BlockNumber, last_block: Optional[BlockNumber], step: int=5) -> Iterable[Tuple[(BlockNumber, BlockNumber)]]: if ((last_block is not None) and (start_block > last_block)): raise TypeError('Incompatible start and stop arguments.', 'Start must be less than or equal to stop.') ...
def execute_trace_test(name): for filename in ('mh_trace.json', 'mh_trace_by_tag.json', 'mh_act_trace.lobster', 'mh_imp_trace.lobster'): if os.path.isfile(filename): os.unlink(filename) flags = [] if os.path.isfile('cmdline'): with open('cmdline', 'r') as fd: for raw_...
class FlattenConcatBaseNet(nn.Module): def __init__(self, obs_shapes: Dict[(str, Sequence[int])], hidden_units: List[int], non_lin: nn.Module): super().__init__() self.hidden_units = hidden_units self.non_lin = non_lin self.perception_dict: Dict[(str, PerceptionBlock)] = dict() ...
class CmdTime(COMMAND_DEFAULT_CLASS): key = '' aliases = '' locks = 'cmd:perm(time) or perm(Player)' help_category = 'System' def func(self): table1 = self.styled_table('|wServer time', '', align='l', width=78) table1.add_row('Current uptime', utils.time_format(gametime.uptime(), 3))...
def _get_data_type(n_bytes_per_element, sign_flag): if (n_bytes_per_element not in VALID_ELEMENT_SIZES): raise NotImplementedError((("Found a 'Grid data element size' (a.k.a. 'ES') value " + f"of '{n_bytes_per_element}'. Only values equal to 1, 2, 4 and 8 are valid, ") + 'along with their compressed counter...
def get_header_line(filenames): pipeline = '({read_files}) 2>/dev/null'.format(read_files=read_files(filenames, max_lines=1)) header_lines = subprocess.check_output(pipeline, shell=True).decode('utf8').splitlines() header_line = header_lines[0] for (n, filename) in enumerate(filenames): other_li...
class OptionSeriesPackedbubbleDataDatalabelsTextpath(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._c...
class CollectorConfig(Config): class Config(): underscore_attrs_are_private = True id: str = '' trigger: CollectorTrigger report_config: ReportConfig reference_path: Optional[str] project_id: str api_url: str = ' api_secret: Optional[str] = None cache_reference: bool = True ...
class PhonyCursor(): def __init__(self, test_file=None): if (not test_file): test_file = os.path.join(os.path.dirname(__file__), 'tests/etl_test_data.json') with open(test_file) as json_data: self.db_responses = json.load(json_data) self.results = None def execute...
def check_reqdir(reqdir: str, pfiles: 'JobsFS', cls=RequestDirError) -> requests.RequestID: (requests_str, reqid_str) = os.path.split(reqdir) if (requests_str != pfiles.requests.root): raise cls(None, reqdir, 'invalid', 'target not in ~/BENCH/REQUESTS/') reqid = requests.RequestID.parse(reqid_str) ...
def test_packages_installed(host): installed = False for name in ('kernel', 'kernel-common', 'kernel-devel', 'kernel-headers', 'linux-headers', 'linux-image'): package = host.package(name) if (not package.is_installed): continue version = '-'.join((ver for ver in (package.ver...
def ComputeReposWithChanges(repos_and_curr_branch, params): commands = [] for (repo, _branch) in repos_and_curr_branch: commands.append(ParallelCmd(repo, ([params.config.git] + ['status', '-s']))) repos_with_changes = {} def OnOutput(output): if (not output.stdout): repos_wit...
class DateDetectorTemplate(object): __slots__ = ('template', 'hits', 'lastUsed', 'distance') def __init__(self, template): self.template = template self.hits = 0 self.lastUsed = 0 self.distance = def weight(self): return ((self.hits * self.template.weight) / max(1, s...
_arguments def listen_events(args): class Processor(ListenerProcessor): def __init__(self, queue): self.queue = queue def process(self, events: List[Event]): for e in events: self.queue.put(e) client = EmbeddedNotificationClient(server_uri=args.server_uri,...
class QR_Window(QWidget): def __init__(self, win): QWidget.__init__(self) self.win = win self.setWindowTitle(('ElectrumSV - ' + _('Payment Request'))) self.label = '' self.amount = 0 self.setFocusPolicy(Qt.NoFocus) layout = QGridLayout() self.qrw = QRC...
def setup_test_data(db): baker.make('submissions.DABSSubmissionWindowSchedule', submission_fiscal_year=2020, submission_fiscal_month=8, is_quarter=False, submission_reveal_date='2020-06-01', period_start_date='2020-04-01') baker.make('reporting.ReportingAgencyOverview', toptier_code='043', fiscal_year=2020, fis...
def _validate_submission_type(filters: dict) -> None: legacy_submission_type = filters.get('submission_type', ...) submission_types = filters.get('submission_types', ...) if ((submission_types == ...) and (legacy_submission_type == ...)): raise InvalidParameterException('Missing required filter: sub...
def remove_redundant_and_unpin_blocks(asmcfg, head, mode, unpin=True): reachable_loc_keys = list(asmcfg.reachable_sons(head)) blocks_to_be_removed = [] rip = ExprId('RIP', 64) new_next_addr_card = ExprLoc(asmcfg.loc_db.get_or_create_name_location('_'), 64) for block in asmcfg.blocks: if (blo...
def savgol(x, total_width=None, weights=None, window_width=7, order=3, n_iter=1): if (len(x) < 2): return x if (total_width is None): total_width = (n_iter * window_width) if (weights is None): (x, total_wing, signal) = check_inputs(x, total_width, False) else: (x, total_...
class OptionSeriesGaugeSonificationTracksMappingHighpassResonance(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 parse_cnc_request_config(f, data): data['msg_type_decoded'] = 'REQUEST_CONFIG' data['loop_count'] = unpack('I', f.read(4))[0] data['nb_localscans'] = unpack('I', f.read(4))[0] data['nb_extscans'] = unpack('I', f.read(4))[0] data['nb_ifscans'] = unpack('I', f.read(4))[0] data['nb_killed'] = u...
def _main(): env = jinja2.Environment(loader=jinja2.FileSystemLoader('.')) env.filters['event_link'] = _filter_event_link env.filters['member_heading'] = _filter_member_heading env.filters['yes_or_no'] = _filter_yes_or_no templ = env.get_template('event_docs.md.j2') for filename in sys.argv[1:]:...
def admin_login(driver): try: driver.get(CHALL_URL) (username, password) = ('admin', 'gtrunkgeljndrthuiujgejleuudbcklbeuvbktkgfgcftvkfhkdugrcfheegjjtb') username_input = driver.find_element_by_id('username') password_input = driver.find_element_by_id('password') username_inpu...
def edit(filename=None, contents=None, use_tty=None, suffix=''): editor = get_editor() args = ([editor] + get_editor_args(os.path.basename(os.path.realpath(editor)))) if (use_tty is None): use_tty = (sys.stdin.isatty() and (not sys.stdout.isatty())) if (filename is None): tmp = tempfile....
def test_split_color_glyphs_by_version(): layerBuilder = LayerListBuilder() colorGlyphs = {'a': [('b', 0), ('c', 1), ('d', 2), ('e', 3)]} (colorGlyphsV0, colorGlyphsV1) = builder._split_color_glyphs_by_version(colorGlyphs) assert (colorGlyphsV0 == {'a': [('b', 0), ('c', 1), ('d', 2), ('e', 3)]}) ass...
def send_image(self, fileDir=None, toUserName=None, mediaId=None, file_=None): logger.debug(('Request to send a image(mediaId: %s) to %s: %s' % (mediaId, toUserName, fileDir))) if (fileDir or file_): if hasattr(fileDir, 'read'): (file_, fileDir) = (fileDir, None) if (fileDir is None)...
.usefixtures('use_tmpdir') def test_validate_no_logs_when_overwriting_with_same_value(caplog): with open('job_file', 'w', encoding='utf-8') as fout: fout.write('EXECUTABLE echo\nARGLIST <VAR1> <VAR2> <VAR3>\n') with open('config_file.ert', 'w', encoding='utf-8') as fout: fout.write('NUM_REALIZAT...
class OptionPlotoptionsDependencywheelSonificationTracksMappingPan(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 OptionPlotoptionsSankeySonificationContexttracksMappingPan(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 _get_required_dbt_package_version() -> Optional[str]: packages_file_path = os.path.join(PATH, _PACKAGES_FILENAME) packages_yaml = OrderedYaml().load(packages_file_path) for requirement in packages_yaml.get('packages', []): package_id = requirement.get('package') if (not package_id): ...
class BaseEventGeneratorNode(Node, metaclass=BaseEventGeneratorNodeMeta): def __init__(self) -> None: super(BaseEventGeneratorNode, self).__init__() self._start_time: float = time() def _time_elapsed_since_start(self) -> float: return (time() - self._start_time) def setup_generator(s...
class OptionTime(Options): def Date(self): return self._config_get('undefined') def Date(self, value: Any): self._config(value, js_type=False) def getTimezoneOffset(self): return self._config_get('undefined') def getTimezoneOffset(self, value: Any): self._config(value, js...
def test_to_security_item(): item = technical.to_security_item('stock_sz_000338') assert (item.id == 'stock_sz_000338') assert (item.code == '000338') item = technical.to_security_item('000338') assert (item.id == 'stock_sz_000338') assert (item.code == '000338') item = technical.to_security...
def main(): a = ArgumentParser() a.add_argument('-f', '--fsa', metavar='FSAFILE', required=True, help="HFST's optimised lookup binary data for the transducer to be applied") a.add_argument('-i', '--input', metavar='INFILE', type=open, required=True, dest='infile', help='source of analysis data') a.add_a...
def extract_fields(aggregate: Dict, collections: List[Collection]) -> None: for collection in collections: field_dict = aggregate[collection.name] for field in collection.fields: if field_dict.get(field.name): field_dict[field.name] = merge_fields(field_dict[field.name], ...
def extractUrbanlegendsclubOrg(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) i...
def addr_infos(): return [hr.AddrInfo(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP, sockaddr=hr.IPv4Sockaddr(address='10.0.0.42', port=6052)), hr.AddrInfo(family=socket.AF_INET6, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP, sockaddr=hr.IPv6Sockaddr(address='2001:db8:85a3::8a2e:370:...
.parametrize('val, meant_to_be, encode_fn, decode_fn', ((ADDRESS_TALLY_PAIRS[0], tuple, encode_address_tally_pair, decode_address_tally_pair), (DUMMY_VOTE_1, Vote, encode_vote, decode_vote), (DUMMY_VOTE_2, Vote, encode_vote, decode_vote), (SNAPSHOT_1, Snapshot, encode_snapshot, decode_snapshot), (TRUMP_TALLY, Tally, en...
class CargoTomlParser(FileParser): def parse(self, content: str) -> List[str]: try: data = toml.loads(content) dependencies = [] if ('dependencies' in data): dependencies.extend(data.get('dependencies', {}).keys()) if ('dev-dependencies' in dat...
def _fuse_group_ops_by_type(sorted_graph: List[Tensor], op_type: str, workdir: str=None) -> List[Tensor]: if (not _group_ops_by_type(sorted_graph, op_type, workdir)): return sorted_graph sorted_graph = toposort(sorted_graph) sorted_graph = transform_utils.sanitize_sorted_graph(sorted_graph) retu...
def analyze(mission): try: Analyzer(mission).analyze() except WorkerExit: raise except Exception as err: traceback.print_exc() download_ch.pub('ANALYZE_FAILED', (err, mission)) except PauseDownloadError as err: download_ch.pub('ANALYZE_INVALID', (err, mission)) ...
def _access_list_rpc_to_rlp_structure(access_list: Sequence) -> Sequence: if (not is_rpc_structured_access_list(access_list)): raise ValueError('provided object not formatted as JSON-RPC-structured access list') rlp_structured_access_list = [] for d in access_list: rlp_structured_access_list...
class OptionPlotoptionsColumnSonificationContexttracksMappingPan(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 FaucetTaggedAndUntaggedSameVlanTest(FaucetTest): N_TAGGED = 1 N_UNTAGGED = 3 LINKS_PER_HOST = 1 CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "mixed"\n' CONFIG = '\n interfaces:\n %(port_1)d:\n tagged_vlans: [100]\n %(port_2)d:\n ...
class FLCSVDataset(FLDataset): def __init__(self, path: str): self.data_frame = pd.read_csv(path) def __len__(self): return len(self.data_frame) def __getitem__(self, idx): raw_row = self.data_frame.iloc[idx] return self._get_processed_row_from_single_raw_row(raw_row) def...
class RegressionErrorNormality(Metric[RegressionErrorNormalityResults]): def __init__(self, options: AnyOptions=None): super().__init__(options=options) def calculate(self, data: InputData) -> RegressionErrorNormalityResults: dataset_columns = process_columns(data.current_data, data.column_mappi...
class System_base(_System_base): def __init__(self, **args): super(System_base, self).__init__(**args) for k in (set(system_default_keys) - set(args.keys())): v = default_so.__dict__[k] if (not inspect.isclass(v)): try: self.__dict__[k] = c...
def test_align_concatenate_to_phylip(o_dir, e_dir, request): program = 'bin/align/phyluce_align_concatenate_alignments' output = os.path.join(o_dir, 'mafft-gblocks-clean-concat-phylip') cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft-gblocks-clean'), '--outpu...
class TestLayoutTokensText(): def test_should_select_tokens_based_on_index(self): token_1 = LayoutToken(text='token1', whitespace=' ') token_2 = LayoutToken(text='token2', whitespace=' ') layout_tokens_text = LayoutTokensText(LayoutBlock.for_tokens([token_1, token_2])) assert (str(la...
def extractTranslatingSloth(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None tagmap = [('', "Wife, I Am the Baby's Father", 'translated'), ("Wife, I Am the Baby's Father", "Wife, I ...
class OptionPlotoptionsWaterfallLabel(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): ...
class FrontendUtilsTest(TestCase): def test_readable_size_correct_no_snapshot(self): scales = ['B', 'KB', 'MB', 'GB', 'TB', 'EB'] original_val = 10 for i in range(6): val = (original_val * (1024 ** i)) string_val = frontend_utils.readable_size(val) correct...
class OptionSeriesTreemapSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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, ...
('/get-complex-object', methods=['GET']) def get_complex_object(): print(bool(request.args.get('returnObject'))) if bool(request.args.get('returnObject')): return_object = {'complexObj': [{'id': '0001', 'type': 'donut', 'name': 'Cake', 'ppu': 0.55, 'batters': {'batter': [{'id': '1001', 'type': 'Regular'...
def test_conversion_of_ai_standard_to_red_shift_material_diffuse_properties(create_pymel, setup_scene): pm = create_pymel (ai_standard, ai_standard_sg) = pm.createSurfaceShader('aiStandard') diffuse_color = (1, 0.5, 0) diffuse_weight = 0.532 diffuse_roughness = 0.8 transl_weight = 0.25 diffu...
class LayoutMapBoxLayer(OptPlotly.Layout): def sourcetype(self): return self._attrs['sourcetype'] def sourcetype(self, val): self._attrs['sourcetype'] = val def source(self): return self._attrs['source'] def source(self, val): self._attrs['source'] = val def below(sel...
class TestUCSSerialize(util.ColorAssertsPyTest): COLORS = [('color(--ucs 0.75 0.1 0.1 / 0.5)', {}, 'color(--ucs 0.75 0.1 0.1 / 0.5)'), ('color(--ucs 0.75 0.1 0.1)', {'alpha': True}, 'color(--ucs 0.75 0.1 0.1 / 1)'), ('color(--ucs 0.75 0.1 0.1 / 0.5)', {'alpha': False}, 'color(--ucs 0.75 0.1 0.1)'), ('color(--ucs no...
class VarCompositeTest(unittest.TestCase): def test_var_composite(self): input_path = os.path.join(data_dir, 'varc-ac00-ac01.ttf') ttf = ttLib.TTFont(input_path) ttf.flavor = 'woff2' out = BytesIO() ttf.save(out) ttf = ttLib.TTFont(out) ttf.flavor = None ...
class DataMonitoring(): def __init__(self, config: Config, tracking: Optional[Tracking]=None, force_update_dbt_package: bool=False, disable_samples: bool=False, selector_filter: FiltersSchema=FiltersSchema()): self.execution_properties: Dict[(str, Any)] = {} self.config = config self.trackin...
class _Wizard(QtGui.QWizard): def __init__(self, parent, pyface_wizard): QtGui.QWizard.__init__(self, parent) self._pyface_wizard = pyface_wizard self._controller = pyface_wizard.controller self._ids = {} self.currentIdChanged.connect(self._update_controller) def addWizar...
class Sum(AST): def __init__(self, types, attributes=None): self.types = types self.attributes = (attributes or []) def __repr__(self): if (self.attributes is None): return ('Sum(%s)' % self.types) else: return ('Sum(%s, %s)' % (self.types, self.attributes...
class NameTableTest(unittest.TestCase): def test_getDebugName(self): table = table__n_a_m_e() table.names = [makeName('Bold', 258, 1, 0, 0), makeName('Gras', 258, 1, 0, 1), makeName('Fett', 258, 1, 0, 2), makeName('Sem Fraccoes', 292, 1, 0, 8)] self.assertEqual('Bold', table.getDebugName(258...
class OptionPlotoptionsArearangeStatesHoverMarker(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): sel...
def test_group_summaries_by_folder(): summaries = [('folder1/module1.py', 'Summary 1'), ('folder2/module2.py', 'Summary 2')] grouped = group_summaries_by_folder(summaries) assert (grouped == {'folder1': [('folder1/module1.py', 'Summary 1')], 'folder2': [('folder2/module2.py', 'Summary 2')]})
def test_sort(): o = _common.Sort(key='abc', direction=_common.Sort.Direction.ASCENDING) assert (o.key == 'abc') assert (o.direction == _common.Sort.Direction.ASCENDING) o2 = _common.Sort.from_flyte_idl(o.to_flyte_idl()) assert (o2 == o) assert (o2.key == 'abc') assert (o2.direction == _comm...
class ComponentManager(Service): logger = logging.getLogger('trinity.extensibility.component_manager.ComponentManager') _endpoint: EndpointAPI reason = None def __init__(self, boot_info: BootInfo, component_types: Sequence[Type[BaseIsolatedComponent]]) -> None: self._boot_info = boot_info ...
def find_or_build_fs_dir(settings, participant_label): fs_sub_dir = os.path.join(settings.fs_dir, 'sub-{}'.format(participant_label)) if os.path.isfile(os.path.join(fs_sub_dir, 'mri', 'wmparc.mgz')): logger.info('Found freesurfer outputs for sub-{}'.format(participant_label)) return else: ...
def extractAustincrustranslationBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (item['tags'] == []): titlemap = [('Isekai de Slow Life wo (Ganbou) Chapter ', 'Iseka...
def test_raises_if_email_doesnt_match_token_user(Fred): verifier = verifiers.EmailMatchesUserToken(User) token = Token(user_id=1, operation=TokenActions.RESET_PASSWORD) with pytest.raises(ValidationError) as excinfo: verifier(token, email='not really') assert (excinfo.value.attribute == 'email')...
class OptionSeriesPieMarker(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._config(num, js_type...
class Rules(QObject): __instance = None updated = pyqtSignal(int) LOG_TAG = '[Rules]: ' def instance(): if (Rules.__instance == None): Rules.__instance = Rules() return Rules.__instance def __init__(self): QObject.__init__(self) self._db = Database.instanc...
def lazy_import(): from fastly.model.apex_redirect_all_of import ApexRedirectAllOf from fastly.model.service_id_and_version import ServiceIdAndVersion from fastly.model.timestamps import Timestamps globals()['ApexRedirectAllOf'] = ApexRedirectAllOf globals()['ServiceIdAndVersion'] = ServiceIdAndVers...
class ChatShared(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string) return cls(**obj) def __init__(self, request_id: int, chat_id: int) -> None: self.request_id: int = request_id self.cha...
def graph(docs): G = nx.Graph() for doc in docs: for pair in pairs(doc): if ((pair[0][0], pair[1][0]) in G.edges()): G.edges[(pair[0][0], pair[1][0])]['weight'] += 1 else: G.add_edge(pair[0][0], pair[1][0], weight=1) return G
class SelfDestructBuiltIn(SolidityBuiltInFunction): def setup_impl(self, call_info: FunctionCallInfo): assert (len(call_info.arguments) == 1) destroy = ir.SelfDestruct(call_info.ast_node, call_info.arguments[0]) halt = ir.Halt(call_info.ast_node, False) self.cfg = CfgSimple.statement...
def get_print_string_code(string): code = '[-]' code += '>[-]' code += '<' prev_value = 0 for i in range(len(string)): current_value = ord(string[i]) code += get_set_cell_value_code(current_value, prev_value, zero_next_cell_if_necessary=False) code += '.' prev_value =...
class MyObject_labeled(event.Component): ('!a') def r1(self, *events): print(('r1 ' + ' '.join([ev.type for ev in events]))) ('!a:b') def r2(self, *events): print(('r2 ' + ' '.join([ev.type for ev in events]))) ('!a:a') def r3(self, *events): print(('r3 ' + ' '.join([ev.t...
def file_hash(*args, **kwargs): from .hashes import file_hash as new_file_hash message = '\n Importing file_hash from pooch.utils is DEPRECATED. Please import from the\n top-level namespace (`from pooch import file_hash`) instead, which is fully\n backwards compatible with pooch >= 0.1.\n ' warn...
class MarkdownTest(unittest.TestCase): def test_parses_normal_text_as_a_paragraph(self): self.assertEqual(parse('This will be a paragraph'), '<p>This will be a paragraph</p>') def test_parsing_italics(self): self.assertEqual(parse('_This will be italic_'), '<p><em>This will be italic</em></p>') ...
def gen_profiler(func_attrs, workdir, header_files, backend_spec): op_type = func_attrs['op'] file_pairs = [] elem_input_type = backend_spec.dtype_to_backend_type(func_attrs['inputs'][0]._attrs['dtype']) code = PROFILER_TEMPLATE.render(header_files=header_files, elem_input_type=elem_input_type, kernel=k...
class OptionPlotoptionsLineOnpointPosition(Options): def offsetX(self): return self._config_get(None) def offsetX(self, num: float): self._config(num, js_type=False) def offsetY(self): return self._config_get(None) def offsetY(self, num: float): self._config(num, js_type=...
class NumberListStringArgument(ArgumentDefinition): NOT_A_VALID_NUMBER_LIST_STRING = 'The input should be of the type: <b><pre>\n\t23,5.5,11,1.01,3\n</pre></b>i.e. numeric values separated by commas.' VALUE_NOT_A_NUMBER = "The value: '%s' is not a number." PATTERN = re.compile('^[0-9\\.\\-+, \\t]+$') de...
.parametrize('version_info', [(2, 1, 0), (2, 7, 0), (2, 7, 15), (3, 6, 0), (3, 6, 7), (3, 6, 7, 'candidate', 1)]) def test__get_stdlib_packages_unsupported(version_info: tuple[((int | str), ...)]) -> None: with mock.patch('sys.version_info', version_info), pytest.raises(UnsupportedPythonVersionError, match=re.escap...
def operator_contains(item, field, value): if (field not in item): return False try: ipaddress.ip_network(item[field]) ipaddress.ip_network(value) return operator_contains_network(item[field], value) except ValueError: pass return ((field in item) and (value in it...