content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def id2trc(s_id, grid_dim): """ Convert state id to row, col, cell type """ t = s_id // (grid_dim[0] * grid_dim[1]) r = (s_id - t * grid_dim[0] * grid_dim[1]) // grid_dim[1] c = (s_id - t * grid_dim[0] * grid_dim[1] - r * grid_dim[1]) // 1 return t, r, c
b261d3b37d70b5578814b9f099d9763752838e2b
646,304
from typing import Iterable from typing import List def indent(level: int, lines: Iterable[str]) -> List[str]: """ Indent the lines by the specified level. """ return [' ' * level + line for line in lines]
9fea8a60c3dfa9f91b49c39167cd3dadf1b21604
646,305
def gaussian_kl(q, p): """ computes the KL divergence per batch between two Gaussian distributions parameterized by q and p Args: q (list) Gaussian distribution parametrized by q[0] (torch tensor): mean of q [batch_size, *latent_dims] q[1] (torch tensor): varianc...
c5ecc089d3c60de0f037be446596a2691b3b742a
646,306
import os def get_sub_folders(path): """Returns the name of all subfolders within a path""" return next(os.walk(path))[1]
5a61e38fa9fbd6f2012635ad92eb74084e180ac0
646,307
def find_index_neg_num(lis): """ This func. returns position (0 to n) of negative number in lis, and None if there is no negative no. """ return next((index for index, val in enumerate(lis) if val < 0), None)
6b1b06e0c2c1119c1ec6c70e3a41587ea1188e29
646,308
import torch def make_features(x): """Builds features i.e. a matrix with colums [x,x^2,x^3]. """ x=x.unsqueeze(1) return torch.cat([x**i for i in range(1,4)],1)
c5b282901efb15af9f98c865f0422378dd85b1f0
646,309
def max_exposed_loop( sequence_length, n_transmembrane_region, outer_loops, terminal_exposed_loop_min, internal_exposed_loop_min): """ This is the key algorithm in SurfG+ to identify Potentially Surface Exposed proteins. It evaluates all loops that poke out of the periplasmic side of the...
1846adaf9d4834252019cc38b6621e707ba9cc04
646,311
import re def load_data(filename): """加载数据 单条格式:[词1, 词2, 词3, ...] """ D = [] with open(filename, encoding='utf-8') as f: for l in f: D.append(re.split(' +', l.strip())) return D
21485446cd7c83aa7bc3a9490d1d341e6f8df1ed
646,312
def slice2gridspec(key): """Convert a 2-tuple of slices to start,stop,steps for x and y. key -- (slice(ystart,ystop,ystep), slice(xtart, xstop, xstep)) For now, the only accepted step values are imaginary integers (interpreted in the same way numpy.mgrid, etc. do). """ if ((len(key) != 2) or ...
3e8eaacbf2ef21e5c3538cbe5e7aa2349b0e52b5
646,313
def make_shell_logfiles_url(host, shell_port, _, instance_id=None): """ Make the url for log-files in heron-shell from the info stored in stmgr. If no instance_id is provided, the link will be to the dir for the whole container. If shell port is not present, it returns None. """ if not shell_port: r...
33b762e6361481736dd7a0b30e1cca385bc8bc7a
646,314
def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1): """A default set of length-bucket boundaries.""" assert length_bucket_step > 1.0 x = min_length boundaries = [] while x < max_length: boundaries.append(x) x = max(x + 1, int(x * length_bucket_step)) return boundaries
4a022deadbe2f46dc16950bb0af6e6e4a55c9499
646,315
def RotByte(word): """ Part of KeyExpansion. TEST: >>> RotByte([1, 2, 3, 4]) == [2, 3, 4, 1] True """ return word[1:4] + [word[0]]
58c76b98ca66aaebd474011ece2ec3537ce6eb9b
646,316
def leaves(G): """ Return the nodes of G with out-degree zero in a list. G-- nx.Digraph return-- List of leaves nodes. Example: >>> G=random_dag(10,20) >>> leaves_list=leaves(G) >>> len(leaves_list)>0 True >>> any([G.out_degree(x)>0 for x in leaves_list]) False """ ...
2e9dd6ad037437fdeecb6c814c9b1334c20f141c
646,317
def _object_get(entry, attr): """ simple getter over object entry Example:: class A(object): def __init__(self, attribute): self.attribute = attribute def foo(): return self.attribute a = A(10) #: calls foo as it's callable ...
7006844d6136d5262f456b71c241c42ced7a0ac4
646,319
def removeMacColons(macAddress): """ Removes colon character from Mac Address """ return macAddress.replace(':', '')
babe078c4a2b91e7ee56be15f62e58baa4189b8d
646,320
import torch def load_model(load_path, net, device): """ Loads a stored network with pytorch. """ checkpoint = torch.load(load_path, map_location=device) net.load_state_dict(checkpoint) net.to(device) net.eval() return net
0ef5fcf3d532c0096f1e16023836559a583c87c8
646,321
from typing import List import os def filter_dir_files_by_extension(release_notes_dir: str, extension: str) -> List[str]: """ Receives path to RN dir, filters only files in RN dir corresponding to the extension. Needed because RN directory will be extended to contain JSON files for configurations, see...
9de8a5b1a7d4c076ced0f61679054a3b46bdda1f
646,322
def prefix_strip(mystring, prefixes=["rust_"]): """ strip passed in prefixes from the beginning of passed in string and return it """ if not isinstance(prefixes, list): prefixes = [prefixes] for prefix in prefixes: if mystring.startswith(prefix): return mystring[len(prefix):]...
d19c4903ec28e035bbbc769c6dfcad96faaad13e
646,323
def method_available(klass, method): """Checks if the provided class supports and can call the provided method.""" return callable(getattr(klass, method, None))
f061a7c7fc322881895644284f8a637424f86e66
646,324
def punnettParse(s : str) -> list: """Take a str and turn it into a list of strings punnett can accept""" if len(s) % 2: raise ValueError('Even number of alleles required') return ["".join(sorted(s[i:i+2])) for i in range(0,len(s),2)]
e95e27191691e5e603f03830b491559ec19c5c6b
646,325
def str_month(month): """Transforms datetime month object into a "%m/%y" string. Args: month (datetime/datetime.date): Month. Returns: A "%m/%y" string representation. """ return month.strftime("%m/%y")
38e50628157934747e7ee4d1f0a4093292df40d0
646,326
def _ReadCsv(path): """Returns the contents of the .csv as a list of (int, int).""" ret = [] with open(path) as f: for line in f: parts = line.rstrip().split(',') if len(parts) == 2 and parts[0] != 'revision': ret.append((int(parts[0]), int(float(parts[1])))) return ret
1180ac4391293d0f538ffcc58f80d903f8cb29a0
646,327
import requests def getJson(url): """ HTTP GET request :param url: - api url :return: - json object, if response status is OK """ response = requests.get(url) if response.status_code == 200: return response.text raise Exception(response.text)
4016f82de8591ffb2c62f99936b7f3d52fba9cf4
646,328
def test_find_longest_sequence(): """ Given an array L, find the position p and length k which - all elements to the left of p from p-k position are in ascending order - all elements to the right of p until p+k position are in descending order - and L[p] is the biggest among that sequence """ de...
b9d34dfa7c2d5a9ac2e163494e8dffe00b627d8e
646,329
def mt_loss(theta, R, beta): """Compute objective function for multi task group lasso.""" n_samples = len(R) obj = 0. for n in range(n_samples): obj += R[n] ** 2 obj *= 0.5 return obj
edb1693d71f0cc880cd91ae76a7780ebbf2794fc
646,330
def pull_line_geometry(linegeometry, pull_value, end_point_bool=True, start_point_bool=True): """This function will take an ArcPolyline, a pull value, and a start and end point boolean. The function returns a line geometry whose length are pulled back based on the input parameters. Line Geometry- arc polyli...
c09df950ba56526ea61604029f14b2939aa0811f
646,331
def get_col_widths(dataframe): """ helper function to auto set col widths """ # First we find the maximum length of the index column idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))]) # Then, we concatenate this to the max of the lengths of column name...
36c8f81f7a7eb71dfaef057f710aea902af31585
646,332
def _lang_strings(varname, language_config): """language config should look like: { "english": "some en string", "spanish": "some es string" }""" lang_strings = [] for lang_name, lang_string in language_config.iteritems(): lang_string = 'LangString %s ${LANG_%...
e1571345f04f2d43770e8aaf5c3e596b91fdfc71
646,333
import re def RemoveMatchingTests(test_output, pattern): """Removes output of specified tests from a Google Test program's output. This function strips not only the beginning and the end of a test but also all output in between. Args: test_output: A string containing the test output. pattern: ...
7cc3bcf11a8f7fce8f95d3cc615f7eb62e902a33
646,334
def reduced_df_from_split_plus_more(df_new, new_wells_loaded_list_inUWIstyle, UWI): """ Takes in: Returns: """ df_new_allWells = df_new.copy() print("len(df_new_allWells)", len(df_new_allWells)) df_reduced = df_new[df_new[UWI].isin(new_wells_loaded_list_inUWIstyle)] df_reduced = df_new....
15f272e40ddb3d8a3fb7e7caae12299649ef05c0
646,335
def reconcile_countries_by_code(codeinfo, plot_countries, gdp_countries): """ Inputs: codeinfo - A country code information dictionary plot_countries - Dictionary whose keys are plot library country codes and values are the corresponding country name gdp_countries ...
1734538a83381b075709ef2324c24394ea2cf6dd
646,336
def is_cdap_entity_role(role): """ CDAP create roles for entities by default. These roles are in the format of '.namespace', '.program' etc. :param role: The role to judge :return: bool: if role is a cdap entity role """ return role['name'].startswith(('.artifact', '.application', '.program', '.dataset', 's...
8ffe9c8525d711e38a061136045f948b31691dd3
646,337
def changes_to_yaml(changes): """ Return a multi-line string of pseudo-yaml from a nested dict produced by `diff()`. Output is like a yaml version of the original dicts, except that deletions are prefixed with '<' and additions with '>'. Note that: - Modified values are shown as a d...
86611fa96015be87dc78ab3b46cbded9c23ca8b1
646,338
def indices_to_matches(cost_matrix, indices, threshold): """ Generates three list of indices """ matched_cost = cost_matrix[tuple(zip(*indices))] matched_mask = (matched_cost <= threshold) matches = indices[matched_mask] unmatched_a = tuple(set(range(cost_matrix.shape[0])) - set(matches[...
7d598decd976c1c5445a67cd2e6cad7529b3b84d
646,339
def islice(vals, inds): """Returns a list of values from `vals` at the indices in `inds`.""" sliced = [] for (i, v) in enumerate(vals): if i in inds: sliced.append(v) return sliced
247c94fd42c4201d740aee2d4851a77c31626e04
646,340
import collections def as_namespaced_named_tuple(name, data): """Takes a name and either a dict or list of strings, uses the name to namespace the values and return as a named tuple:: >>> foo = as_namespaced_named_tuple(u'Foo', [u'a', u'b']) >>> foo.a u'foo:a' >>> ba...
bb278fa12e1c60a618d70fe8fccb95c5c361deb8
646,341
def merge_ranges(ranges): """Merge short, fragmental ranges into long, continuous ones. Parameters ---------- ranges : list of int Ranges to merge. Returns ------- list of int Merged ranges. Notes ----- Ranges that have overlaps will be merged into one. For exa...
e13817f71163c75425daac6acbb024f989467ff7
646,342
from typing import List def sieve_of_atkin(limit: int = 200) -> List[int]: """ The Sieve of Atkin is an ages-old algorithm to sift out all primes under a certain maximum limit :param limit: This is the upper boundary for the value of the primes to be calculated :return: """ prime_seed = [2, 3,...
508e0ee00a6c63bb424f06a0ae64addf44c69f01
646,343
def crop_border(img_list, crop_border): """Crop borders of images Args: img_list (list [Numpy]): HWC crop_border (int): crop border for each end of height and weight Returns: (list [Numpy]): cropped image list """ if crop_border == 0: return img_list else: ...
4c076b1e16969f86cb61485a6def6c3ba6185e35
646,344
def calc_pr_curve(gt_bboxes, det_bboxes): """閾値ごとの精度及び再現率を計算する。 Args: gt_bboxes (DataFrame): 正解の矩形一覧 det_bboxes (DataFrame): 予測した矩形一覧 Returns: tuple: (precision, recall) """ TP = det_bboxes["Correct"] FP = ~det_bboxes["Correct"] n_positives = len(gt_bboxes.index) ...
f47b26745f0f5b221e2313881079458202489c18
646,345
def select_samples_with_object_budget(args, ordered_images, object_budget, dataset, ): """ :param ordered_images: Unlabeled image names ordered from most uncert...
d87076424d854a6468ed45b5b53bbc8bb974f706
646,346
import torch def argmax(x): """ Arg max of a torch tensor (2 dimensional, dim=1) :param x: torch tensor :return: index the of the max """ return torch.max(x, dim=1)[1]
511b073d7ad2bfcd2b16f18fe8bf8a4cc14927cb
646,347
import os def locate(fn): """Locates a binary on the path. Returns the fully-qualified path, or None. """ exec_suffix = '.exe' if os.name == 'nt' else '' for p in ["."] + os.environ['PATH'].split(os.pathsep): f = os.path.join(p, fn + exec_suffix) if os.path.exists(f): ...
2b117160392a9468fbaa11957aa315b5dfb65b6e
646,348
def nos_unknown_host_cb(host, fingerprint): """An unknown host callback. Returns `True` if it finds the key acceptable, and `False` if not. This default callback for NOS always returns 'True' (i.e. trusts all hosts for now). """ return True
576c0a195e15bc33079050c4c527c3b196d5325f
646,349
from typing import Any import inspect def _args_to_vars( *, args, kwargs: dict[str, Any], signature: inspect.Signature | None, keep_result: bool = True, ) -> dict[str, Any]: """Convert args and kwargs into dict of params based on the given function. For simple validators the validator is ...
9c8465def2be13b5b459080b2b6196972ab0f273
646,350
import os def _instance_from_path(path: str) -> int: """Helper function that retrieves the UK Biobank instance number from a file string assuming the following format: /path/to/file/{sample_id}_xxx_{instance}_0.zip""" return int(os.path.basename(path).split('_')[2])
d2aab2878a5bc3c22f84c136596daee7ebc87e5b
646,351
def merge_values(src, new): """Update a value list with a list of new or updated values.""" l_min, l_max = (src, new) if len(src) < len(new) else (new, src) l_min.extend(None for i in range(len(l_min), len(l_max))) for i, val in enumerate(new): new[i] = val if val else src[i] return new
6ff17140737c04014d064e35ecbe58233ce18fa9
646,352
async def async_handle_google_actions(cloud, payload): """Handle an incoming IoT message for Google Actions.""" return await cloud.client.async_google_message(payload)
ec43b1b33da6596bb5cb42d6b3548e45001a42d3
646,353
def check_status(status): """ A little helper function that checks an API error code and returns a nice message. Returns None if no errors found """ if status == 'REQUEST_DENIED': return 'The geocode API is off in the Google Developers Console.' elif status == 'ZERO_RESULTS': ret...
5adfcd923e5384fa08f6ba0b89aa17492a891923
646,355
def surface_area(l, w, h): """Return the total surface area of a box""" return (2 * l * w) + (2 * w * h) + (2 * h * l)
be40294c8b1f80108e951936e8b8fe58e3e555bd
646,356
def get(isdsAppliance, check_mode=False, force=False): """ Get information on existing snapshots """ return isdsAppliance.invoke_get("Retrieving snapshots", "/snapshots")
026008004fd43eebf234c08f7d3a1cb5ce7fc481
646,357
def get_length_of_closed_loops_in_graph(deck): """Treat deck as a graph: - Trace the path each card takes. - Return the length of each closed loop. """ closed_loops = [] # for start in xrange(len(deck)): for start in range(len(deck)): index, loop = start, 0 while deck...
a007e6715275f7252c58c4c82cf34682e9e19d8e
646,358
def get_session_info(env, sid): """:since 1.0: changed `db` input parameter to `env`""" for row in env.db_query(""" SELECT DISTINCT s.sid, n.value, e.value FROM session AS s LEFT JOIN session_attribute AS n ON (n.sid=s.sid AND n.name='name') LEFT JOIN session_attribute AS e O...
bc66f657a47e8e1c6804186f16f475cdd32f2cbb
646,359
def solidity_library_symbol(library_name): """ Return the symbol used in the bytecode to represent the `library_name`. """ # the symbol is always 40 characters in length with the minimum of two # leading and trailing underscores length = min(len(library_name), 36) library_piece = library_name[:leng...
b20d961e0885b3784f670136f99b2c6981f17d65
646,360
def hostname_valid(hostname): """ Test if specified hostname should be considered valid Args: hostname (str): hostname to test Returns: bool: True if valid, otherwise False """ if (not hostname or hostname.startswith('localhost') or hostname.e...
19ac5d58961569034535b9dda2b94e875e543b91
646,361
import itertools def global_integration_cli_args(integration_config_paths): """ The first arguments to pass to a cli command for integration test configuration. """ # List of a config files in order. return list(itertools.chain(*(('--config_file', f) for f in integration_config_paths)))
ee0c552453ed18197890a2666e0a6ccdbb6c53a1
646,362
def _helpArraysXml(idx, inputName=None, label=None): """Internal helper """ if inputName is None: inputName = 'Input' if label is None: label = 'Array%d' % idx return''' <StringVectorProperty name="SelectInputScalars%d" label="%s" command="SetInputArrayT...
93e6f260b6e47b75726cf30d1dd3a2166bd1a488
646,363
def euclidean_dist_vec(y1, x1, y2, x2): """ Calculate Euclidean distances between pairs of points. Vectorized function to calculate the Euclidean distance between two points' coordinates or between arrays of points' coordinates. For accurate results, use projected coordinates rather than decimal de...
7c0787c4a90f4ac07bcf9faeee2dfd7fdb88085e
646,364
def streak_next(values, i): """Given a list of numbers, skip forward over consecutive streaks Used by DfView.find() If i references a value within a consecutive streak, the value returned will be the index of the end of the streak. If i references a value at the end of a streak, the value retu...
ca81546314aab1ac963fa227b97fb692145a40c6
646,365
def hello(): """ Fonction appelee pour le chemin par defaut. Returns: str: un message : """ return "hello world!"
a4f4eb3fb5e052247bde740ffe1e331b7e501730
646,366
def multiply(valor_uno, valor_dos): """Su función es multiplicar""" return valor_uno * valor_dos
17216b68df2aa36a879453864359aa55de66c307
646,367
from datetime import datetime def epoch_to_date(s): """ UNIX epoch timestamp in string or float to datetime object """ return datetime.utcfromtimestamp(float(s))
1ce9d4e2ae0992dda78b561b67df994c212b1862
646,369
def convert_excel_kurtosis(K, n): """ K is the kurtosis you get from Excel. The function will return (n-2) * (n-3) * K / ((n + 1) * (n - 1)) + 3 * (n - 1) / (n + 1). """ if (n < 3): return None return (n-2) * (n-3) * K / ((n + 1) * (n - 1)) + 3 * (n - 1) / (n + 1)
dbc8a90f6c5ff46352e9fdaefafcb4ce372e6387
646,370
def clean_matrix_U_invalid_object_id(_U): """ in pipeline object_ids that couldn't be processed and end up having no OBJID ('') should be removed :param _U: :return: invalid records from _U where OBJID missing """ return _U[_U.OBJID != ""]
9945e6aedee60a8a76572670cba77ee1c78a8889
646,371
def convert_inputs(inputs: dict) -> dict: """ Convert elements in the dictionary loaded by json to formats that Terra accepts as inputs """ results = {} for key, value in inputs.items(): if isinstance(value, bool): value = 'true' if value else 'false' elif isinstance(value, t...
111a23329c01a9ce4cc0074a21b60c7090b7dd50
646,373
import re def parse_timezone(timezone: str) -> float: """Parse timezone to offset.""" match = re.match( r"^(?P<sign>[-+])(?P<hours>\d{1,2}):(?P<minutes>\d{1,2})$", timezone ) if match: if match.group("sign") == "-": sign = -1.0 else: sign = 1.0 r...
0916ece008c16d0149c2238a7ed5069c1c572505
646,374
def render_comment_list(comment_list, user, comment_list_css="main-thread"): """ Inclusion tag for rendering a comment list. Context:: Comment List Template:: comment_list.html """ return dict(comment_list=comment_list, comment_list_css=comment_list_css, user=user)
74774f88993d5ab8385a92abc91c6534cf5b01c1
646,375
def _confirm_no_logfile_not_web_flac(params): """ Gazelle trackers require a logfile for lossless releases If no logfile is indicated, ask if the user wants to change the release type to "web" (no logfile required), ignore the lack of logfile and continue the upload or cancel it :returns conti...
7a1bbe051954d243e213a1dbc1a0a233eb6faf22
646,376
def mim2gene_lines(): """Returns some lines in mim2gene format, including header""" lines = [ "# Copyright (c) 1966-2016 Johns Hopkins University. Use of this file " "adheres to the terms specified at https://omim.org/help/agreement.\n", "# Generated: 2017-02-02\n", "# This file ...
a026118fb511c90db5ab9264157e31808d7d8c8a
646,377
def roc_to_common_era(date: str): """Turn ROC era string to common era e.g. 105/01/01 -> 2016/01/01 """ year = int(date[:3]) + 1911 return f"{year}{date[3:]}"
745a5fcd377f17c44d53c0778a2ae355b310d006
646,378
def inv_min_max_norm(x, min_x, max_x): """ Computes the inverse min-max-norm of input x with minimum min_x and maximum max_x. """ return x * (max_x - min_x) + min_x
e9889e5dc22f9a7c47a95b31bcf0cf758732ef1c
646,379
def is_top(module_index): """Returns True if module is in the top cap""" return ( (module_index>=736)&(module_index<832) )
c89d7050cad257fa6f826e41c03ae96e6a95c38c
646,381
def my_function(a, b): """Returns a * b. >>> my_function(['A', 'B'], 3) #doctest: +NORMALIZE_WHITESPACE ['A', 'B', 'A', 'B', 'A', 'B',] This does not match because of the extra space after the [ in the list. >>> my_function(['A', 'B'], 2) #doctest: +NORMALIZE_WHITESPACE [ 'A...
d01887162ba68b4f1c76f542485b855067ba2d7b
646,384
import os def pathname_to_run_name(base): """ Convert a pathname to a base runfolder name handle the case with a trailing / >>> print pathname_to_run_name("/a/b/c/run") run >>> print pathname_to_run_name("/a/b/c/run/") run >>> print pathname_to_run_name("run") run >>> print pathname_to_run_name("...
716799b607fedb0ce2223d9fdc9bffc6c7133c4f
646,385
from typing import List from typing import Dict from typing import Any def prepare_queue_details_get_output(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ Prepares context output for queue_details_get command. :param records: List containing dictionaries of queue records. :return: prepar...
884d6c1cf6d841c68338e41d852e80f607150986
646,386
def sort_files(args): """Sort the input files.""" file_dict = {} file_dict['GHG-only'] = sorted(args.ghg_files) file_dict['AA-only'] = sorted(args.aa_files) file_dict['historical'] = sorted(args.hist_files) nfiles = len(file_dict['GHG-only']) assert len(file_d...
9c62be5f052da2f36b663395793ac65713890198
646,387
def _get_histogram_settings(agg): """ Get the settings for a histogram aggregation :param agg: the histogram aggregation json data :return: dict of {setting_name: setting_value} """ histogram_settings = dict(field=agg['field']) settings = agg['settings'] histogram_settings['interval'] ...
fbc7e844be3dbb1196c3d0a0ccce30128aebaee5
646,388
def test_desc_with_no_default(test_arg): """ this is test for description decoration without default parm value :param test_arg: :return: """ print('this.is decr without any default value') return {}
2f96db55dd73553a7204cb822da14ad2a5bd59a8
646,389
def escaped(val): """ escapes a string to allow injecting it into a json conf """ val = val.replace('\\', '/') val = val.replace('"', '\"') return val
6f8b6b66bf78b175042a268b85df275a3eafd2e2
646,390
def calc_an_sparsity(L, q, K): """Calculates sparsity of Adjacent Neighborhood scheme""" return 1 + L*(q-1)*q**(K-1)
0fc6f63a1f417c46a26721fcf82e9dc0c827cc6c
646,391
import sys import os def save_badge(badge, filepath, force=False): """ Save badge to the specified path. """ # Validate path (part 1) if filepath.endswith("/"): print("Error: Filepath may not be a directory.") sys.exit(1) # Get absolute filepath path = os.path.abspath(file...
f1052000d489d0117cb20f067d20243977052678
646,392
def rightjustify(linetext, linecount, max_countwidth): """Justify ordered line to the right Arguments: linetext {str} -- a text to justify linecount {int} -- a line count (1-based) max_countwidth {int} -- a maximum count width Returns: str -- a justified line """ fi...
4ed7ecb2fe4c26fe944496d8b50e44889b4cb29e
646,394
def cut_text(value): """ returns a cut string if its length is greater than 50 chars """ return value if len(value) <= 50 else f"{value[:50]}..."
f290035c7a36edd526d45262396d1c47cbd56d0c
646,395
def menu_principal(request): """ Funcão que contém as configurações do menu principal do Cont2. Retorna um dicionário com as configurações """ menu_buttons = [ {'link': '/almoxarifado/cont/cadastros', 'text': 'Cadastros'}, {'link': '/almoxarifado/cont/entrada-1', 'text': 'Entrada de...
30ed270334b4f2000ce28f9b07afd69dd876f478
646,396
def getInputs(tx): """ The getInputs function is a small helper function that returns input addresses for a given transaction :param tx: A single instance of a Bitcoin transaction :return: inputs, a list of inputs """ inputs = [] for input_addr in tx['inputs']: inputs.append(...
2ee5de01006242c6339c32c463b3f92795e1900e
646,397
import threading def threadsafe_function(fn): """ Decorator for making sure that the decorated function is thread safe. http://stackoverflow.com/questions/1072821/ """ lock = threading.Lock() def new(*args, **kwargs): lock.acquire() try: r = fn(*args, **kwargs) ...
fb50f4759b50daf5f17698bf9fbbf5e939521425
646,398
def clean_openslide_keys ( properties_dict ): """Openslide returns dictionaries that have . in the keys which mongo does not like, I need to change this to _""" cleaned_dict = {} for k,v in properties_dict.iteritems(): new_key = k.replace('.','_') cleaned_dict[new_key] = v retur...
2b6ad8b05388c0fe4164390fd7a5aeb04b8b9cae
646,399
import math def cramers_V_calc(phi_square, classes): """ Calculate Cramer's V. :param phi_square: phi_squared :type phi_square : float :param classes: confusion matrix classes :type classes : list :return: Cramer's V as float """ try: return math.sqrt((phi_square / (len(cl...
1c85f8dac6d384990496f1a88d32bbd7fe48cef4
646,400
import json import codecs def write_json(filename, obj): """Write JSON.""" fail = False try: j = json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) with codecs.open(filename, 'w', encoding='utf-8') as f: f.write(j + "\n") except Exception: fail = Tr...
25b4ea17887d541644adbdc87af70f8d245df922
646,401
def WriteResponseFile(fnames): """WriteResponseFile(fnames) writes the file names to hdrstack """ f = open('hdrstack', 'w') for name in fnames: f.write(name +'\n') f.close() return True
e1fb155e9b2e46e9bba4e3e5e727c8ec43e5d53d
646,402
import re def filter_sequence_search_subjects(_from, uris): """ Adds filters to SPARQL based on the allowed graphs and URI's from sequence search [description] Arguments: _from {list} -- List of allowed graphs uris {list} -- List of URI's from sequence search """ from...
8bce3ba2b63127c81eacdd7c949b7adcb927f389
646,403
def load_select_choices_or_calculations(value): """load select_choices_or_calculations""" return value
47d86305bf3a855a08c2e0a5d75a6b4399b3f968
646,404
def unescape(s: str) -> str: """ :说明: 对字符串进行 CQ 码去转义。 :参数: * ``s: str``: 需要转义的字符串 """ return s.replace("&#44;", ",") \ .replace("&#91;", "[") \ .replace("&#93;", "]") \ .replace("&amp;", "&")
4c313abe0d8b1e1df2275f5466a44bdbda64cb7c
646,405
import re def remove_amp_references(txt: str) -> str: """Remove references to amp.""" txt = re.sub("^amp/", "", txt, flags=re.MULTILINE) txt = re.sub("/amp/", "/", txt, flags=re.MULTILINE) txt = re.sub("/amp:", ":", txt, flags=re.MULTILINE) return txt
7fee823504caf3bffb76540764a83ea2e4699950
646,406
def timeargs(request): """Fixture for default function and args to use with timing functions. Covers no arg, positional-only args, and keyword-only args cases. Parameters ---------- request : _pytest.fixtures.FixtureRequest Built-in pytest fixture. See the pytest documentation for details....
44ca96b74836b8d021df76bce72734759a391b31
646,407
from pathlib import Path def list_run(dname): """List all .dat files in a directory.""" path = Path(dname) return sorted(list(path.glob('*.dat')))
d9d9e6485f04aab9e69c8ca3b596d8fb87771596
646,408
def RemoveSparse(freq, opts): """ # RemoveSparse(tdm, Y) # Remove sparse terms (terms which are very rare etc.) - Y is a way to subset tdm - automatically implement the default Y that is suggested """ if opts.remove_n_sparse: head = freq.sort('sum', ascending=Tru...
08308986cf88ff13cd7bc20878abda96c3e2f55d
646,409
def residue_points(m): """Return a dictionary with each residue and the numbers that produce it""" D = {} for i in range(m): r = (i**2) % m if str(r) in D: D[str(r)].append(i) else: D[str(r)] = [i] return D
9ecdf64f20f53119bbbf1af3af790251cac9de9b
646,410
def collate_masks(values, pad_idx, eos_idx, left_pad_source, left_pad_target): """Convert a list of 2d tensors into a padded 3d tensor.""" size_0 = max(v.size(0) for v in values) size_1 = max(v.size(1) for v in values) res = values[0].new(len(values), size_0, size_1).fill_(pad_idx) def copy_tensor...
aeffb2f278a33ce8f12f28d9ef118efdbfa35e3f
646,411
def transpose(matlist, K): """ Returns the transpose of a matrix Examples ======== >>> from sympy.matrices.densetools import transpose >>> from sympy import ZZ >>> a = [ ... [ZZ(3), ZZ(7), ZZ(4)], ... [ZZ(2), ZZ(4), ZZ(5)], ... [ZZ(6), ZZ(2), ZZ(3)]] >>> transpose(a, ZZ) ...
2f3909e6c7bd0d554520c8d240d7630e0620f3f5
646,412