content
stringlengths
22
815k
id
int64
0
4.91M
def generic_exception_json_response(code): """ Turns an unhandled exception into a JSON payload to respond to a service call """ payload = { "error": "TechnicalException", "message": "An unknown error occured", "code": code } resp = make_response(jsonify(payload), code) ...
54,300
def reference_col(tablename, unique=False, nullable=False, pk_name='id', **kwargs): """Column that adds primary key foreign key reference. Usage: :: category_id = reference_col('category') category = relationship('Category', backref='categories') """ return db.Column(...
54,301
def convertSvgToPng(svg_data): """ Converts the given svg data to PNG. This one is preferred over convertSvgTo(), because it simply returns the result instead of a file and does not have excessive white space. """ import cairosvg import StringIO buffer = StringIO.StringIO() cairosvg.svg2...
54,302
def RegexCheck(re, line_number, line, regex, msg): """Searches for |regex| in |line| to check for a particular style violation, returning a message like the one below if the regex matches. The |regex| must have exactly one capturing group so that the relevant part of |line| can be highlighted. If more ...
54,303
def load_graphml(filename, folder=None): """ Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string, the name of the graphml file (including file extension) folder : string, the folder containing the file, if None, u...
54,304
def cosine_distances(test, support): """Computes pairwise cosine distances between provided tensors Parameters ---------- test: tf.Tensor Of shape (n_test, n_feat) support: tf.Tensor Of shape (n_support, n_feat) Returns ------- tf.Tensor: Of shape (n_test, n_support) """ rnorm_test = t...
54,305
def read_table_file(file, element, sheet_name=0, n=0, sheet_type="Model"): """Instantiate one or more element objects using inputs from an Excel table. Parameters ---------- file: str Path to the file containing the shaft parameters. element: str Specify the type of element to be in...
54,306
def substring(column, pos=0, l=1): """ Substring starts at ``pos`` and is of length ``l`` when str is String type or returns the slice of byte array that starts at ``pos`` in byte and is of length ``l`` when ``column`` is Binary type # Arguments column: a ``Column`` object, or a column name ...
54,307
def assert_array_equal(x: numpy.matrix, y: numpy.matrix, err_msg: Literal["-1"]): """ usage.scipy: 2 """ ...
54,308
def _f2_div_ ( self , other ) : """Operator for ``2D-function / other''""" return _f2_op_ ( self , other , Ostap.MoreRooFit.Division , "Divide_" )
54,309
def usplit( uval ): """ Split Unicode string into a sequence of characters. \U sequences are considered to be a single character. You should assume you will get a sequence, and not assume anything about the type of sequence (i.e. list vs. tuple vs. string). """ # The commented code (below)...
54,310
def aten_mean(mapper, graph, node): """ 构造求均值的PaddleLayer。 TorchScript示例: %x.28 : Tensor = aten::mean(%result.1, %4967, %3, %2) 参数含义: %x.28 (Tensor): 输出,求均值后的结果。 %result.1 (Tensor): 输入,需要求均值的Tensor。 %4967 (int/list): 求平均值运算的维度。 %3 (bool): 是否在输出Tensor中保留减小的维度。 ...
54,311
def get_partial_dict(prefix, dictionary, container_type=dict): """Given a dictionary and a prefix, return a Bunch, with just items that start with prefix The returned dictionary will have 'prefix.' stripped so:: get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}) would return...
54,312
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
54,313
def test_input_email_report_email_address(): """ Given: - tag list When: - Reporting email to API Then: - Raises Value error for missing email_address field """ from EmailRepIO import report_email_address_command client = emailrep_client() args = { 'tags'...
54,314
async def add_user(user: NewUserPayload): """ Creates new user in database """ try: user_exists = await storage.driver.user.check_if_exists(user.email, user.id) except ElasticsearchException as e: raise HTTPException(status_code=500, detail=str(e)) if not user_exists: try...
54,315
def beginRow(theWhere, theX, theY, theWidth = -1, theHeight = -1, thePadding = 0): """ Start a new row. One of the most annoying tasks when building UI is to calculate where each component should be placed on the screen. cvui has a set of methods that abstract the process of positioning components, so you don't ...
54,316
async def test_light_goes_unavailable_and_recovers(hass: HomeAssistant) -> None: """Test a light goes unavailable and then recovers.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE}, unique_id=MAC_ADDRESS, ) config_ent...
54,317
def data_integrity(testcase, session, loaded_objects, label=None): """Checks that the data was loaded correctly into a session. Args: testcase (unittest.TestCase): the test case where this function is being called. session (Session): the session where the imported objects have been ...
54,318
def save_regress_model(model, models_path, model_name, weights_path, model_path, file_suffix, test_rmse, test_mae, args): """ Utility to save the architecture, the weights and the full model for Regression """ architecture_path = models_path + model_name + '_architecture' ...
54,319
def check_bsp_planetary(): """ Verifica se existe o arquivo BSP Planetary. """ bsp_planets_filename = os.getenv("BSP_PLANETARY") bsp_planets = os.path.join(os.getenv("DATA_DIR"), bsp_planets_filename) if not os.path.exists(bsp_planets): # Se nao existir no data, criar link os...
54,320
async def _update_instance_async(filter, projection, update) -> dict: """Helper to update an instance async-style""" await moto.update_one(collection="system", filter=filter, update=update) return await _get_instance_async(filter, projection)
54,321
def itemsInView(): # pragma: no cover """Iterate over all of the items in view on one of the open windows. Items can be tasks, calendar items, or project markers. Only 'tasks' has a well-defined meaning. XXX: Which window? """ content = omniFocus.defaultDocument().documentWindows()[0].content...
54,322
def cryptominisat_solve(input_file: Path, docker_mode: bool = DEFAULT_DOCKER_MODE_ON) -> Optional[List[int]]: """Attempts to solve a CNF formula with CryptoMiniSAT and returns the result as a list of integers. Returns an empty list if the result was unsatisfiable, and returns ``None`` if CryptoMiniSAT ...
54,323
def sen(x): """ El seno de un número. El ángulo debe estar expresado en radianes. .. math:: \sin(x) Args: x (float): Argumento. Returns: El seno. """ return math.sin(x)
54,324
def req_item_packs(): """ Called by S3OptionsFilter to provide the pack options for an Item Access via the .json representation to avoid work rendering menus, etc """ req_item_id = None args = request.args if len(args) == 1 and args[0].isdigit(): req_item_id = args[0] e...
54,325
def count_records(context, expected_result): """@expected_result: fail or work""" try: con, cur = context.dbt.db.create_connection_with_cursor() cur.execute("SELECT count(*) from testdata;") context.dbt.found_records = cur.fetchall()[0][0] logging.info("Found {} records in the DB...
54,326
def create_board() -> t.List[t.List[int]]: """Initialize game board (road).""" board = [] # Create rows for _ in range(BLOCKS_AMOUNT_Y + 1): board.append( [Blocks.frame] + [Blocks.empty for _ in range(BLOCKS_AMOUNT_X - 2)] + [Blocks.frame] ) return...
54,327
def SymDatToPath(symtext): """Convert a Cygwin style symlink data to a relative path.""" return ''.join([ch for ch in symtext[12:] if ch != '\x00'])
54,328
def n_bytes(count: int, name: str = ""): """ Create an instance of a byte string of ``count`` length. Setting ``count`` to ``-1`` will consume the entire remaining buffer. """ class BYTES(BytesDataType): size = count return BYTES(name)
54,329
def find_trait_and_value(obj, pathname): """Return a tuple of the form (trait, value) for the given dotted pathname. Raises an exception if the value indicated by the pathname is not found in obj. If the value is found but has no trait, then (None, value) is returned. """ names = pathname.split(...
54,330
def icon(name, extension=None, style=None, use_inheritance=True, allow_theme=True, _always_return=True): """ Find an icon with the given ``name`` and ``extension`` and return a :class:`PySide.QtGui.QIcon` for that icon. ================ =========== ============ Argument Default ...
54,331
def bigbird_block_rand_mask(from_seq_length, to_seq_length, from_block_size, to_block_size, num_rand_blocks, last_idx=-1): """Create adjacency list of random attention. Args: ...
54,332
def list_(env=None, user=None): """ List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... } """ cmd = _create_conda_cmd('list', args=['--json'], env=env, user=user) ret = _execcmd(cmd, user=user) if ret['retcode'] == ...
54,333
def push_data(): """ Push to front end """ pass
54,334
def read_dir_key(fname='', existing_dict=None, delim=None): """ Read a directory mapping key. """ out_dict = read_nametoname_key(fname=fname, existing_dict=existing_dict, delim=delim) return(out_dict)
54,335
def show(ctx): """Display details about how to invoke PyOCC. """ pass
54,336
def main(): """Create PowerMax storage group object and perform action on it based on user input from playbook""" obj = PowerMaxStorageGroup() obj.perform_module_operation()
54,337
def get_end_pair_index(s: str, i: int): """ This method takes a string and an integer as inputs. It searches for the opening brace'[' using the given integer as the index of the opening brace in the given string. It outputs the index of the closing pair ']' in the string. :param s: The input string...
54,338
def main(): """The main runner for our script.""" ## Deal with incoming. parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', '--verbose', action='store_true', help='More verbose ou...
54,339
def count(obj: Union[int, List]) -> int: """Return the number of integers in obj. >>> count(27) 1 >>> count([4, 1, 8]) 3 >>> count([4]) 1 >>> count([]) 0 >>> count([4, [1, 2, 3], 8]) 5 >>> count([1, [2, 3], [4, 5, [6, 7], 8]]) 8 """ if isinstance(obj, int): ...
54,340
def kmeans(x, n_clusters=20, random_state=42, **sklearnArg): """Given a set of different 1D functions (represented in matrix form where each row contains the function values on a given grid), this method clusters those functions and tries to find typical function structures. Args: x (numpy matr...
54,341
def GetClientSecretFlag(): """Anthos auth token client-secret flag, specifies the Client Secret is the shared secret between OIDC client application and OIDC provider.""" return base.Argument( '--client-secret', required=False, help='Client Secret is the shared secret between OIDC client applicati...
54,342
def generate_cocktail_vs_xgboost_incumbent_times( cocktail_folder: str, baseline_folder: str, baseline_name: str, benchmark_task_file: str, ): """Generate the cocktail vs XGBoost incumbent times information. Generates information regarding the cocktail vs xgboost time performance and sa...
54,343
def start_thread(): """ Starts the flexx thread that manages the flexx asyncio worker loop. """ import threading import asyncio flexx_loop = asyncio.new_event_loop() # assign the loop to the manager so it can be accessed later. def flexx_thread(loop): """ Function to star...
54,344
def login(request): """ Fonction idantifiant les gens et/ou renvoyant le formulaire. """ message = None form = None topThree = [] if request.method == 'POST': if request.session.test_cookie_worked(): request.session.delete_test_cookie() form = LoginForm(reque...
54,345
def start_instance_pool(instance_pool_id: str, configuration: Configuration = None, secrets: Secrets = None) -> OCIResponse: """Start the given OCI Compute instances.""" client = oci_client(ComputeManagementClient, configuration, secrets, ...
54,346
def label_rank(label, scores, label_order) -> int: """ Add Labels based on Rank :param label: Label to assign to item :param scores: Score to rank item :param label_order: Order of Labels :return: Return Index """ loc = label_index(label, label_order) if loc is None: return ...
54,347
def _single_quote_string(name: str) -> str: # pragma: no cover """Single quote a string to inject it into f-strings, since backslashes cannot be in double f-strings.""" return f"'{name}'"
54,348
def parse_override_config_and_write_file(namespace): """ Parse the command line for overriding the defaults and create an override file. """ overrides = parse_override_config(namespace) try: tmp_dir = tempfile.mkdtemp() override_config_file = os.path.join(tmp_dir, OVERRIDE_YAML) with open(overri...
54,349
def compute_rel_rois(num_rel, rois, relations): """ union subject boxes and object boxes given a set of rois and relations """ rel_rois = np.zeros([num_rel, 5]) for i, rel in enumerate(relations): sub_im_i = rois[rel[0], 0] obj_im_i = rois[rel[1], 0] assert(sub_im_i == obj_im...
54,350
def get(req, api): """ Execute `python2 app.py` E entre, pelo seu browser em `localhost:8888/example/ex_endpoint` Deverá abrir uma página escrita `sucesso!` Output: string """ result = yield api.example_util.write(req) req.send(result)
54,351
def obeserveAtoms(graph): """ """ importantAtoms = graph.layers["$"].children importantAtoms.discard(graph.layers["Base"]) for atom in importantAtoms: pset = atom.parents print(" or ".join(map(lambda x: x.name, pset.difference(set([graph.layers["$"]])))))
54,352
def test_token_is_singleton(): """ tests that different types of tokens are singleton. """ token1 = RS256Token() token2 = RS256Token() assert token1 == token2 token3 = HS256Token() token4 = HS256Token() assert token3 == token4
54,353
def test_cms_signin_redirect_to_site_signin(client): """ Test that the cms/login redirects users to site signin page. """ response = client.get("/cms", follow=True) assert response.request["PATH_INFO"] == "/signin/"
54,354
def from_gml(text): """ Return the list of graphs read from `text`, a string in GML format. This function assumes that the input follows the GML specification, provides unique integer ids even for isolated nodes, and defines one or more graphs. This function ignores anything other than node ids...
54,355
def test_products_update_cache(data, mocker): """ get wtil retrieve products from cache file """ mocker.patch("sps.cache.save", autospec=True) mocker.patch("sps.request.fetch", autospec=True) request.fetch.return_value = data products.get(None, "fake-file-name", False, True) cache.save.a...
54,356
def parse(type_string: str, *, func=None): """Parse the given type string. Args: type_string (str): The type string to be parsed. func (function): The function to which the type string belongs (optional). This causes the type string to be evaluated in func's context. ...
54,357
def run(data, inFile="", encrypt=False, method=3, aad="", key=config.KEY): """ Run encryption of decryption. data: file name with extension encrypt: False to decrypte method: Block cyphering method """ from threading import Thread if len(data) > 100000: thread = Thread(target=...
54,358
def append_to_csv(csv_path: Path, data_obj: Dataclass, encoding: str = "utf-8") -> None: """ Append a data object to a CSV file. This function makes the following assumptions: * 'obj' is a dataclass. This code will check dynamically to make sure the object is a dataclass before writing it to file, and...
54,359
def convert_str_version_number(version_str): """ Convert the version number as a integer for easy comparisons :param version_str: str of the version number, e.g. '0.33' :returns: tuple of ints representing the version str """ version_numbers = version_str.split('.') if len(version_number...
54,360
def download( # pylint: disable=E0012,C0330,R0913 destination, project_id, sample_ids, file_types, skip_existing, download_urls, download_template, host, email, password, api_key, no_progress, ): # noqa: D413,D301,D412 # pylint: disable=C0301 """Download deliverable...
54,361
def valid_simulation(_state, _params): """ AW - valid_simulation - return a binary variable per simulation indicating whether or not that simulation satifies the desired policy outcome. :param _state: tensor (N x D): tensor of the state trajectory. :return: tensor (N, ), bool: tensor of whether ...
54,362
def refresh_screen(screen, game, game_font): """Function that redraws the screen at each iteration of the main event loop Args: screen (pygame.display): Surface to redraw the game on game (SudokuGame): Class representing a single instance of a Sudoku game game_font (pygame.freetype.Font...
54,363
def computeA(diameter): """Computes area of circle""" radius = diameter / 2.0 return np.pi * (radius**2)
54,364
def RemoveFromLinuxKernelCmdline(option): """ Remove 'option' to the kernel boot options of the grub configuration. """ if FindInLinuxKernelCmdline(option): src = r'^(.*?' + MyDistro.grubKernelBootOptionsLine + r'.*?)(' + option + r')(.*?)("?)$' rep = r'\1\3\4' try: R...
54,365
def write_wallet(wallet_json): """interpret a json as wallet and writes it in the wallets subfolder inside the specter-folder. overwrites it if existing. """ fpath = os.path.join( app.specter.wallet_manager.working_folder, "%s.json" % wallet_json["alias"] ) _write_json_file(wallet_json, ...
54,366
def get_maximum_weight(G, S, T): """ Given a networkx graph G and two subsets of vertices S and T, this method returns the maximum weight of an edge e, having one endpoint in S and the other in T :param G: A networkx graph :param S: A subset of vertices in G :param T: A subset of vertices in G ...
54,367
def create_volume_snapshot(session, cg_id, display_name, return_type=None, **kwargs): """ Creates a new snapshot for the specified volume. Manually initiated snapshots will fall under the "On Demand" snapshot policy. :type session: zadarapy.session.Session :param session...
54,368
def every_sleep(seconds: float): """ 指定秒数待機します :param seconds: 待機秒数 """ yield sleep(seconds)
54,369
def parse_elem(elem): """Determine element type and dispatch to other parse functions.""" if len(elem) == 0: return parse_text(elem) if not elem[0].attrib: return parse_list(elem) if elem[0].get('Name') == 'Key': return parse_key_value_dict(elem) return parse_attrib_dict(elem...
54,370
def describe_clusters(clusters=None): """ Describes one or more of your clusters. See also: AWS API Documentation Examples This example provides a description of the specified cluster in your default region. Expected Output: :example: response = client.describe_clusters( cl...
54,371
def configured_version_for(artifact_name: str) -> Optional[str]: """Given the name of an artifact, retrieves the version of that artifact from the current stack configuration. Returns `None` if no version has been specified for that artifact. In general, we will have versions specified for all artifact...
54,372
def filtered_cumulative_sum(df, columns, latest_date, reference_column_name="covid_vacc_date"): """ This calculates cumulative sums for a dataframe, and when given a set of characteristics as columns, produces a dictionary of dataframes. Args: df (Dataframe): pandas dataframe. At the very least...
54,373
def handover_results(): """ Endpoint to get a list of all the handover by release This is using docstring for specifications --- tags: - handovers operationId: handovers parameters: - name: release in: query type: string description: get handover list for ...
54,374
def safezip(*args): """make sure *args* are equal len before zipping""" Nx = len(args[0]) for i, arg in enumerate(args[1:]): if len(arg) != Nx: raise ValueError(_safezip_msg % (Nx, i + 1, len(arg))) return list(zip(*args))
54,375
def chaid_to_graphviz( tree: dict, classes: Union[list, np.ndarray] = [], classes_color: list = [], round_pred: int = 2, percent: bool = False, vertical: bool = True, node_style: dict = {}, arrow_style: dict = {}, leaf_style: dict = {}, **kwds, ): """ --------------------...
54,376
def process_dataset(dataset, func): """Calculate things here using the dataset, then return a dictionary containing names and values for each calculated quantity.""" new_dataset = copy.copy(dataset) del new_dataset["val"] new_dataset.update(func(dataset)) return new_dataset
54,377
def cosine_beta_schedule(timesteps, s = 0.008): """ cosine schedule as proposed in https://openreview.net/forum?id=-NEXDKk8gZ """ steps = timesteps + 1 x = np.linspace(0, steps, steps) alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2 alphas_cumprod = alphas_cumprod...
54,378
def _infinity(name): """ Create a single instance of an class with a given name. """ return type(name + "Type", (object, ), { '__repr__': lambda self: "{0}.{1}".format(self.__module__, name), '__str__': lambda self: name, '__unicode__': lambda self: name, })()
54,379
def allocate_packs(packs, tracks, pack_refs, num_silent_tracks): """Allocate tracks to channels and packs. This is intended to be used on a subset of tracks referenced by an audioObject, or on all tracks if there is no programme/content/object hierarc...
54,380
def edit_settings(request): """Edit user settings.""" user = request.user if user.groups.filter(name='Mozillians').exists(): raise Http404 form = forms.EditSettingsForm(request.POST or None, instance=user.userprofile) if request.method == 'POST' and form.is...
54,381
def ls(ctx, path, output): """ list lab nodes """ try: client = get_client(ctx) resp = client.api.list_nodes(path) node_indexes = resp.keys() nodes_list = [(idx, resp[idx]) for idx in node_indexes] node_table = [] for idx, n in nodes_list: sta...
54,382
def calculate_priority(priority_table_uri): """Create dictionary mapping each land-cover class to their priority weight. Args: priority_table_uri (str): path to priority csv table Returns: priority_dict (dict): land-cover and weights_matrix """ LOGGER.info("Creating land-cover prio...
54,383
def create_virtual_cdrom_spec(client_factory, datastore, controller_key, file_path, cdrom_unit_number): """Builds spec for the creation of a new Virtual CDROM to the VM.""" config_spec = clien...
54,384
def read_image_from_file(file_path: str) -> np.ndarray: """Read image data from a file and return as is.""" img = cv2.imread(file_path, cv2.IMREAD_UNCHANGED) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img
54,385
def get_line(x, camera_id, camera_param): """Get line in world""" # x: n * 2 x_tmp = np.concatenate((x, np.ones((len(x), 1)).astype(np.float32)), axis=1) new_x = (x_tmp - camera_param[camera_id]['C']) * camera_param[camera_id]['FInv'] sample_num = len(new_x) cam_origin = np.array([[0, 0, 0]...
54,386
def get_cca_data_as_matrices(data_set="train"): """ Normalizes data and returns data and labels as separate lists. Args: data_set: data set to retrieve Returns: data: list of data vectors labels: list of vectors """ X_scores, labels = CCA_reduction(data_set=data_set) dat...
54,387
def shard_query(query, shard_count): """ Given a datastore.Query object and a number of shards, return a list of shards where each shard is a pair of (low_key, high_key). May return fewer than `shard_count` shards in cases where there aren't many entities. """ OVERSAMPLING_MULTIPLIER = 32 #...
54,388
def get_bindings(keysToObtain=None): """Returns a dict struct with the direct input equivalent of the necessary elite keybindings""" if keysToObtain is None: keysToObtain = keys_to_obtain direct_input_keys = {} latest_bindings = get_latest_keybinds() bindings_tree = parse(latest_bindings) ...
54,389
def add_intercept(A): """ Adds an intercept (column of ones) to a supplied array A such that the intercept is the first (leftmost) column """ n = A.shape[0] intercept = ones(n).reshape(n, 1) return hstack((intercept, A))
54,390
def predict_adjacent_stop(departure_stop_num, arrival_stop_num, features, num_predictions): """ Predict the time to travel between two adjacent stops on the same route trip. This method uses stop numbers and not stop IDs since stop IDs are not available in the historical data used to train the model. ...
54,391
def test(cover=False): """Run the unit tests.""" if cover and not os.environ.get("COVERAGE"): import sys os.environ["COVERAGE"] = "1" os.execvp(sys.executable, [sys.executable] + sys.argv) import unittest tests = unittest.TestLoader().discover("tests") unittest.TextTestRun...
54,392
def make_param_file(param_file_name): """ make_paramfile(paramfile_name) Creates checkfile for analysis, storing key paramtere """ param_file = {} pickle.dump(param_file, open(param_file_name + '.pkl', 'wb'))
54,393
def _cut_open_ended_intervals(intervals): """Keep only one open interval If there are multiple open intervals keep only the latest open; cut others so they no longer intersect each other. :param intervals: [Interval] :return: processed intervals: [Interval] """ filtered_intervals = [] ...
54,394
def get_content_type(obj): """ Returns the content type for ``obj``. """ return ContentType.objects.get_for_model(obj)
54,395
def spark_random_split(data, ratio=0.75, seed=42): """Spark random splitter. Randomly split the data into several splits. Args: data (pyspark.sql.DataFrame): Spark DataFrame to be split. ratio (float or list): Ratio for splitting data. If it is a single float number it splits d...
54,396
def get_test_suite_kwargs(args): """Set and return test suite kwargs based on options.""" kwargs = vars(args) del kwargs['verbose'] ydk_root = get_ydk_root() default_profile = ydk_root + '/profiles/test/ydktest.json' default_test_root = os.path.join(ydk_root, 'test', 'test-cases') kwargs.upd...
54,397
def unique_all(x: Array, /) -> UniqueAllResult: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ values, indices, inverse_indices, counts = np.unique( x._array, return_counts=True, return_index=True, ...
54,398
def tail(filepath, n): """Similate Unix' tail -n, read in filepath, parse it into a list, strip newlines and return a list of the last n lines""" with open(filepath) as f: file = f.read() tail_result = file.split('\n')[-n:] return tail_result
54,399