text
stringlengths
15
7.82k
ids
listlengths
1
7
def METHOD_NAME(self): # Test example from page 4 of # https://www.haystack.mit.edu/tech/vlbi/mark5/docs/230.3.pdf stream_hex = '0000 002D 0330 0000' + 'FFFF FFFF' + '4053 2143 3805 5' self.crc_hex = '284' self.crc12 = CRC(0x180f) self.crcstack12 = CRCStack(0x180f) self.stream_hex = stream_h...
[ 102, 2 ]
def METHOD_NAME(tokenizer, train_batch_size, eval_batch_size): # Load dataset train_dataset, test_dataset = load_dataset("imdb", split=["train", "test"]) # Preprocess train dataset train_dataset = train_dataset.map( lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=T...
[ 19, 4146 ]
def METHOD_NAME(self): return self.METHOD_NAME
[ 803, 3547 ]
async def METHOD_NAME(data, objectService): """We can upload a small amount of literal data""" name = f"taskcluster/test/client-py/{taskcluster.slugid.v4()}" await upload.uploadFromBuf( projectId="taskcluster", name=name, contentType="text/plain", contentLength=len(data), ...
[ 74, 3217, 8915, 6107, 9 ]
def METHOD_NAME(self, name): return self.has_callback(name) and self.num_callbacks(name) > 0
[ 5334, 1076 ]
def METHOD_NAME(y: Float64Array, x: Float64Array) -> Float64Array: """ Projection of y on x from y Parameters ---------- y : ndarray Array to project (nobs by nseries) x : ndarray Array to project onto (nobs by nvar) Returns ------- ndarray Projected values of...
[ 5786 ]
def METHOD_NAME(current_actor_context): """ Report if there's configuration for a type we don't recognize. """ current_actor_context.feed(IfCfg( filename="/NM/ifcfg-pigeon0", properties=(IfCfgProperty(name="TYPE", value="AvianCarrier"),) )) current_actor_context.feed(INITSCRIPTS_...
[ 9, 17622, 46, 44 ]
def METHOD_NAME(self): """test label formatter for histogram for None""" formatted_label = self.histogram._format_bin_labels(None) assert formatted_label == "null and up"
[ 9, 6069, 636, 2931, 98 ]
def METHOD_NAME(self): return all( self.datasets[key].METHOD_NAME for key in self.datasets )
[ 1466, 1047, 261, 568 ]
def METHOD_NAME() -> None: """ Main function """ # Dir path if len(sys.argv) != 2: sys.stderr.write(f'Usage: {sys.argv[0]} <setup_dir>\n') exit(2) dirpath = sys.argv[1] # Dir non existence if os.path.exists(dirpath): sys.stderr.write(f'Directory: {dirpath} already...
[ 57 ]
def METHOD_NAME(scene): img = ImageMobject( np.uint8([[63, 0, 0, 0], [0, 127, 0, 0], [0, 0, 191, 0], [0, 0, 0, 255]]), ) img.height = 2 img1 = img.copy() img2 = img.copy() img3 = img.copy() img4 = img.copy() img5 = img.copy() img1.set_resampling_algorithm(RESAMPLING_ALGORITHM...
[ 9, 660, 4239 ]
def METHOD_NAME(devName): devName = resolveDevName(devName) return os.path.exists(os.path.join("/sys/devices/virtual/block/", devName))
[ 137, 162, 398 ]
def METHOD_NAME(elec_txt_dataframe): """Parse keys from EIA series_id string.""" input_ = elec_txt_dataframe.iloc[[2], :] expected = pd.DataFrame( { "series_code": ["RECEIPTS_BTU"], "fuel_agg": ["NG"], "geo_agg": ["US"], "sector_agg": ["2"], ...
[ 9, 297, 219, 280, 4045, 147 ]
def METHOD_NAME(self, context, data_dict, fields_types, query_dict): '''Modify queries made on datastore_delete The overall design is that every IDatastore extension will receive the ``query_dict`` with the modifications made by previous extensions, then it can add/remove stuff into it before passing it...
[ 914, 34 ]
f METHOD_NAME(self):
[ 9, 2469 ]
def METHOD_NAME(plugins: list[dict[str, str]]) -> list[dict[str, str]]: plugins_dict: dict[str, dict[str, str]] = {} for plugin in plugins: # Plugins from later indexes override others plugin["name"] = plugin["name"].lower() plugins_dict[plugin["name"]] = plugin return sorted(plugins...
[ 3686, 1294 ]
def METHOD_NAME(self): self.file.METHOD_NAME()
[ 1462 ]
def METHOD_NAME(train_data, train_labels, predict_data, nClasses): # Create an algorithm object and call compute train_algo = d4p.bf_knn_classification_training(nClasses=nClasses, fptype="float") train_result = train_algo.METHOD_NAME(train_data, train_labels) # Create an algorithm object and call comput...
[ 226 ]
def METHOD_NAME(self): request = Mock(method="BADWOLF") view = Mock() obj = Mock() perm_obj = KolibriAuthPermissions() self.assertFalse(perm_obj.has_object_permission(request, view, obj))
[ 9, 1068, 377, 103 ]
def METHOD_NAME(self, *args, **kwargs): public_doc_records = public_doc_query() for doc in public_doc_records: pdf_name = create_name(doc) # We don't want to delete the original so we are not moving and we can't rename and copy at the same time try: temp_name = grab_doc(pdf_n...
[ 276 ]
def METHOD_NAME(bucket, file_name): """ Exposes helper method without breaking existing bindings/dependencies """ return storage_service_key_source_function(bucket, file_name)
[ 948, 549, 59 ]
def METHOD_NAME(argv, log=False): """Call nvcc with arguments assembled from argv. Args: argv: A list of strings, possibly the argv passed to main(). log: True if logging is requested. Returns: The return value of calling os.system('nvcc ' + args) """ src_files = [f for f in argv if ...
[ 4311, 15543 ]
def METHOD_NAME(fmt, *args): s = fmt.format(*args) return (s, len(s))
[ 6569, 275, 772 ]
def METHOD_NAME(list_name, msgid): return "{}/arch/msg/{}/{}".format(settings.MAILING_LIST_ARCHIVE_URL, list_name, hash_list_message_id(list_name, msgid))
[ 363, 277, 274 ]
def METHOD_NAME(self, model): data = model.db.get_unit_operation_parameters("co2_addition") model.fs.unit.load_parameters_from_database() assert model.fs.unit.energy_electric_flow_vol_inlet.fixed assert ( model.fs.unit.energy_electric_flow_vol_inlet.value == data["energy_electric_flow_vo...
[ 9, 557, 386 ]
def METHOD_NAME(self, train_conf, vars_conf): new_opt_confs = [] for param_group in self.param_groups: assert ( param_group["contiguous_params"] != True ), "contiguous_params cannot be used in graph" optimizer_conf = train_conf.optimizer_conf.add() lr = ( ...
[ 567, 2546, 43, 303 ]
def METHOD_NAME(self): """Return the precached index of the object. :rtype: int """ # Get the index of the object in its precache table METHOD_NAME = string_tables[self.precache_table][self._path] # Is the object precached? if METHOD_NAME != INVALID_STRING_INDEX: # Return the precach...
[ 724 ]
def METHOD_NAME(self, method, device): """Test pershot save density matrix instruction""" backend = self.backend(method=method, device=device) # Stabilizer test circuit circ = QuantumCircuit(1) circ.x(0) circ.reset(0) circ.h(0) circ.sdg(0) # Target statevector target = qi.Density...
[ 9, 73, 2915, 430, 14123 ]
def METHOD_NAME(self, path, mode): path = path.decode(self.encoding) _evil_name(path) return errno_call(self._context, os.METHOD_NAME, path, mode)
[ 8347 ]
def METHOD_NAME(self) -> str: """ Resource Name. """ return pulumi.get(self, "name")
[ 156 ]
def METHOD_NAME(self): return bool(self.__flags & DEF_BOUND)
[ 137, 125 ]
def METHOD_NAME(cfg, in_channels): return RetinaNetModule(cfg, in_channels)
[ 56, 18193 ]
def METHOD_NAME(pip_version=None): # type: (Optional[PipVersionValue]) -> bool pip_ver = pip_version or PipVersion.DEFAULT return pip_ver.version < Version("23.2")
[ 1466, 3116, 1836 ]
def METHOD_NAME(self,nb,data=None): tab_num = nb.get_current_page() tab = nb.get_nth_page(tab_num) alloc = tab.get_allocation() x, y, w, h = (alloc.x, alloc.y, alloc.width, alloc.height) pixbuf = self.svg.get_pixbuf_sub(f'#layer{tab_num}').scale_simple(w-10, h-10, GdkPixbuf.InterpType.BILINEAR) ...
[ 69, 10401 ]
def METHOD_NAME(d: datetime) -> datetime: # There are two types of datetime objects in Python: naive and aware # Assume any dbt snapshot timestamp that is naive is meant to represent UTC if d is None: return d elif is_aware(d): return d else: return d.replace(tzinfo=pytz.UTC)
[ 197, 24, 2894 ]
def METHOD_NAME(cql, namespaces, fes_version='1.0'): """transforms Common Query Language (CQL) query into OGC fes1 syntax""" filters = [] tmp_list = [] logical_op = None LOGGER.debug('CQL: %s', cql) if fes_version.startswith('1.0'): element_or = 'ogc:Or' element_and = 'ogc:And' ...
[ -1 ]
def METHOD_NAME(redis, key: str) -> Any: """ Gets a JSON serialized value from the cache. """ cached_value = redis.get(key) if cached_value: logger.debug(f"Redis Cache - hit {key}") try: deserialized = json.loads(cached_value) return deserialized excep...
[ 19, 763, 175, 59 ]
def METHOD_NAME(self) -> None: self.store.METHOD_NAME() try: flask.current_app.config.METHOD_NAME() except RuntimeError: pass
[ 537 ]
def METHOD_NAME(self, description, uuids=None, report=None): """Check that the delta description is correct.""" report = report if report is not None else self.report uuids = sorted(uuids or [REPORT_ID, NOTIFICATION_DESTINATION_ID]) self.assertEqual({"uuids": uuids, "email": self.email, "description": d...
[ 638, 1364 ]
def METHOD_NAME(mocker, cobbler_api): # Arrange mock_builtins_open = mocker.patch("builtins.open", mocker.mock_open()) mock_system = System(cobbler_api) mock_system.name = "test_manager_regen_ethers_system" mock_system.interfaces = {"default": NetworkInterface(cobbler_api)} mock_system.interface...
[ 9, 722, 9351, -1 ]
async def METHOD_NAME(self, key, user=None, is_iter=False): """ Process a dict lookup message """ logging.debug("Looking up {} for {}".format(key, user)) orig_key = key # Priv and shared keys are handled slighlty differently key_type, key = key.decode("utf8").split("/", 1) try: resul...
[ 356, 1906 ]
def METHOD_NAME(self): """Check that all foreign keys are created correctly""" # filter questions on survey questions = list(StudentQuestionBase.objects.filter(survey=self.survey)) self.assertTrue(self.grading_q.pk in [q.pk for q in questions]) self.assertTrue(self.slider_q.pk in [q.pk for q in ques...
[ 9, -1, 219 ]
def METHOD_NAME(self): self.args = [ "command_dummy", "--host", TESTSERVER_URL + "/service?request=GetCapabilities", ] with open(SERVICE_EXCEPTION_FILE, "rb") as fp: capabilities_doc = fp.read() with mock_httpd( TESTSERVER_ADDRESS, [ ...
[ 9, 549, 442 ]
def METHOD_NAME(self): if LXML_PRESENT: self.assertEqual(registry.lookup('html'), LXMLTreeBuilder) self.assertEqual(registry.lookup('xml'), LXMLTreeBuilderForXML) else: self.assertEqual(registry.lookup('xml'), None) if HTML5LIB_PRESENT: self.assertEqual(registry.looku...
[ 9, 1906, 604, 7469, 44 ]
def METHOD_NAME(n_fp, order): """ Prepare DOF permutation vector for each possible facet orientation. """ from sfepy.base.base import dict_to_array if n_fp == 2: mtx = make_line_matrix(order) ori_map = ori_line_to_iter fo = order - 1 elif n_fp == 3: mtx = make_tri...
[ 19, 1890, 7212, 13501 ]
def METHOD_NAME(self) -> List[NamedUser]: ...
[ 9579 ]
def METHOD_NAME(): model = SemanticSegmentation(2) model.eval() model.serve()
[ 9, 3124 ]
def METHOD_NAME(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
[ 24, 3 ]
def METHOD_NAME(self, max_norm, aggregate_norm_fn=None): """Clips gradient norm.""" return utils.clip_grad_norm_(self.params, max_norm, aggregate_norm_fn)
[ 4226, 140, 387 ]
def METHOD_NAME(agent_args, technologies, stock): from muse.agents.agent import Agent from muse.agents.factories import create_agent agent_args["share"] = "agent_share_zero" agent = create_agent( agent_type="Retrofit", technologies=technologies, capacity=stock.capacity, s...
[ 9, 946, -1, 61, -1 ]
def METHOD_NAME(self, handler: ErrorHandler[object] | None) -> None: ...
[ 0, 168, 1519 ]
def METHOD_NAME(self): pass
[ 709, 710 ]
def METHOD_NAME( repo, settings, fs=None, prefix: Optional[Tuple[str, ...]] = None, hash_name: Optional[str] = None, **kwargs, ): from dvc.fs import get_cloud_fs if not settings: return None cls, config, fs_path = get_cloud_fs(repo.config, **settings) fs = fs or cls(**con...
[ 19, -1 ]
def METHOD_NAME(self): pass
[ 709, 710 ]
def METHOD_NAME(self, skip_run=False, executable=None): # start with the run command cmd = [] if skip_run else self.build_run_cmd(executable=executable) # add arguments and insert dummary key value separators which are replaced with "=" later for key, value in self.args: cmd.extend([key, self.ar...
[ 56 ]
def METHOD_NAME(self): raise ValueError("this dispatcher is not writable")
[ 276, 77, 417 ]
f METHOD_NAME(self):
[ 19, 2456 ]
def METHOD_NAME(self): """Exporter EntryPoint to call.""" return self.get_record_value('entry_point')
[ 475, 1669 ]
def METHOD_NAME(scope): if scope == "list": return [None] elif scope in ["create", "import:backup"]: return [ { "owner": {"id": random.randrange(400, 500)}, "assignee": {"id": random.randrange(500, 600)}, "organization": {"id": random.r...
[ 1614 ]
def METHOD_NAME(input_event, relation, text_encoder, max_e1, max_r, force): abort = False e1_tokens, rel_tokens, _ = data.conceptnet_data.do_example(text_encoder, input_event, relation, None) if len(e1_tokens) > max_e1: if force: XMB = torch.zeros(1, len(e1_tokens) + max_r).long().to(set...
[ 0, -1, 1461 ]
def METHOD_NAME(self): return self.maxsize > 0 and len(self.queue) == self.maxsize
[ 324 ]
def METHOD_NAME(self, item, identity_field=None): identity = {} from_ = item if isinstance(item, dict) and 'data' in item: from_ = item['data']['message'][identity_field] identity['username'] = from_.get('username', None) identity['email'] = None identity['name'] = from_.get('first_name'...
[ 19, 4449, 2989 ]
def METHOD_NAME(self): return self.client.format_url( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redisEnterprise/{clusterName}/databases/{databaseName}", **self.url_parameters )
[ 274 ]
def METHOD_NAME(test_file): with Image.open(test_file) as im: assert im.tell() == 0 # prior to first image raises an error, both blatant and borderline with pytest.raises(EOFError): im.seek(-1) with pytest.raises(EOFError): im.seek(-523) # after the fi...
[ 9, 336 ]
def METHOD_NAME(): """See base_runner.""" return True
[ 220, 1797 ]
def METHOD_NAME(configuration_policy_group_name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, vpn_server_configuration_name: Optional[pulumi.Input[str]] = None, ...
[ 19, 830, 54, 846, 146 ]
def METHOD_NAME(wn, tn): if tn is None: # special case. i.e. the last tile. #dont know why it is a special case, if the ALL-1 is received with a tile #then it should always be one, if the tile is consired received by the method #below, then it should not be false #i think the...
[ 4132, 2876, 584, 74 ]
def METHOD_NAME( self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionGraphicsItem, # pylint: disable=unused-argument widget: Optional[QtWidgets.QWidget] = ..., ): # pylint: disable=unused-argument self._paint_boundary(painter)
[ 5932 ]
def METHOD_NAME(self): """Configure the DUT (Router in our case) which we use for testing the EMU functionality prior to the test""" sys.stdout.flush() if not CTRexScenario.router_cfg['no_dut_config']: sys.stdout.write('Configuring DUT... ') start_time = time.time() CTRexScenari...
[ 200, 1290 ]
def METHOD_NAME(self, peer_id: ID) -> PublicKey: """ :param peer_id: peer ID to get public key for :return: public key of the peer :raise PeerStoreError: if peer ID not found """
[ 9600 ]
f METHOD_NAME(self, flag):
[ 0, 4160 ]
def METHOD_NAME(self, get_ipython, clear_output): """ Context manager that monkeypatches get_ipython and clear_output """ original_clear_output = widget_output.clear_output original_get_ipython = widget_output.get_ipython widget_output.get_ipython = get_ipython widget_output.clear_output = clear_out...
[ 4331, 4741 ]
def METHOD_NAME(): with pytest.raises(ImportError): from ddtrace.constants import INVALID_CONSTANT # noqa
[ 9, 532 ]
def METHOD_NAME(lnst_config): for preset_name in PRESETS: preset = lnst_config.get_option("colours", preset_name) if preset == None: continue fg, bg, bf = preset extended_re = "^extended\([0-9]+\)$" if fg == "default": fg = None elif not re.mat...
[ 557, 8435, 280, 200 ]
def METHOD_NAME(self) -> LoggingMode: """ Get the logger's mode. :return: The logger mode. """ return self._mode
[ 854 ]
def METHOD_NAME(data): """ Calculates the CRC32C checksum of the provided data. Args: data: the bytes over which the checksum should be calculated. Returns: An int representing the CRC32C checksum of the provided bytes. """ return _crc32c(six.ensure_binary(data))
[ 17276 ]
def METHOD_NAME(self, model): pass # Not needed
[ 238, 44 ]
def METHOD_NAME(self): size = 100 matrix = torch.randn(size, size, dtype=torch.float64) matrix = matrix.matmul(matrix.mT) matrix.div_(matrix.norm()) matrix.add_(torch.eye(matrix.size(-1), dtype=torch.float64).mul_(1e-1)) # set up vector rhs rhs = torch.randn(size, dtype=torch.float64) # ...
[ 9, 10452 ]
def METHOD_NAME(): if Promise.unhandled_exceptions: for exctype, value, tb in Promise.unhandled_exceptions: if value: raise value.with_traceback(tb) # traceback.print_exception(exctype, value, tb)
[ -1, 10853 ]
def METHOD_NAME(src_lines, var_name, lines): add_comments_header(lines) lines.append("const char *{0} =".format(var_name)) for src_line in src_lines: lines.append('"' + cpp_escape(src_line) + "\\n\"") lines[len(lines) - 1] += ';' add_comments_footer(lines)
[ 238, 7728, 144, 1479 ]
def METHOD_NAME(self): return os.path.join(self.save_path, 'train')
[ 849, 157 ]
def METHOD_NAME(): mc = MailChimp(mc_api=app.config["MAILCHIMP_KEY"]) try: email = request.form.get("email") try: data = mc.lists.members.create_or_update( list_id=app.config["MAILCHIMP_LIST"], subscriber_hash=get_subscriber_hash(email), ...
[ 57, 72 ]
def METHOD_NAME(): vip = utils.config_get('vip') vip_iface = utils.config_get('vip_iface') vip_cidr = utils.config_get('vip_cidr') corosync_bindiface = utils.config_get('ha-bindiface') corosync_mcastport = utils.config_get('ha-mcastport') if None in [vip, vip_cidr, vip_iface]: utils.juju...
[ 3907, 2043, 2624 ]
def METHOD_NAME( query: str, offset: int, length: int, expected_result: Any, expected_num_rows_total: int ) -> None: # simulate index file index_file_location = "index.duckdb" con = duckdb.connect(index_file_location) con.execute("INSTALL 'httpfs';") con.execute("LOAD 'httpfs';") con.execute...
[ 9, 324, 526, 1070 ]
async def METHOD_NAME( db: AsyncSession = Depends(get_async_db), form_data: OAuth2PasswordRequestForm = Depends(),
[ 273, 43, 1089, 466 ]
def METHOD_NAME(cls): super().METHOD_NAME() cls.sth_related = SomethingRelated.objects.create(name='Rel1') cls.pol_1 = PolymorphicModelTest.objects.create( name='Pol1', sth_related=cls.sth_related ) cls.pol_2 = PolymorphicModelTest.objects.create( name='Pol2', sth_rel...
[ 0, 1, 2 ]
def METHOD_NAME(self): return []
[ 19, 2537, 24, 673, 2428 ]
def METHOD_NAME(self): factory = RequestFactory() bad_referers = ( "http://otherdomain/bar/", "http://otherdomain/admin/forms/form/", ) for referer in bad_referers: with self.subTest(referer=referer): request = factory.get( "/api/v1/foo", HTTP_REFERER=...
[ 9, 137, 2870, 377, 1168, 41, 4486 ]
METHOD_NAME(self):
[ 22 ]
def METHOD_NAME(self): 'od.keys() -> list of keys in od' return list(self)
[ 219 ]
def METHOD_NAME(minion_id, package_name, state_tree): module_contents = """ def get_test_package_name(): return "{}" """.format( package_name ) top_file_contents = """ base: {}: - install-package """.format( minion_id ) install_package_sls_co...
[ 131, 551, 151 ]
def METHOD_NAME(vineyard_client): df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]}) object_id = vineyard_client.put(df) pd.testing.assert_frame_equal(df, vineyard_client.get(object_id))
[ 9, 2842, 1616 ]
def METHOD_NAME(self) -> str: """ Resource type. """ return pulumi.get(self, "type")
[ 44 ]
def METHOD_NAME(self): """ Test rectangular transfer of self.d_array1 to self.d_array2 """ # Reference o1 = self.offset1 o2 = self.offset2 T = self.transfer_shape logger.info("""Testing D->D rectangular copy with (N1_y, N1_x) = %s, (N2_y, N2_x) = %s: array...
[ 9, -1 ]
def METHOD_NAME(self, view_size): if self.selection_valid(): before_selection = view_size // 2 self.view.start = max(0, self.selection - before_selection) self.view.end = self.view.start self.max_view_size = view_size self._expand_view() else: self.max_view_size =...
[ 1128, 1179 ]
def METHOD_NAME(event): """ Control-P in vi edit mode on readline is history next, unlike default prompt toolkit. If completer is open this still select previous completion. """ event.current_buffer.auto_up()
[ 1511, 351, 894, 1511, 1323 ]
def METHOD_NAME(self, X, queue=None): y = super()._predict(X, _backend.linear_model.regression, queue) return y
[ 2103 ]
def METHOD_NAME( record_property, get_host_key, setup_splunk, setup_sc4s, event ): host = get_host_key dt = datetime.datetime.now(datetime.timezone.utc) iso, _, _, _, _, _, epoch = time_operations(dt) # Tune time functions iso = dt.isoformat()[0:23] epoch = epoch[:-3] mt = env.from_stri...
[ 9, -1 ]
def METHOD_NAME(self) -> None: warnings.filterwarnings("default", category=DeprecationWarning) warnings.filterwarnings("ignore", category=DeprecationWarning, module="pyscf") warnings.filterwarnings(action="ignore", category=DeprecationWarning, module=".*drivers*") warnings.filterwarnings( action...
[ 0, 1 ]
def METHOD_NAME(self, channel, on): pass
[ 307, 69, 3988 ]