content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def dont_linkify_urls(attrs, new=False): """Prevent file extensions to convert to links. This is a callback function used by bleach.linkify(). Prevent strings ending with substrings in `file_exts` to be converted to links unless it starts with http or https. """ file_exts = ('.py', '.md', '.sh'...
e0ab3b0a004a2f6a3adca9ca24f0c33c6fc34d3a
658,610
def find_pareto_front(population): """Finds a subset of nondominated individuals in a given list :param population: a list of individuals :return: a set of indices corresponding to nondominated individuals """ pareto_front = set(range(len(population))) for i in range(len(population)): ...
2e53edda5e3d3afd541cedff3bb3d247f913969c
697,316
from pathlib import Path import string import random def make_random_dir_path() -> Path: """ Creates a fully-qualified Path to a fake directory. The directory path is guarantee to begin with / and starts with no special characters other than /. The branch_depth of the path (ie /one/two/three has a depth o...
adea6a44228e4c6781f10334f0a62c32c5f29d6f
185,172
import torch def load_model(filename, model): """Load the model parameters in {filename}.""" model_params = torch.load(str(filename)) model.load_state_dict(model_params) return model
14cb058d61dedc1ad4b41b0aab09a4ce56db37a1
673,612
def aliquot_sum(input_num: int) -> int: """ Finds the aliquot sum of an input integer, where the aliquot sum of a number n is defined as the sum of all natural numbers less than n that divide n evenly. For example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is a simple O(n) implementation. ...
d7839f10d54c44f61525835d2947b09780666b4f
323,265
async def convert_media_format(media_format): """Translates media format names into norwegian""" media_formats = { 'TV': 'TV-Serie', 'TV_SHORT': 'Kort TV-Serie', 'MOVIE': 'Film', 'SPECIAL': 'Ekstramateriale', 'MUSIC': 'Musikk', 'MANGA': 'Manga', 'NOVEL': ...
bd338c984baf9fa46f2f427c8965ff2331198a76
576,926
def wrap(x, m): """ Mathematical modulo; wraps x so that 0 <= wrap(x,m) < m. x can be negative. """ return (x % m + m) % m
7cd3b2e5f2edcd09f093cf29f9dc09e3eb97e2ed
485,919
import json def fluent_list_output(value): """ Return stored json representation as a multilingual dict, if value is already a dict just pass it through. """ if isinstance(value, dict): return value try: result = json.loads(value) return {k: v if isinstance(v, list) els...
1155137a37237e41066c95910e30f2d5a18c467c
553,413
import requests def is_license_valid(key): """Checking License Key from External API Args: key (str): Serial Key for Raven Restocks Returns: bool: If the key is valid """ r = requests.post( 'https://xserver.boxmarshall.com/api/v2/authorize/validate/no-device', json={"seri...
d42e9be643380a095d361d5e668c923218996e0a
281,420
def write_alarm_msg(radar_name, param_name_unit, date_last, target, tol_abs, np_trend, value_trend, tol_trend, nevents, np_last, value_last, fname): """ writes an alarm file Parameters ---------- radar_name : str Name of the radar being controlled ...
f734983e1aa59cb9c17a2e3988d870625f9aee3d
101,983
def get_contents(collection_id, collections_referenced): """Return the ``contents`` value of the collection with ``collection_id`` as its ``id`` value. :param int collection_id: the ``id`` value of a collection model. :param dict collections_referenced: the collections (recursively) referenced by a collect...
9d5db9a2b4338a1bd6ba311361018a73bae386bb
353,917
def _ifOnlyWalk(row): """Helper funtion to return True if row only contains Walk mode.""" modes = set(row.split(",")) walkExist = "Mode::Walk" in modes length = len(modes) == 1 return walkExist & length
61fa0c853936dd53dd8981aa25f63a3a2488565b
565,233
def add_header(response): """ Append after request the nessesary headers. """ response.headers['Access-Control-Allow-Headers'] = "accept, content-type" return response
0d8367134570e39838c5af060186f74a841eda9f
209,649
def sz_to_ind(sz, charge, nsingle): """ Converts :math:`S_{z}` to a list index. Parameters ---------- sz : int Value :math:`S_{z}` of a spin projection in the z direction. charge : int Value of the charge. nsingle : int Number of single particle states. Returns ...
c6016a5f21f4a4e9904046260b94b1f4d6d397ba
49,391
def load_file(infile): """Read and return text file as a string of lowercase characters.""" with open(infile) as f: loaded_string = f.read().lower() return loaded_string
0a78a660ddabc897f1c8344c4588e59700687f09
613,671
def get_inputs(depthdata_str_list): """ Given a list of strings composed of 3 floating pt nbrs x, y, z separated by commas, convert them to floats and return them as 3 individual lists. :param depthdata_str_list: list of floating point string pairs, separated by a comma (think .csv file) :return: ...
397937ca85dbd2836582ef37ae193f9929b79ab0
678,755
def _user_can_edit(user, group_profile): """Can the given user edit the given group profile?""" return user.has_perm("groups.change_groupprofile") or user in group_profile.leaders.all()
9ebcea9592b821fe3ec3a25186204342c119815c
105,157
def _set_default_capacitance( subcategory_id: int, style_id: int, ) -> float: """Set the default value of the capacitance. :param subcategory_id: :param style_id: :return: _capacitance :rtype: float :raises: KeyError if passed a subcategory ID outside the bounds. :raises: IndexError...
2b016bf2a8f4006fcff6c6b081037a0ff589f0de
205,251
def test_file(test_dir): """ Returns path to the file with `filename` and `content` at `test_dir`. """ def wrapper(filename: str, content: str): file = test_dir / filename file.write_text(content, encoding="utf-8") return file return wrapper
e4e9d500ba7c5227add47833bdc8d3be3a8d4252
45,447
def obj_name(obj, oid): """Return name of folder/collection object based on id Args: obj - dict oid - string """ return obj[oid]['name']
8ae962c271e89fb034221432cae461b8f6500b72
360,320
def CompressList(lines, max_length, middle_replacement): """Ensures that |lines| is no longer than |max_length|. If |lines| need to be compressed then the middle items are replaced by |middle_replacement|. """ if len(lines) <= max_length: return lines remove_from_start = max_length / 2 return (lines[:re...
4ef04859c70a71055272a28e6634cdb3e4d269e4
302,624
def avgCl(lst): """return the average RGB of a RGB list""" c1=c2=c3=0 n = len(lst) for c in lst: c1+=c[0] c2+=c[1] c3+=c[2] c1,c2,c3=c1/n,c2/n,c3/n return [c1,c2,c3]
289728e3870adf7affe0d76001b46333428edd2f
117,387
def gist_namer(art_title, num): """ Create formatted gist name to help with grouping gists Parameters ---------- art_title : str defaults to the notebook name num: int gist count for this article e.g. first gist of article is 0 """ # lower case and snake_case the whole th...
5b7cff7b91b291870e9e8d913875af14e44f3c08
169,297
def retag_from_strings(string_tag) : """ Returns only the final node tag """ valure = string_tag.rfind('+') if valure!= -1 : tag_recal =string_tag [valure+1:] else : tag_recal = string_tag return tag_recal
5bef884498efb19eb354bb6119450c9c25a19e1c
700,817
def removesuffix(s, suffix): """ Removes suffix a string :param s: string to remove suffix from :param suffix: suffix to remove :type s: str :type suffix: str :return: a copy of the string with the suffix removed :rtype: str """ return s if not s.endswith(suffix) else s[:-len(su...
7503e7ca390434936cdda8f706f5ca1eb7b80b98
24,437
def st_rowfreq(row,srate,length): """ for a row in a stockwell transform, give what frequency (Hz) it corresponds to, given the sampling rate srate and the length of the original array """ return row*srate/length
283405aa5c3ae96d96a98b84e0533d5f78f4eef3
310,507
def convert_labels(df, columns=['label'], reverse=False): """ Convert labels in provided columns to numeric values (or back to text). Edits the dataframe in place. """ if reverse: labels_vals = { 0: 'Refuted', 1: 'Supported', 2: 'NotEnoughInfo' } else: ...
155e7171811dd4d9c1b819affb4ee7a23b56b5c9
85,115
def select_bboxes_via_score(bboxes_list, scores_list, score_thr): """Select bboxes with scores >= score_thr. Args: bboxes_list (list[ndarray]): List of bboxes. Each element is ndarray of shape (n,8) scores_list (list(list[float])): List of lists of scores. score_thr (float):...
e3bd82706cb79b0385d1a7c5cc45e0a6637ec841
331,144
def fetch_all_views(eng): """ Finds all views. """ tables = eng.execute("SELECT table_name from information_schema.views;") return [table[0] for table in tables if "exp_view_table" in table[0]]
583abe6efe1c42c27daaf6fbc5b44c4b276e1ded
124,352
def add_argument(parser, flag, type=None, **kwargs): """Wrapper to add arguments to an argument parser. Fixes argparse's behavior with type=bool. For a bool flag 'test', this adds options '--test' which by default sets test to on, and additionally supports '--test true', '--test false' and so on. Finall...
d802615f737c806be97962f18fdd7e8057512f96
15,239
def elevation(location): """Return the elevation field of a location.""" return location[2]
6509a4f7d59d56a94f7c9e8b199a3911c33c72bc
302,052
import math def distance(M, node_1, node_2): """Computes the Euclidean L2 Distance.""" x1, y1 = M.intersections[node_1] x2, y2 = M.intersections[node_2] return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
c4b8cc9d5c352d6a4399926c4495c3cb072ad876
508,210
def audit_renamed_col_dict(dct: dict) -> dict: """ Description ----------- Handle edge cases where a col could be renamed back to itself. example: no primary_geo, but country is present. Because it is a protected col name, it would be renamed country_non_primary. Later, it would be set as pr...
5f70bbce182e3cccbe22d13975f02b941c01c090
233,738
def _mangle(cls, name): """ Given a class and a name, apply python name mangling to it :param cls: Class to mangle with :param name: Name to mangle :return: Mangled name """ return f"_{cls.__name__}__{name}"
8b789a03b2f25c71bc661cc1eb394650087128b9
40,397
import torch def sample_pdf( bins: torch.Tensor, weights: torch.Tensor, N_samples: int, det: bool = False, eps: float = 1e-5, ): """ Samples a probability density functions defined by bin edges `bins` and the non-negative per-bin probabilities `weights`. Note: This is a direct con...
8d706ef5952a3c4ff5081a04d22f2e5fd4b2045b
680,607
def insert_user(cursor,username,hash_pw): """ Insert a new user in the database Parameters: ----------- cursor: Psycopg2 cursor Cursor of type RealDict in the postgres database username : Str name of the user hash_pw : Str encrypted password of the user (to be teste...
0fe9f192bf50e95392ffa0fb5d6e2bf42d5bd627
329,243
def rectanglesOverlap(r1, r2): """Check whether r1 and r2 overlap.""" if ((r1[0] >= r2[0] + r2[2]) or (r1[0] + r1[2] <= r2[0]) or (r1[1] + r1[3] <= r2[1]) or (r1[1] >= r2[1] + r2[3])): return False else: return True
bf1022196956dd01694084c65ba54a7b597b0fd0
100,527
def select_shape(input_shape, slice_point, axis=1): """ calculate the output shape of this layer using input shape Args: @input_shape (list of num): a list of number which represents the input shape @slice_point (list): parameter from caffe's Slice layer @axis (int): parameter from caff...
ba468d2a7d7f52055082d9ae34ea2dac41d9802e
204,278
def _dtype_descr(dtype): """ Get a string that describes a numpy datatype. :param dtype: The numpy datatype. :return: A string describing the type. """ if dtype.kind == 'V': return dtype.descr else: return dtype.char
690c98fdd787313317182c647e64ccb8784ca9ad
136,754
from typing import Dict def parse_guid(guid: str) -> Dict[str, int]: """ Parse a guid back to its four constituents Args: guid: a valid guid str Returns: A dict with keys 'location', 'work_station', 'sample', and 'time' as integer values """ guid = guid.replace('-',...
b76994b2da80b750fb09e33bda6ac4a05dd9d1b1
615,627
def GetInputs(var, env): """Expands an env substitution variable and returns it as a list of strings.""" return [str(v) for v in env.subst_list(var)[0]]
ee0deb1c4f25d732fcb93c2dd96f3bb162fefcbf
456,751
def parse_gage(s): """Parse a streamgage key-value pair. Parse a streamgage key-value pair, separated by '='; that's the reverse of ShellArgs. On the command line (argparse) a declaration will typically look like:: foo=hello or foo="hello world" :param s: str :rtype: tuple(key, value) ...
299b47f3a4757c924620bdc05e74f195a4cb7967
709,261
def last_support(entry): """Find the last friendly action between the players""" seasons = entry['seasons'] last_support = None for season in seasons[:-1]: if 'support' in season['interaction'].values(): last_support = season['season'] return last_support
ee997b73a428b99d47819db1c80db077d9a78ddd
426,539
def draw_sure(deck, n, exclusions): """Draw n cards from a deck but skip any cards listed in exclusions. Please note this func always returns a list, unlike native deuces draw function. """ drawn = [] while len(drawn) < n: c = deck.draw() if c in exclusions + drawn: c...
4e43998962e15916b397843cb1ea254b10a1c1b9
618,350
def getPointRange(iFace, dims): """Return the correct point range for face iFace on a block with dimensions given in dims""" il = dims[0] jl = dims[1] kl = dims[2] if iFace == 0: return [[1, il], [1, jl], [1, 1]] elif iFace == 1: return [[1, il], [1, jl], [kl, kl]] elif i...
63945a7ae725fdda799deb7e20090a60101c326a
441,597
def pypi_link(pkg_filename): """ Given the filename, including md5 fragment, construct the dependency link for PyPI. """ root = 'https://files.pythonhosted.org/packages/source' name, sep, rest = pkg_filename.partition('-') parts = root, name[0], name, pkg_filename return '/'.join(parts)
1f71b2c6c34b52a60c2ead14b40e98ef0c89a8cf
16,844
def _manifest(package_name): """ Helper function to create an appropriate manifest with a provided package name. :pram package_name The package name used in the manifest file. """ return """ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="{}" > <uses-sdk ...
f7da2c1285558327f143e4ca231ba7586c1acb58
150,846
import re def avg_word_length(text): """ Averages the word length in `text` :param text: The text to analyze (str) :return: average_word_len (float) """ words = re.sub(r'[\.\?!]', '', text).split() return sum(len(word) for word in words) / len(words)
ef710c291d0a29a2969818ade60a93b111f471da
249,976
def generate_outpath(filepath): """ Generates the output name for an input nii.gz file by appending 'noise' to file name. """ parts = filepath.split('.') prefix = '.'.join(parts[:-2]+['noise']) return prefix
4a041b847aee153bd693ca6113a9ac5c71cd01d3
339,206
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. The idea is to put 0 and 2 in their correct positions, which will make sure all the 1s are automatically placed in their right positions Args: input_list(list): List ...
a88ebdb718c42140bdec5aafbf352ff8f403e3f7
253,296
def ft2m(ft): """feet -> meters""" return 0.3048*ft
8ab872d97eb8adcc2cbf72bae270ea5e9045a5ff
673,760
def split_by_unescaped_sep(text, sep=':'): """Split string at sep but only if not escaped.""" def remerge(s): # s is a list of strings. for i in range(len(s) - 1): n_esc = len(s[i]) - len(s[i].rstrip('\\')) if n_esc % 2 == 0: continue else: ...
6eb360787a3ba5e08f499d2a3352d1170d2fcf89
39,166
def discretize(pde, geo, time_nsteps=None, space_nsteps=None): """ Discretize PDE and Geometry Parameters: pde (PDE): The partial differential equations. geo (Geometry): The geometry to be discretized. Returns -------- pde_disc: PDE Rese...
1f2e8df5a143b056892a53a71ec2baa0d2d1c92f
421,527
import hmac import hashlib import base64 def sign(message, secret): """Compute a Base64-encoded HMAC-SHA256. Arguments: message (unicode): The value to be signed. secret (unicode): The secret key to use when signing the message. Returns: unicode: The message signature. """ ...
96aba415aa95e9bfb59d01e6b88b2d4034d213b3
496,540
import re def get_flex_counters(module): """ @summary: Parse output of "counterpoll show" command and convert it to the dictionary. Composed dictionary example: {'PG_WATERMARK_STAT': {'Interval': '10000', 'Status': 'enable'}, 'PORT_STAT': {'Interval': '10000', 'Status...
8c8205c52dd8b08f4434297ebf39846197b6f74f
543,936
def convert_period_into_pandas_freq(period_str): """converts the period into a frequency format used by pandas library. Args: period_str (string): period in string format using m, h and d to represent minutes, hours and days. Returns: string: new value for period according to pandas frequency format...
e471ee8a2b6bdb384d4db089ac3a62d9658ef69b
92,388
def newline_join(string, line_length): """ Inserts newline into the string. Newline is inserted at first the word boundary after the line_length characters. Parameters ---------- string : str String to insert newlines into. line_length : int Line length threshold after whic...
771f6f41876f8ed004eb26f73970801e0a8ad247
552,059
def Odds(p): """Computes odds for a given probability. Example: p=0.75 means 75 for and 25 against, or 3:1 odds in favor. Note: when p=1, the formula for odds divides by zero, which is normally undefined. But I think it is reasonable to define Odds(1) to be infinity, so that's what this function ...
f4e40f290b4207a9262d4f4ed6014bead0eec92a
179,028
def seq_to_kmers(seq, k=3): """ Divide a string into a list of kmers strings. Parameters: seq (string) k (int), default 3 Returns: List containing a list of kmers. """ N = len(seq) return [seq[i:i+k] for i in range(N - k + 1)]
77901b378a329529955a1852419662ae2d7acbec
248,247
def make_shape_channels_first(shape): """Makes a (N, ..., C) shape into (N, C, ...).""" return shape[:1] + shape[-1:] + shape[1:-1]
db3315f9191957a6f0395f17273d32cb8f954ef3
446,038
import itertools def flatten(ls): """ flatten a nested list """ flat_ls = list(itertools.chain.from_iterable(ls)) return flat_ls
46c9ce5b089cae4ee67876b4f5e798dbf334036d
54,845
import json def get_placeholder_value_given_type(value): """Given an a parameter type, return a placeholder value""" # string, array, object, boolean, integer, float, or datetime. if value.lower() == "string": return json.dumps("") elif value.lower() == "array": return [] elif valu...
e8e8b6f6730b6ed301e57aac0938714588ce8467
461,916
def is_dos_style_abspath(path): """ Check whether the given path is a DOS/Windows style absolute path. path: A path string """ if len(path) < 3: return False drv = path[0] # drive letter # A:65, B:66, ... Z:90, a:97, b:98, ... z:122 if ord(drv) < 65 or (ord(drv) > 90 and ord(dr...
167f2a00a15897f6fcfc6aeb1785b0b97ae3fb22
489,291
def subsample(data_array, subsample_interval): """ Subsample every points_per_sample points """ return data_array[..., 0::subsample_interval]
514f667052e6a5135eac7df91052839b49120a0a
139,845
def find_next_empty(puzzle): """ Takes a puzzle as parameter Finds the next row, col on the puzzle that's not filled yet (with a value of -1) Returns (row, col) tuple or (None, None) if there is none """ for row in range(9): for col in range(9): if puzzle[row][col] ==...
fd56f9c46659cb9c4e21bc00c984ef55a5238f1e
516,707
def is_defined(value): """Return True IFF `value` is not 'UNDEFINED' or None. >>> is_defined("UNDEFINED") False >>> is_defined(None) False >>> is_defined("FOO") True """ return value not in ["UNDEFINED", None]
2776c6df504b0d2aca148bd8c69e341fcab2f9c7
531,470
def _mpas_to_netcdf_calendar(calendar): """ Convert from MPAS calendar to NetCDF4 calendar names. """ if calendar == 'gregorian_noleap': calendar = 'noleap' elif calendar != 'gregorian': raise ValueError('Unsupported calendar {}'.format(calendar)) return calendar
bdeaf343deeb4beb8c04654ab5104425396e98be
27,535
def cut_rod2(p, n, r={}): """Cut rod. Same functionality as the original but implemented as a top-down with memoization. """ q = r.get(n, None) if q: return q else: if n == 0: return 0 else: q = 0 for i in range(n): ...
2fa1433dffb9099709e466025645c4981f289692
10,270
import requests def follow_url(URL): """ Just a wrapper function that automatically raises an error if there's issues requesting. """ r = requests.get(URL) r.raise_for_status() return r.text
1fae5b04f25b1509fdaf71855b3ad0de2cc228e1
342,978
def risk_level(value): """ Returns a string based risk level from a number. 1: Low 2: Medium 3: Medium 4: High """ if value == 1: return 'low' if value == 2 or value == 3: return 'medium' if value == 4: return 'high'
1afa4f2a74956a5e2eebf030ed2183dae7bd9227
267,375
def _cv_delta(x, eps=1.): """Returns the result of a regularised dirac function of the input value(s). """ return eps / (eps**2 + x**2)
8dcfc19acd0f311ea7ffa12c2a1d7b806d69c59b
595,866
def bezier_sample(t, params): """Sample points from cubic Bezier curves defined by params at t values.""" A = params.new_tensor([[1, 0, 0, 0], [-3, 3, 0, 0], [3, -6, 3, 0], [-1, 3, -3, 1]]) t = t.pow(t.new_tensor([0, 1, 2, 3])...
3e57054df8ee955b40ae3dbb375589c44eb72b2e
440,345
import _warnings def snap_to_lines(fixation_sequence, text_block, method="warp", **kwargs): """ Deprecated in 0.4. Use `eyekit.fixation.FixationSequence.snap_to_lines()`. """ _warnings.warn( "eyekit.tools.snap_to_lines() is deprecated, use FixationSequence.snap_to_lines() instead", Fut...
f7357c2ea56dc928b6e209ad5361dfd8157808e9
323,530
def is_valid_interval(interval): """Checks if the given interval is valid. A valid interval is always a positive, non-zero integer value. """ if not isinstance(interval, int): return False if interval < 0: return False return True
18c41942e6b72251d618653516232eb74c8b5097
59,661
def get_node_info(node, ws): """ Args: node (Node): ws (list(int)): knowledge weights. [cdscore, rdscore, asscore, stscore] Returns: return node information for a searched tree analysis node information: self node, parent node, depth, score, RDScore, CDScore, STScore, ASScor...
d17ce544acbedc6171b1af11a27b1a3356ea3a0e
67,258
import ipaddress def is_ipv4(ip: str): """Return True if given address is a valid IPv4 address, otherwise return False""" try: ipaddress.IPv4Address(ip) except ipaddress.AddressValueError: return False return True
3efccd8d5b969d53a26f4b0bc52db909fe160213
293,145
def mutate_string(string, pos, change_to): """ Fastest way I've found to mutate a string @ 736 ns >>> mutate_string('anthony', 0, 'A') 'Anthony' :param string: :param pos: :param change_to: :return: """ string_array = list(string) string_array[pos] = change_to retur...
c6119076411b57f9ded2e899d40b6b82bb5f7836
12,855
def create_minio_dispatcher_node(name): """ Args: name(str): Name of the minio node Returns: dict: A dictionnary with the minio node configuration """ return { "endpoint_url": "http://{:s}:9000/".format(name), "aws_access_key_id": "playcloud", "aws_secret_acce...
df313dfa7152944332551dd70aab4b0a0e36ff56
643,358
def activeTT_init(M): """ Initialize list of tour types that can be used in this problem instance :param M: Model :return: list of tour type indexes """ return [t for t in M.TTYPES if M.tt_ub[t] > 0]
b90006e640569b92fb6d1eb196564bdec5898b11
448,089
def get_other_person_from_match(user_id, match): """given a Match, return the Person corresponding to the user who is NOT the passed user ID (i.e. the other Person) """ if match.person_1.user_id == user_id: return match.person_2 elif match.person_2.user_id == user_id: return match.pe...
5ee3af4a095d084eb8685cb044c2df2ea365d65d
359,314
def partition_from_ragged_tensor_by_name(ragged_tensor, partition_type: str): """Extract row partition tensor from ragged tensor defined by string identifier of the partition scheme. Args: ragged_tensor (tf.RaggedTensor): Ragged tensor to extract row partition from. partition_type (str): String...
dfc449f5dd044d61ae54a676ff2a00a91ba570bf
239,295
def lerp(value1=0.0, value2=1.0, parameter=0.5): """ Linearly interpolates between value1 and value2 according to a parameter. Args: value1: First interpolation value value2: Second interpolation value parameter: Parameter of interpolation Returns: The linear intepolatio...
dc37e08e0e586e19a565dd9c48995e1de811c512
323,112
def trim_variant_fields(location, ref, alt): """ Trims common prefixes from the ref and alt sequences Parameters ---------- location : int Position (starting from 1) on some chromosome ref : str Reference nucleotides alt : str Alternate (mutant) nucleotide Ret...
c211b2a62d38dfcecf0351d0fa62e9cc70baf974
375,714
def ensure_quotes(s: str) -> str: """Quote a string that isn't solely alphanumeric.""" return '"{}"'.format(s) if not s.isalnum() else s
650a58a0b33350b661a698c206ac02b729b25fc7
144,952
import math def keep_top_genes(counts, num_genes_discard, criteria="Variance"): """ This function takes a matrix of counts (Genes as columns and spots as rows) and returns a new matrix of counts where a number of genesa re kept using the variance or the total count as filtering criterias. :param c...
ed364e66d35b9ae035cc3d2af16e0fbeb355e1ed
383,804
import re def fixSlashes(url): """ Removes double slashes in URLs, and ensures the protocol is doubleslahed """ # insert missing protocol slashes p = re.compile( '(:/)([^/])' ) url = p.subn( r'\1/\2', url)[0] # strip any double slashes excluding :// p = re.compile( '([^:])//' ) ...
8213ff86e85d49a829f4eff8627a97c33e984a9e
687,871
import math def days_to_hmsm(days): """ Convert fractional days to hours, minutes, seconds, and microseconds. Precision beyond microseconds is rounded to the nearest microsecond. Parameters ---------- days : float A fractional number of days. Must be less than 1. Returns ----...
94d454bbcae30e043b8017f2903bc1e19489226d
304,999
def filter_resources(resource, filter_name, filter_value): """Filter AWS resources Args: resource (object): EC2 resource filter_name (string): Filter name filter_value (string/list): Filter value(s) Returns: List: Filtered AWS resources "...
d72f091af78ec73a81a50dc02cbeefde94de58d9
19,419
def read_prophage_table(infile): """ Reads tab-delimited table with columns for: 1 - path to GenBank file, 2 - replicon id, 3 - prophage start coordinate, 4 - prophage end coordinate, 5 (optional) - prophage name (if not provided pp1, pp2, etc. will be assigned for each file) :param...
22ce00548ff0fb1fa9ee45c51269bfa40babc512
126,251
import struct def read_uint(buf, endianness=""): """ Reads an unsigned integer from `buf`. """ return struct.unpack(endianness + "H", buf.read(2))[0]
19e9a962e9d8e66fe04832cf6bfcac72c19943b0
71,527
def _is_A_list_company_symbol(code: str) -> bool: """测试code是否是符合A股代码要求的字符串 Precondition ======================================================================================= :param code: A股代码 Post condition ======================================================================================...
3b139cc1726682d8c2a363d765fc112a7822de5c
377,671
import requests def url_exists(url): """Check if a given url exists.""" codes = [200, 302] # 200 OK, 302 Found return True if requests.head(url).status_code in codes else False
19d0221f0169a0338c9d114999e26c0a86c473cf
479,782
def get_text(soup): """ Extracts text from the page source PARAMS: soup:BeautifulSoup object - page source converted to BeautifulSoup object RETURNS: text:str - text contents of the page """ text = "" lead = soup.find("div", {"class": "delfi-article-lead"}).text tex...
2cce80d5abad085a9b5962af6cf2d4f8bbc3eaa1
185,697
def fraction_str(numerator, denominator) -> str: """ Formats a fraction to the format %.5f [numerator/deniminator] :param numerator: :param denominator: :return: Formatted string """ if denominator > 0: return "%.5f [%.5f/%d]" % (float(numerator)/denominator, numerator, denominator) ...
280f734854551a6e1315dee34e2c4af5da1591e3
535,318
import typing def first_non_null(iterable: list) -> typing.Optional[str]: """Takes in an iterable, returns the first item that is not equal to '', if not found then None. :parameter iterable: A list that a for loop can iterate over :type iterable: list :return: The first item that is not eq...
18517a9e73f2cea1953234fc02842aedb55c445f
270,314
def ndvire3(b7, b8): """ Normalized Difference Vegetation Index Red-edge 3 \ (Gitelson and Merzlyak, 1994). .. math:: NDVIRE3 = (b8 - b7) / (b8 + b7) :param b7: Red-edge 3. :type b7: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns NDVIRE3: Index va...
965a27aec24d0a53c6d5afe23f4b2c951cf7fb17
535,704
def FormatDiffHunks(hunks): """Re-serialize a list of DiffHunks.""" r = [] last_header = None for hunk in hunks: this_header = hunk.header[0:2] if last_header != this_header: r.extend(hunk.header) last_header = this_header else: r.extend(hunk.h...
b3baa2ccc1784301a7ebf45746864f1a9bbabaa4
622,114
def _parse_r_line(line, *_): """ Parse router info line. :param line: the line :return: dict with router info """ split_line = line.split(' ') return { 'nickname': split_line[0], 'ip': split_line[5], 'dir_port': int(split_line[7]), 'tor_port': int(split_line[...
5e4befcebf6a8d254d52bf5b49f4834346dc62a2
433,594
def _conditional_field_block(if_keyword, expression, colon, comment, newline, indent, fields, dedent): """Applies an existence_condition to each element of fields.""" del if_keyword, newline, colon, comment, indent, dedent # Unused. for field in fields.list: condition = field.fie...
969d2c95e5f6724a0d65c2b72c6149d27bc4676f
240,605
def convert_bool_args(args: dict) -> dict: """Convert boolean CLI arguments from string to bool. Args: args: a mapping from CLI argument names to values Returns: copy of args with boolean string values convert to bool """ new_args = {} for k, v in args.items(): if v.low...
0f0c44faf01e26ad814b3779e62f071a56d626bf
540,872