code
stringlengths
281
23.7M
.django_db def test_extract_parent_from_hash_failure(): recipient_id = 'acb93cfc-e4f8-ecd5-5ac3-fa62f115e8f5-C' recipient_hash = TEST_RECIPIENT_PROFILES[recipient_id]['recipient_hash'] baker.make('recipient.RecipientProfile', **TEST_RECIPIENT_PROFILES[recipient_id]) expected_name = None expected_dun...
class ViewStridedOpTestCase(unittest.TestCase): def _gen_view_bmm_module(self, input0: Tensor, input1: Tensor, test_name: str, dtype: str, expected_num_tensors: int, expected_num_ops: int, num_bmms: int=1) -> Model: Ys = [] for i in range(num_bmms): Y = ops.bmm_rcr()(input0, input1) ...
_required _passes_test(is_installer, 'installer_registration') def installation(request, event_slug): installation_form = InstallationForm(event_slug, (request.POST or None), prefix='installation') hardware_form = HardwareForm((request.POST or None), prefix='hardware') forms = [installation_form, hardware_f...
def main(): if (sys.version_info[0] < 3): print('\nPython 3 is required!\n') return if (args.debug == True): import signal signal.signal(signal.SIGINT, debug_signal_handler) if os.path.exists(args.output): os.remove(args.output) db = sqlite3.connect(args.output) ...
class Test(unittest.TestCase): def testTypeCtor(self): c = fracttypes.Type(id=72, suffix='i', printf='%d', typename='int', default=0, slots=1, cname='int') self.assertEqual('i', c.suffix) def testTypeLists(self): self.assertEqual(len(fracttypes.typeObjectList), len(fracttypes.typeList)) ...
_renderer(wrap_type=DatasetSummaryMetric) class DatasetSummaryMetricRenderer(MetricRenderer): def _get_table(metric_result: DatasetSummaryMetricResult) -> BaseWidgetInfo: column_names = ['Metric', 'Current'] rows = (['id column', metric_result.current.id_column], ['target column', metric_result.curr...
def test_multiple_functions(mesh, pvd): V = FunctionSpace(mesh, 'DG', 0) P = FunctionSpace(mesh, 'CG', 1) f = Function(V, name='foo') g = Function(P, name='bar') pvd.write(f, g) with pytest.raises(ValueError): pvd.write(f) with pytest.raises(ValueError): pvd.write(g, f)
class Analyse(QObject): finished = Signal(str, str) progress_update = Signal(RunModelEvent) def __init__(self, ert: EnKFMain, target_fs: EnsembleAccessor, source_fs: EnsembleReader): QObject.__init__(self) self._ert = ert self._target_fs = target_fs self._source_fs = source_f...
_page.route('/table/change_config', methods=['POST']) def table_change_config(): res = check_uuid(all_data['uuid'], request.json['uuid']) if (res != None): return jsonify(res) if ('config_name' in request.json): config_names = _get_config_names(all_data['root_log_dir']) if (config_na...
class TestDSLBase(unittest.TestCase): def setUp(self): reset() def run_example(self, example: Example) -> None: _ExampleRunner(example, QuietFormatter(import_module_names=[__name__])).run() def run_all_examples(self): for each_context in Context.all_top_level_contexts: fo...
def crlf_get_url_method(uri, headers, scanid=None): crlf_payloads = fetch_crlf_payload() for payload in crlf_payloads: parsed_uri = (((((urllib.parse.urlparse(uri).scheme + '://') + urllib.parse.urlparse(uri).netloc) + urllib.parse.urlparse(uri).path) + '/') + payload) crlf_get_method = req.api_...
class TestOFPTableMod(unittest.TestCase): table_id = 3 config = def test_init(self): c = OFPTableMod(_Datapath, self.table_id, self.config) eq_(self.table_id, c.table_id) eq_(self.config, c.config) def _test_serialize(self, table_id, config): c = OFPTableMod(_Datapath, t...
def test_nested_pickling(tmp_path): def make_pickle() -> bytes: return pickle.dumps(hello_fn) pkl = make_pickle() assert (bytes(__name__, 'ascii') in pkl) assert (b'hello_fn' in pkl) ex = LocalExecutor(tmp_path) j = ex.submit(make_pickle) assert (j.result() == pkl)
def comp_appres(depth, res, a, n, srcpts=1, recpts=1, verb=1): AB = ((n + 1) * a) model = {'src': [((- a) / 2), (a / 2), 0, 0, 0.001, 0.001], 'rec': [(AB - (a / 2)), (AB + (a / 2)), (AB * 0), (AB * 0), 0.001, 0.001], 'depth': np.r_[(0, np.array(depth, ndmin=1))], 'freqtime': 1e-20, 'verb': verb, 'res': np.r_[(....
class Exon(): def __init__(self, name, gene_symbol, log2_fold_change=None, p_value=None, data=[]): self.name = str(name) self.gene_symbol = str(gene_symbol) if (log2_fold_change is not None): self.log2_fold_change = float(log2_fold_change) else: self.log2_fold...
def test_formatting_list(): instances = [OLS(), ('ols', OLS()), ('ols', OLS()), ['list', OLS()]] formatted = _format_instances(instances, False) strings = [] for i in formatted: assert isinstance(i, tuple) assert isinstance(i[0], str) assert isinstance(i[1], OLS) assert (...
_required _required def console(request, hostname): context = collect_view_data(request, 'vm_list') context['vm'] = get_vm(request, hostname) context['vms'] = vms = get_vms(request) context['vms_tags'] = get_vms_tags(vms) context['can_edit'] = request.user.is_admin(request) view_vm_console.send(...
def main(): print('\nmodule top();\n ') luts = LutMaker() lines = [] params_list = [] for (tile_name, sites) in gen_sites(): gen_fun = random.choice((ramb18, ramb18_2x, ramb36, fifo18, fifo18_ramb18, fifo36)) params_list.append(gen_fun(tile_name, luts, lines, sites)) for lut i...
class OptionPlotoptionsAreasplinerangeSonificationContexttracksMappingGapbetweennotes(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...
class flow_mod_failed_error_msg(error_msg): version = 3 type = 1 err_type = 5 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: ...
def divide(pitch_motif: PitchLine, duration_motif: DurationLine, n: int) -> List[Tuple[(PitchLine, DurationLine)]]: motifs = [] unit = (sum(duration_motif) / n) pm = [] dm = [] for (i, duration) in enumerate(duration_motif): current = sum(dm) tmp = (current + duration) residu...
def test_add_vectors(mocker): mock_qdrant_client = mocker.patch('qdrant_client.QdrantClient', autospec=True) mocker.patch('os.getenv', side_effect=(lambda x: 'dummy_value')) qdrant = Qdrant(env_file_path='/path/to/your/env/file') mock_qdrant_client.return_value.upsert.return_value = True vectors = [...
def test_topbottom(P2): u = TrialFunction(P2) v = TestFunction(P2) xs = SpatialCoordinate(P2.mesh()) a = (inner(grad(u), grad(v)) * dx) L = (((- inner(20, v)) * dx) + (inner(10, v) * ds_tb)) bc_expr = ((10 * (xs[2] - 0.5)) * (xs[2] - 0.5)) bcs = [DirichletBC(P2, bc_expr, 1), DirichletBC(P2, ...
def _unpack_string(code, read_fn): if ((ord(code) & 224) == 160): length = (ord(code) & (~ 224)) elif (code == b'\xd9'): length = _struct_unpack('B', read_fn(1))[0] elif (code == b'\xda'): length = _struct_unpack('>H', read_fn(2))[0] elif (code == b'\xdb'): length = _stru...
class OptionPlotoptionsVariablepieSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsVariablepieSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsVariablepieSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionPlotopti...
def write_json_file(file_name: str, results: list) -> str: now = datetime.now() timestamp = f'_{now.month}-{now.day}-{now.year}_{now.hour}-{now.minute}.json' file_path = (file_name + timestamp) click.secho(f'[*] Writing results to {file_path}', fg='green') with open(file_path, 'w') as f: jso...
class RealMatrix(BroadcastMatrixType, metaclass=MemoizedClass): def __init__(self, rows: int, columns: int) -> None: BroadcastMatrixType.__init__(self, real_element, rows, columns) def with_dimensions(self, rows: int, columns: int) -> BMGMatrixType: return RealMatrix(rows, columns)
def test_always_transact(accounts, tester, argv, web3, monkeypatch, history): owner = tester.owner() argv['always_transact'] = True height = web3.eth.block_number result = tester.owner() assert (owner == result) assert (web3.eth.block_number == height == len(history)) monkeypatch.setattr('br...
class LinkerdHeaderMapping(AmbassadorTest): target: ServiceType def init(self): self.target = HTTP() self.target_no_header = HTTP(name='noheader') self.target_add_linkerd_header_only = HTTP(name='addlinkerdonly') def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, ...
class bsn_header(experimenter): subtypes = {} version = 6 type = 4 experimenter = 6035143 def __init__(self, xid=None, subtype=None): if (xid != None): self.xid = xid else: self.xid = None if (subtype != None): self.subtype = subtype ...
def _mutate_array_js(array, ev): is_nd = (hasattr(array, 'shape') and hasattr(array, 'dtype')) mutation = ev.mutation index = ev.index objects = ev.objects if (is_nd is True): if (mutation == 'set'): raise NotImplementedError('Cannot set nd array in-place') elif (mutation...
def test_find_width_returns_empty_array_with_too_big_threshold(data_width): result = scared.signal_processing.find_width(data_width, scared.signal_processing.Direction.POSITIVE, 2, 10) assert np.array_equal(result, np.empty((0, 2))) result = scared.signal_processing.find_width(data_width, scared.signal_proc...
def test_environ(): environ = Environ() environ['TESTING'] = 'True' environ['GONE'] = '123' del environ['GONE'] assert (environ['TESTING'] == 'True') assert ('GONE' not in environ) with pytest.raises(EnvironError): environ['TESTING'] = 'False' with pytest.raises(EnvironError): ...
def mk_suggested_vote(concise_casper, mk_vote): def mk_suggested_vote(validator_index, validation_key): target_hash = concise_casper.recommended_target_hash() target_epoch = concise_casper.current_epoch() source_epoch = concise_casper.recommended_source_epoch() return mk_vote(validat...
class Flag(): def __init__(self, aliases, description, required=False, dtype='bool'): if isinstance(aliases, str): self.aliases = [aliases] else: self.aliases = aliases self.description = description self.required = required self.dtype = dtype ...
def parse_molden_atoms(data): atoms = list() coords = list() nuc_charges = list() for atom in data['atoms']: atoms.append(atom['symbol']) coords.extend(atom['xyz']) Z = atom['atomic_number'] nuc_charges.append(Z) atoms = tuple(atoms) coords = np.array(coords, dtyp...
class MonoThreadEpisodeBatcher(): def __init__(self, create_agent, agent_args, create_env, env_args): self.agent = create_agent(**agent_args) assert (not self.agent.require_history()) self.env = create_env(**env_args) self.n_envs = self.env.n_envs def execute(self, agent_info=Dic...
def autodoc_post_process_docstring(app, what, name, obj, options, lines): try: if ansi_clean: for (il, line) in enumerate(lines): lines[il] = ansi_clean(line) def _sub_codeblock(match): code = match.group(1) return '::\n\n {}'.format('\n '.jo...
def build(abcd, node, net, gv, outfile, tpl=template_html, **args): abcd = ABCD2HTML(node) pnet = Net2HTML(net, gv, abcd) d = {'filename': node.st.filename, 'css': template_css, 'jscode': template_jscode, 'headers': template_headers, 'abcd': abcd.html(), 'tree': pnet.html(), 'svg': pnet.svg()} d.update(...
def as_ctrait(obj): if (isinstance(obj, type) and hasattr(obj, 'instantiate_and_get_ctrait')): return obj.instantiate_and_get_ctrait() elif ((not isinstance(obj, type)) and hasattr(obj, 'as_ctrait')): return obj.as_ctrait() else: raise TypeError('Object {!r} does not support conversi...
def fix_citations(ao_no, citation_type, citations): CITATION_EXCLUDE_LOOKUP = {'2017-03': {'ao': ['2010-11', '2011-12', '2015-16']}, '2019-11': {'statute': [(52, '301')]}} CITATION_INCLUDE_LOOKUP = {'1999-40': {'regulation': [(11, 110, 3)]}, '2019-14': {'regulation': [(11, 102, 1), (11, 102, 6), (11, 104, 1), (...
class PythonicProtocolSpecification(): def __init__(self) -> None: self.speech_acts = {} self.all_performatives = [] self.all_unique_contents = {} self.all_custom_types = [] self.custom_custom_types = {} self.initial_performatives = [] self.reply = {} ...
def __find_commit_message__(sha): git_show_r = subprocess.Popen(filter(None, ['git', 'show', '-s', '--pretty=%B', '-w', sha]), bufsize=1, stdout=subprocess.PIPE).stdout commit_message = git_show_r.read() git_show_r.close() commit_message = commit_message.strip().decode('unicode_escape', 'ignore') co...
def run_yamllint(path, indent=0): path = Path(path) try: import yamllint.config import yamllint.linter except ImportError: return '' result = [] with path.open('r', encoding='utf-8') as f: problems = yamllint.linter.run(f, yamllint.config.YamlLintConfig(json.dumps(YAM...
class TestStylesheetsCSS(util.PluginTestCase): def setup_fs(self): config = self.dedent("\n matrix:\n - name: css\n sources:\n - '{}/**/*.txt'\n aspell:\n lang: en\n d: en_US\n hunspell:\n ...
class Command(BaseCommand): def handle(self, *args, **kwargs): update_bnf_table() client = BQClient('hscic') table = client.get_table('practices') table.insert_rows_from_pg(models.Practice, schemas.PRACTICE_SCHEMA) table = client.get_table('presentation') table.insert...
def find_ancestors(starting_resource, full_name): ancestor_resources = [starting_resource] resources = utils.get_resources_from_full_name(full_name) for (resource_type, resource_id) in resources: if ((resource_type == starting_resource.type) and (resource_id == starting_resource.id)): co...
def test_interference_graph_of_test_loop_test1_without_dead_code(construct_graph_test_loop_1, variable_x, variable_u, variable_v, aliased_variable_y): (nodes, cfg) = construct_graph_test_loop_1 nodes[1].remove_instruction(Phi(variable_x[3], [variable_x[2], variable_x[4]])) nodes[1].remove_instruction(Phi(va...
class FinanceForecastEvent(BaseDocType): id = Keyword() timestamp = Date() reportPeriod = Date() securityId = Keyword() type = Keyword() description = Keyword() preEPS = Float() changeStart = Float() change = Float() class Meta(): index = 'finance_forecast_event' ...
def test_too_few_zvals(single_cell_roff_grid): roff_grid = single_cell_roff_grid roff_grid.split_enz = np.full(8, fill_value=4, dtype=np.uint8).tobytes() roff_grid.zvals = np.ones(5, dtype=np.float32) with pytest.raises(ValueError, match='size of zdata'): roff_grid.xtgeo_zcorn()
class OptionSeriesVennClusterZones(Options): def className(self): return self._config_get(None) def className(self, text: str): self._config(text, js_type=False) def from_(self): return self._config_get(None) _.setter def from_(self, num: float): self._config(num, js_...
def test_missing_values_param_functionality(): df = {'Name': ['tom', 'nick', 'krish', 'jack'], 'City': ['London', 'Manchester', 'Liverpool', 'Bristol'], 'Age': [20, 21, 19, 18], 'Marks': [0.9, 0.8, 0.7, 0.6], 'dob': pd.date_range('2020-02-24', periods=4, freq='T'), 'const_feat_num': [1, 1, 1, np.nan], 'const_feat_c...
def main(): parser = argparse.ArgumentParser(description='LiteX SoC on Arty') builder_args(parser) soc_sdram_args(parser) vivado_build_args(parser) args = parser.parse_args() cls = MinSoC soc = cls(**soc_sdram_argdict(args)) builder = Builder(soc, **builder_argdict(args)) builder.bui...
def usage(): print('++') print((((('| ' + sys.argv[0]) + ' Version ') + vernum) + ' |')) print('| This program is free software; you can redistribute it and/or modify |') print('| it under the terms of the GNU General Public License as published by |') print('| t...
def base_keyword(name, explicit_prefix=False, require_whitespace=False): base_kwd = regex_item(((name + '\\b') + ('(?=\\s)' if require_whitespace else ''))) if (explicit_prefix and (name in (reserved_vars + allow_explicit_keyword_vars))): return combine((Optional(explicit_prefix.suppress()) + base_kwd))...
class RxMessageBroker(object): def __init__(self, owner, backend: 'Backend'): self.owner = owner self.backend = backend self.effective_log_level = backend.log_level self.cond = Condition() self.rx_connectable = dict() self.node_io = dict() self.disconnected = ...
('value,expected', [param('abc', Key(key_or_group='abc'), id='abc'), param('abc/cde', Key(key_or_group='abc/cde'), id='abc/cde'), param('abc.cde', Key(key_or_group='abc.cde'), id='abc.cde'), param('ab-c/d-ef', Key(key_or_group='ab-c/d-ef'), id='ab-c/d-ef'), param('ab-c.d-ef', Key(key_or_group='ab-c.d-ef'), id='ab-c.d-e...
class TestSearchIndex(unittest.TestCase): def test_jaccard(self): sets = [[1, 2, 3], [3, 4, 5], [2, 3, 4], [5, 6, 7]] index = SearchIndex(sets, similarity_func_name='jaccard', similarity_threshold=0.1) results = index.query([3, 5, 4]) correct_results = set([(1, 1.0), (0, 0.2), (2, 0....
class TestDatetime(unittest.TestCase): def test_default(self): obj = HasDatetimeTraits() self.assertEqual(obj.simple_datetime, None) self.assertEqual(obj.epoch, UNIX_EPOCH) self.assertEqual(obj.alternative_epoch, NT_EPOCH) def test_assign_datetime(self): test_datetime = d...
class TestAndroidApp(BaseProjectManagementTest): _GET_METADATA_URL = ' _SET_DISPLAY_NAME_URL = ' _GET_CONFIG_URL = ' _ADD_CERT_URL = ' _LIST_CERTS_URL = ' _DELETE_SHA_1_CERT_URL = ' _DELETE_SHA_256_CERT_URL = ' def android_app(self): return project_management.android_app('1::andr...
class HTTPProxyTestCase(AioHTTPTestCase): def setUp(self): super().setUp() self.endpoint = '/dns' self.dnsq = dns.message.make_query(qname='foo.example.com', rdtype='A') self.dnsq.id = 0 def get_args(self): return ['--listen-port', '0', '--level', 'DEBUG', '--listen-addre...
def get_bert_feature(text, word2ph, device=config.bert_gen_config.device): if ((sys.platform == 'darwin') and torch.backends.mps.is_available() and (device == 'cpu')): device = 'mps' if (not device): device = 'cuda' if (device not in models.keys()): models[device] = DebertaV2Model.fr...
class TimeMonitor(Monitor, ABC): start: pydantic.NonNegativeFloat = pydantic.Field(0.0, title='Start Time', description='Time at which to start monitor recording.', units=SECOND) stop: pydantic.NonNegativeFloat = pydantic.Field(None, title='Stop Time', description='Time at which to stop monitor recording. If n...
class PopupControl(HasPrivateTraits): control = Instance(wx.Window) width = Int() height = Int() resizable = Bool(False) value = Any() closed = Event() popup = Instance(wx.Window) def __init__(self, **traits): super().__init__(**traits) style = wx.SIMPLE_BORDER if...
class DEP001MissingDependencyViolation(Violation): error_code: ClassVar[str] = 'DEP001' error_template: ClassVar[str] = "'{name}' imported but missing from the dependency definitions" issue: Module def get_error_message(self) -> str: return self.error_template.format(name=self.issue.name)
def test_bad_init_error(utils): bad0 = {} bad1 = {'elements_in': []} bad2 = {'elements_in': None} good = {'elements_in': ['selname']} with pytest.raises(InvalidAnalyserConfigError, match="must contain an 'elements_in' indicating the analyser's input"): no_elements_in = ErrorThrowingAnalyser(...
class TestParseVersion(TestFunction, unittest.TestCase): cases = [(['1'], ((1, 0, 0), None, 0)), (['1.0'], ((1, 0, 0), None, 0)), (['1.0.0'], ((1, 0, 0), None, 0)), (['1.0.1'], ((1, 0, 1), None, 0)), (['1.2.3'], ((1, 2, 3), None, 0)), (['1.2.3r'], ((1, 2, 3), 'r', 0)), (['1.2.3r1'], ((1, 2, 3), 'r', 1)), (['1.2.3r1...
.parametrize('arr,arr_type', [(numpy.zeros(0, dtype=numpy.float32), Floats1d), (numpy.zeros((0, 0), dtype=numpy.float32), Floats2d), (numpy.zeros((0, 0, 0), dtype=numpy.float32), Floats3d), (numpy.zeros((0, 0, 0, 0), dtype=numpy.float32), Floats4d), (numpy.zeros(0, dtype=numpy.int32), Ints1d), (numpy.zeros((0, 0), dtyp...
class OptionSeriesPictorialDataDatalabelsTextpath(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._conf...
class OptionPlotoptionsCylinderSonificationDefaultspeechoptionsMappingPitch(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, t...
class OptionPlotoptionsBubbleSonificationContexttracksMappingRate(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 OptionPlotoptionsArcdiagramSonificationDefaultinstrumentoptionsMappingHighpassResonance(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 OptionPlotoptionsVectorSonificationTracksActivewhen(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, num: float): ...
class SkeletonDetector(object): def __init__(self, model='cmu', image_size='432x368'): assert (model in ['mobilenet_thin', 'cmu']) (self._w, self._h) = _get_input_img_size_from_string(image_size) self._model = model self._resize_out_ratio = 4.0 self._config = _set_config() ...
class RelationshipMutualAuthentication(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(): l...
def test_hover_parameter_eqnospace(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = ((test_dir / 'hover') / 'parameters.f90') string += hover_req(file_path, 11, 28) (errcode, results) = run_request(string, fortls_args=['--sort_keywords']) assert (errcode == 0) ...
.parametrize('request_1__group_by', ['a']) .parametrize('request_2__group_by', ['b']) def test_version_user_post(dashboard_user, request_1, request_2, endpoint): response = dashboard_user.post('dashboard/api/version_user/{0}'.format(endpoint.id), json={'data': {'users': ['a', 'b'], 'versions': [request_1.version_re...
def viz_synth_sample(gt_mel, gt_pitch, predict_mel, predict_mel_len, gt_mel_len, vocoder, return_image=False): predict_mel_len = predict_mel_len.item() gt_mel_len = gt_mel_len.item() pitch = (gt_pitch[:gt_mel_len] if (gt_pitch is not None) else None) mel_target = gt_mel[:gt_mel_len].float().detach().T ...
def test_reject_recursive_repeats_multithreaded(): _recursive_repeats def recurse(sleep_now): time.sleep(sleep_now) try: recurse(0.05) return True except ValueError: return False thd1 = spawn(recurse, 0) thd2 = spawn(recurse, 0.02) assert (...
def test_aliased_problems_10(): (x0, x1, x2, x3) = [Variable('x', Integer.int32_t(), i) for i in range(4)] x0.is_aliased = True (y0, y1, y2) = [Variable('y', Integer.int32_t(), i, is_aliased=True) for i in range(3)] cfg = ControlFlowGraph() cfg.add_nodes_from([(start := BasicBlock(0, instructions=[A...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = None fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {...
('foremast.datapipeline.datapipeline.boto3.Session.client') ('foremast.datapipeline.datapipeline.get_details') ('foremast.datapipeline.datapipeline.get_properties') def test_good_set_pipeline_definition(mock_get_properties, mock_get_details, mock_boto3): generated = {'project': 'test'} properties = copy.deepcop...
class OptionSeriesTreemapSonificationTracksMappingVolume(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._c...
def _circlify_level(data, target_enclosure, fields, level=1): all_circles = [] if (not data): return all_circles circles = _handle(data, 1, fields) packed = pack_A1_0([circle.r for circle in circles]) enclosure = enclose(packed) assert (enclosure is not None) for (circle, inner_circl...
def create_index(index_name=None): index_name = (index_name or CASE_INDEX) body = {} aliases = {} body.update({'settings': ANALYZER_SETTING}) if (index_name in INDEX_DICT.keys()): delete_index(index_name) (mapping, alias1, alias2) = INDEX_DICT.get(index_name)[:3] body.update(...
class OptionSeriesNetworkgraphMarkerStates(Options): def hover(self) -> 'OptionSeriesNetworkgraphMarkerStatesHover': return self._config_sub_data('hover', OptionSeriesNetworkgraphMarkerStatesHover) def inactive(self) -> 'OptionSeriesNetworkgraphMarkerStatesInactive': return self._config_sub_data...
class EsRaceStore(RaceStore): INDEX_PREFIX = 'rally-races-' def __init__(self, cfg, client_factory_class=EsClientFactory, index_template_provider_class=IndexTemplateProvider): super().__init__(cfg) self.client = client_factory_class(cfg).create() self.index_template_provider = index_temp...
class ByteStringDecoder(SingleDecoder): is_dynamic = True def decoder_fn(data): return data def read_data_from_stream(self, stream): data_length = decode_uint_256(stream) padded_length = ceil32(data_length) data = stream.read(padded_length) if self.strict: ...
class Plugin(plugin.PluginProto): PLUGIN_ID = 14 PLUGIN_NAME = 'Environment - SI7021/HTU21D' PLUGIN_VALUENAME1 = 'Temperature' PLUGIN_VALUENAME2 = 'Humidity' def __init__(self, taskindex): plugin.PluginProto.__init__(self, taskindex) self.dtype = rpieGlobals.DEVICE_TYPE_I2C s...
def test_unlink(ipfs_mock, np_path, mocker): ethpm.install_package(np_path, 'ipfs://testipfs-math') mocker.spy(ethpm, 'remove_package') cli_ethpm._unlink(np_path, 'math') assert (ethpm.remove_package.call_count == 1) assert np_path.joinpath('contracts/math').exists() cli_ethpm._unlink(np_path, '...
def test_reverse_iso8601_datetime(): dates = [('2011-01-01T00:00:00+00:00', datetime(2011, 1, 1, tzinfo=pytz.utc)), ('2011-01-01T23:59:59+00:00', datetime(2011, 1, 1, 23, 59, 59, tzinfo=pytz.utc)), ('2011-01-01T23:59:59.001000+00:00', datetime(2011, 1, 1, 23, 59, 59, 1000, tzinfo=pytz.utc)), ('2011-01-01T23:59:59+0...
class OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 map...
class OptionSeriesSolidgaugeDataDatalabelsTextpath(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._con...
.parametrize('metric,expected', [(None, 1), ('r2', 1), (get_scorer('neg_mean_squared_error'), 0)], ids=['none', 'R2', 'MSE']) def test_cross_val_score_vector(trend, metric, expected): (coords, data) = trend[:2] model = Vector([Trend(degree=1), Trend(degree=1)]) scores = cross_val_score(model, coords, (data,...
.AnalysisPluginTestConfig(plugin_class=AnalysisPlugin) class TestCweCheckerFunctions(): def test_parse_cwe_checker_output(self, analysis_plugin): test_data = '[\n {\n "name": "CWE676",\n "version": "0.1",\n "addresses": [\n ""\n ...
class CheckerThread(Thread): def __init__(self, parent, url): Thread.__init__(self) self.daemon = True self._armed = True self._url = url self._parent = parent def shutdown(self): if self.result: self._armed = False self.result.terminate() ...
class TDMPCLearner(acme.Learner): def __init__(self, spec: specs.EnvironmentSpec, networks: tdmpc_networks.TDMPCNetworks, random_key: jax.random.PRNGKeyArray, replay_client: reverb.Client, iterator: Iterator[TDMPCReplaySample], *, optimizer: optax.GradientTransformation, discount: float=0.99, min_std: float=0.05, p...
class ASDLParser(spark.GenericParser, object): def __init__(self): super(ASDLParser, self).__init__('module') def typestring(self, tok): return tok.type def error(self, tok): raise ASDLSyntaxError(tok.lineno, tok) def p_module_0(self, arg): (module, name, version, _0, _1)...
def test_edit_event_null_field(db, client, admin_jwt): event = get_event(db) assert (event.location_name == 'Amsterdam') data = json.dumps({'data': {'type': 'event', 'id': str(event.id), 'attributes': {'location-name': None}}}) response = client.patch(f'/v1/events/{event.id}', content_type='application/...
_os(*metadata.platforms) def main(): winword = 'C:\\Users\\Public\\winword.exe' user32 = 'C:\\Windows\\System32\\user32.dll' dll = 'C:\\Users\\Public\\wmiutils.dll' ps1 = 'C:\\Users\\Public\\Invoke-ImageLoad.ps1' wmiprvse = 'C:\\Users\\Public\\WmiPrvSE.exe' common.copy_file(EXE_FILE, winword) ...