content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def latest(scores): """ Return the latest scores from the list """ return scores[-1]
ec5bb0a18f6a86e154065d4b2e4ae089ec45ffe7
58,389
import yaml def read_yaml(infile, log=None) -> dict: """ Read YAML file and return a python dictionary Args: infile: path to the json file; can be hdfs path Returns: python dictionary """ if infile.startswith("hdfs"): raise NotImplementedError else: return yaml.safe_load(open(infile, "r"))
9c0c2ce90841119d158a72966061db3a7fa9a36a
45,701
def species_level(prediction): """Is this prediction at species level. Returns True for a binomial name (at least one space), False for genus only or no prediction. """ assert ";" not in prediction, prediction return prediction and " " in prediction
e005b7890188e5920c53629eb349e6872f87019b
418,159
def get_messages(sqs_queue, pull_batch_size=10, wait_time_seconds=5): """Get n messages from the provided sqs queue.""" messages = sqs_queue.receive_messages( MaxNumberOfMessages=pull_batch_size, WaitTimeSeconds=wait_time_seconds) return messages
0f8b2ea2518df5cce3cc21a20927e5cb7bb70711
204,237
import itertools def _get_length_sequences_where(x): """ This method calculates the length of all sub-sequences where the array x is either True or 1. Examples: x = [0,1,0,0,1,1,1,0,0,1,0,1,1] _get_length_sequences_where(x) [1, 3, 1, 2] x: An iterable containing only 1, True, 0 and False values return: A list with the length of all sub-sequences where the array is either True or False. If no ones or Trues contained, the list [0] is returned. """ if len(x) == 0: return [0] else: res = [len(list(group)) for value, group in itertools.groupby(x) if value == 1] return res if len(res) > 0 else [0]
78ae3c4a0f592df34a55ec5c71bcfbdfaf3ece43
478,040
import zlib def read_zlib_chunks(read_some, dec_size, buffer_size=4096): """Read zlib data from a buffer. This function requires that the buffer have additional data following the compressed data, which is guaranteed to be the case for git pack files. :param read_some: Read function that returns at least one byte, but may return less than the requested size :param dec_size: Expected size of the decompressed buffer :param buffer_size: Size of the read buffer :return: Tuple with list of chunks, length of compressed data length and and unused read data. :raise zlib.error: if a decompression error occurred. """ if dec_size <= -1: raise ValueError("non-negative zlib data stream size expected") obj = zlib.decompressobj() ret = [] fed = 0 size = 0 while obj.unused_data == "": add = read_some(buffer_size) if not add: raise zlib.error("EOF before end of zlib stream") fed += len(add) decomp = obj.decompress(add) size += len(decomp) ret.append(decomp) if size != dec_size: raise zlib.error("decompressed data does not match expected size") comp_len = fed - len(obj.unused_data) return ret, comp_len, obj.unused_data
04846dda234037eee25c82abbbd09ab8e77d020f
311,163
import math def evaluate(expression: str): """ Evaluate a math expression. Args: expression: string representing the math expression to be eval() Returns: result of the math expression from eval() Raises: NameError: If expression passed is not from math library Examples: >>> evaluate("5 + 2") 7 >>> evaluate("sqrt(9)") 3.0 >>> evaluate("hello - hello") Traceback (most recent call last): ... NameError: The use of 'hello' is not allowed """ # Compile the expression code = compile(expression, "<string>", "eval") allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("__")} # Validate allowed names for name in code.co_names: if name not in allowed_names: raise NameError(f"The use of '{name}' is not allowed") return eval(code, {"__builtins__": {}}, allowed_names)
f48d5db64577b5d06645a02f84bc8fda17919412
483,202
def Manhattan_dist(curr_point, goal): """ Finds the Manhattan distance of a point from the goal point """ return abs(goal[0] - curr_point[0]) + abs(goal[1] - curr_point[1])
113cd294b7fd485b249711a9d630e630f4ee5d9e
287,590
def _gf2bitlength_linear(a): """ Computes the length of a polynomial coefficient bit vector = degree + 1. Parameters ---------- a : integer Polynomial coefficient bit vector. Returns ------- n : integer length of polynomial `a`. """ n = 0 while a > 0: n += 1 a >>= 1 return n
b3d6ac750a38741109574666a97fe03d56a4091c
272,471
def height(tree): """The height of a tree.""" if tree.is_leaf(): return 0 else: return 1 + max([height(b) for b in tree.branches])
ba5ef589646022619b0f1d75d8fd701cecc6d4b9
146,616
def defaults(obj, *sources): """ Assigns properties of source object(s) to the destination object for all destination properties that resolve to undefined. Args: obj (dict): Destination object whose properties will be modified. sources (dict): Source objects to assign to `obj`. Returns: dict: Modified `obj`. Warning: `obj` is modified in place. Example: >>> obj = {'a': 1} >>> obj2 = defaults(obj, {'b': 2}, {'c': 3}, {'a': 4}) >>> obj is obj2 True >>> obj == {'a': 1, 'b': 2, 'c': 3} True .. versionadded:: 1.0.0 """ for source in sources: for key, value in source.items(): obj.setdefault(key, value) return obj
2e1752f2f31c75b8e03ef5144feea7149c3cc574
557,174
def update_haplotype(variant, reference_haplotype, reference_offset): """Updates haplotypes for a variant. A list of variant haplotypes are updated given a variant and a reference haplotype (this consists of a sequence and an offset wrt to the reference). All ALT alleles are updated as independent updated haplotypes. Args: variant: A Variant proto. reference_haplotype: A string extracted from the reference genome. reference_offset: An integer. The offset of the starting position of reference_haplotype on reference. Raises: ValueError: Variant.start is smaller than reference_offset. Returns: A list of haplotype objects. Haplotype objects are stored as dicts: {'haplotype': a haplotype (string), 'alt': an alt allele (string), 'variant': an Variant proto} """ if variant.start < reference_offset: raise ValueError('The starting position of a variant is smaller than its ', 'corresponding reference offset', variant.start, reference_offset) offset_start = variant.start - reference_offset offset_suffix = \ variant.start + len(variant.reference_bases) - reference_offset list_updated_haplotype = [] for biallelic_variant in variant.alternate_bases: updated_haplotype = reference_haplotype[: offset_start] + \ biallelic_variant + reference_haplotype[offset_suffix: ] dict_haplotype = { 'haplotype': updated_haplotype, 'alt': biallelic_variant, 'variant': variant } list_updated_haplotype.append(dict_haplotype) return list_updated_haplotype
47e69de78d24a10a7f441102587f29862b0ca18b
210,126
def remove_stop_words(content, stopwords): """Removes the stopwords in an article. :param tokens: The tokens of an article. :type tokens: []str :param stopwords: the list of stopwords :type stopwords: []str :return: The tokens of an article that are not stopwords. :rtype: []str """ return [token for token in content if token not in stopwords]
97e7ef8e92853f629d9c6e2e211d423564d865dd
653,375
import re def fix_grams(ret_str): """ Search for gram strings that have been split with whitespace and rejoin them. For instance "3 SG" will become "3SG" """ for gram in ['3SG', '1PL', '2SG', '2PL']: for i in range(1, len(gram) + 1): first, last = gram[:i], gram[i:] if first and last: expr = '%s\s+%s' % (first, last) ret_str = re.sub(expr, gram, ret_str, flags=re.I) return ret_str
6365e2fe4a20ce448ab1bc5272fd87903fca5782
156,857
import binascii def encode_domain(domain): """Given a domain with possible Unicode chars, encode it to hex.""" try: return binascii.hexlify(domain.encode('idna')) except UnicodeError: # Some strange invalid Unicode domains return None
ae2d761adcf5956b9657ea8d60d3ea202f19f241
44,583
def interpolation(alpha, t1: tuple, t2: tuple): """Return alpha * t1 + (1 - alpha * t2).""" return tuple(alpha * i + (1 - alpha) * j for i, j in zip(t1, t2))
b0a635bd30e81f4327ef0e51d7f0cf08168c3c60
353,041
def get_energy(conformer): """ A function to find the potential energy of a conformer Variables: - conformer (Conformer): the conformer object of interest Returns: - energy (float): the corresponding energy of that conformer. Will result in an error if there is no ASECalculator object attached to the ase_molecule """ energy = conformer.ase_molecule.get_potential_energy() return energy
559d589c0fc64dd30e60a12a74d08e61b06d4890
372,855
def check_all_jobs_complete(jobs): """Given a list of jobs from the DB, check that all are done processing.""" for job in jobs: if(job['status'] == 'processing'): return False return True
bc9e9adc35233e032ae25ca0826f6acd74ca2347
547,388
async def valid_content_type(content_type: str) -> bool: """Return True if supported content-type.""" if content_type.lower() in [ "text/turtle", "text/html", "application/pdf", "image/png", ]: return True return False
67e70a6d199d3f270f83c3e16b856f70040a0424
176,444
def cssname(value): """Replaces all spaces with a dash to be a valid id for a cssname""" return value.replace(' ', '-')
d374d84482d062fde387a967f7d790985e87033c
61,445
def _to_bytes(str_bytes): """Takes UTF-8 string or bytes and safely spits out bytes""" try: bytes = str_bytes.encode('utf8') except AttributeError: return str_bytes return bytes
fd16c24e80bdde7d575e430f146c628c0000bf9a
703,678
import torch def ccwh_to_xyxy(t: torch.Tensor) -> torch.Tensor: """ converts bbox coordinates from `(x_center, y_center, width, height)` to `(xmin, ymin, xmax, ymax)` """ assert t.size(-1) == 4, "input tensor must be of size `(N, 4)` with format `(x_center, y_center, width, height)`" cc = t[..., :2] wh = t[..., 2:] return torch.cat([cc - wh / 2, cc + wh / 2], dim=-1)
0e31ac7829ef8033de323a007b792ff9cb52932b
591,764
def load_paths_dict(preprocess_config): """Creates a dictionary of paths without the path to the df. This is so that the attributes for Preprocessor can be set recursively. Args: preprocess_config (dict): From loading 'create_dset.yml' Returns: paths_dict (dict): same as config['paths_params'] but without the 'train_csv_path' """ paths_params = preprocess_config["paths_params"] paths_dict = { "train_dir": paths_params["train_dir"], "test_dir": paths_params["test_dir"], "train_out": paths_params["train_out"], "test_out": paths_params["test_out"], "masks_out": paths_params["masks_out"], } return paths_dict
a417b0dc9004712329843a4d8fd34195eda33bab
396,946
def srev(S): """In : S (string) Out: reverse of S (string) Example: srev('ab') -> 'ba' """ return S[::-1]
54cef6c2fef90d4b307266664b5cdaf785de4314
137,387
def as_ascii(input_string): """Helper function to parse a byte string to an ascii string if necessary""" try: return input_string.decode('ascii') except AttributeError: return input_string
0cedf0f5a20cc78d88b6462b9682bff8bedfee55
319,363
def get_typeid(typename, field): """determine type ID (single letter indicating type) based on type name and optional field tag parsed from the URI""" if typename == 'Agent': if field in ('100', '600', '700'): return 'P' # Person else: return 'O' # Organization if typename == 'Instance': return 'I' if typename == 'Work': return 'W' # Work return 'X'
518ac505a00b5f153ce4f06b0651033858e94043
177,130
def remove_draw_parameter_from_composite_strategy(node): """Given that the FunctionDef is decorated with @st.composite, remove the first argument (`draw`) - it's always supplied by Hypothesis so we don't need to emit the no-value-for-parameter lint. """ del node.args.args[0] del node.args.annotations[0] del node.args.type_comment_args[0] return node
54fd2824abffa8cde0af85e4293d66b9e19115ea
65,596
def safe_join(separator, values): """Safely join a list of values. :param separator: The separator to use for the string. :type separator: str :param values: A list or iterable of values. :rtype: str """ _values = [str(i) for i in values] return separator.join(_values)
e6ef01fe4bcdd5fa8ed34a922b896dc10ec7eda0
631,350
def exp_smooth(new_n, new_s, new_m, old_n, old_s, old_m, a = 0.05): """ This function takes in new and old smoothed values for mean, sd and sample size and returns an exponentially smoothed mean, sd and sample size. """ smooth_n = a*new_n + (1-a)*old_n smooth_s = a*new_s + (1-a)*old_s smooth_m = a*new_m + (1-a)*old_m result = { "mean": smooth_m, "stddev": smooth_s, "n": smooth_n } return result
08c8c8c5aee12e530cd5152d8e5558fabcb68058
633,023
def Not(thing): """Not(thing) is a nicer way of saying thing.Not()""" return thing.Not()
f67ad1ce2206637598132ffe2d9a86a666d625e2
277,386
def num_add_commas(num): """ Adds commas to a numeric string for readability. Parameters ---------- num : int An int to have commas added to. Retruns ------- str_with_commas : str The original number with commas to make it more readable. """ num_str = str(num) str_list = list(num_str) str_list = str_list[::-1] str_list_with_commas = [ f"{s}," if i % 3 == 0 and i != 0 else s for i, s in enumerate(str_list) ] str_list_with_commas = str_list_with_commas[::-1] return "".join(str_list_with_commas)
c1da51505c9d442daa981c349f9bde426acef987
575,093
from typing import List def get_items_from_string(string: str, separator: str = ',', remove_blanks: bool = True) -> List[str]: """ Returns a list of items, separated by a known symbol, from a given string. """ items = [item.strip() if remove_blanks else item for item in string.split(separator)] if remove_blanks: return list(filter(None, items)) return items
ec6cc6f57c91ce3f701f21301141a6122086c65e
571,462
def IsInclude(line): """Returns True if the line is an #include/#import line.""" return line.startswith('#include ') or line.startswith('#import ')
b62b4fa1cd44f923188649cadaaae769ec11ea89
442,580
def get_id_pair_from_nodes(node1, node2): """ This method returns a sorted pair of ids corresponding to two different nodes :param node1: The first Node object :param node2: The second Node object :return: A sorted pair (id1, id2) of the corresponding ids such that id1 < id2 """ id1, id2 = node1.id, node2.id if id1 < id2: return id1, id2 return id2, id1
ee4cba463ec57bbad9c305d7e9c4c569d927abe2
376,160
def build_slice_name( experiment_name, variable_name, time_index, xy_slice_index ): """ Builds a unique name for a slice based on the experiment, variable, and location within the dataset. Takes 4 arguments: experiment_name - String specifying the experiment that generated the slice. variable_name - String specifying the variable associated with the slice. time_index - Non-negative index specifying the time step associated with the slice. xy_slice_index - Non-negative index specifying the XY slice. Returns 1 value: slice_name - String containing the constructed name. """ return "{:s}-{:s}-z={:03d}-Nt={:03d}".format( experiment_name, variable_name, xy_slice_index, time_index )
486d97602081b0aefbb8e14689fbd8f4a942802a
597,368
import getpass def prompt_for_password(prompt_text): """Interactively prompt the operator for a password.""" return getpass.getpass(prompt_text)
663046763b2352c379ec3b66d928cd73c874af98
441,150
import logging def split(pattern, lyrics): """Split Binasphere lines. Args: pattern: List of integers indicating join pattern. lyrics: String to split. >>> split([0, 1, 1], 'a b c d e f') ['a d', 'b c e f'] """ lyrics = lyrics.split() num_lines = max(pattern) + 1 result = [list() for i in range(num_lines)] i = 0 for word in lyrics: val = pattern[i] result[val].append(word) i += 1 i %= len(pattern) if i != 0: logging.warning('Pattern is not fully matched, ended on %d', i) return [' '.join(line) for line in result]
3dc8a9163b49d2f41a2405d253227af036c13048
64,683
import requests import json def GitHub_post(data, url, *, auth, headers): """ POST the data ``data`` to GitHub. Returns the json response from the server, or raises on error status. """ r = requests.post(url, auth=auth, headers=headers, data=json.dumps(data)) r.raise_for_status() return r.json()
5e86aa8c3780e39f894b63c603c75779fcd159c7
54,380
def add_column_values(table, column_title, column_values): """ Adds a column to a specific table Note that you must include a column title and the values of the column """ if len(table) == 0: raise TypeError("Empty table") table[0].append(column_title) for j in range(1, len(table)): table[j].append(column_values[j]) return table
56ea4353053a88ed15973aced9321ede0e9166f2
206,439
def resolution_from_chunk_key(chunk_key): """ breaks out the resolution from the chunk_key. Args: chunk_key (str): volumetric chunk key = hash&num_items&col_id&exp_id&ch_idres&x&y&z" Returns (str): resolution """ parts = chunk_key.split('&') return parts[5]
d9d3dd10b9063e27a185db2e05f3f7503019d466
255,897
def mulND(v1, v2): """Returns product of two nD vectors (same as itemwise multiplication)""" return [vv1 * vv2 for vv1, vv2 in zip(v1, v2)]
5fecb0e5732161b515f5e719448f0dd0e35ee103
325,540
import re def read_query(fname: str) -> str: """Read a query from file. Read query and remove all white space between tags. Args: fname: Filename tor read. Returns: Read query. """ with open(fname, "r") as file: s = file.read() return re.sub(r"\s+(?=<)", "", s)
39083b8e6e3d4772fc170eb50b54715142ae7896
257,282
def io(func): """ @io decorator for blocking io operations. In pycsp.parallel it has no effect, other than compatibility >>> @io ... def sleep(n): ... import time ... time.sleep(n) >>> sleep(0.01) """ return func
8dc21702ac884d953e79df7d951dfef76ef71b93
616,986
import re def remove_observed(exp_name: str | None) -> str | None: """Scrub (Observed) and calendar year from event names. 'Christmas Day (Observed) 2021' becomes 'Christmas Day'.""" if exp_name is None: return None regexp = ( # Captures (Observed), YYYY, and any whitespace before, after, and in between. r"( *\(Observed\) *)|( *\d{4} *)" ) return re.sub(regexp, "", exp_name)
061b77ca413774275b28fc130f5a66d8e3813790
303,865
import torch def _compl_mul_conjugate(a: torch.Tensor, b: torch.Tensor): """ Given a and b two tensors of dimension 4 with the last dimension being the real and imaginary part, returns a multiplied by the conjugate of b, the multiplication being with respect to the second dimension. """ # PyTorch 1.7 supports complex number, but not for all operations. # Once the support is widespread, this can likely go away. op = "bcft,dct->bdft" return torch.stack([ torch.einsum(op, a[..., 0], b[..., 0]) + torch.einsum(op, a[..., 1], b[..., 1]), torch.einsum(op, a[..., 1], b[..., 0]) - torch.einsum(op, a[..., 0], b[..., 1]) ], dim=-1)
3beda88d9c032fa7434bc363ecd3381effaca3ac
584,483
from typing import Dict from typing import Any def suffix_dict_keys(in_dict: Dict[str, Any], suffix: str) -> Dict[str, Any]: """Adds the given suffix to all dictionary keys.""" return {key + suffix: value for key, value in in_dict.items()}
e16ebf829c4f5cf8421014f44a806421a04d5a86
58,205
def modify_intended_for (image_paths, contents, remove=False): """ Modify the given contents dictionary, storing the given image paths under the IntendedFor key. If IntendedFor key already exists, its value is replaced by the given image paths. If remove flag is True, then the value is replaced by an empty list. Returns the sidecar contents dictionary, sorted by keywords. """ contents['IntendedFor'] = [] if remove else image_paths sorted_dict = dict(sorted(contents.items())) return sorted_dict
9f72695ea377989afb507f031f42ca11781c07b7
179,759
def tabindex(field, index): """Set the tab index on the filtered field.""" field.field.widget.attrs["tabindex"] = index return field
c42b64b3f94a2a8a35b8b0fa3f14fe6d44b2f755
818
def get_block(file, S, E): """ Extract from `file` the next block starting with DOUBLE delimiters 'SS' and ending with matching 'EE'. Returns 3 values: - the text found before the block start - the block with its delimiters - a boolean EOF indicator """ ch = file.read(1) sec = 0 pre = '' blk = '' lev = 0 while file and ch: pc = ch ch = file.read(1) if ch == S: if sec: lev += 1 if pc == S: sec += 1 if sec: blk += pc #print("%c%c > lev %i sec %i" %(pc, ch, lev, sec)) else: pre += pc if ch == E: if sec: lev -= 1 if pc == E: # print("%c%c EE lev %i sec %i" %(pc, ch, lev, sec)) if lev == -2: return (pre, blk+ch, False) # reaching end of file: return (pre, blk, True)
5f1cb8d8b60c9d71f2929996a4a23cfffc55101e
357,660
def check_final_winner(result): """ check_final_winner(result) --> string result : ex) ['player', 'player'] 반환값 : 만약 result 안에 'player' 가 두 개 이상이면 : 'player' 'computer' 가 두 개 이상이면 : 'computer' otherwise : none """ print(f"player: {result.count('player')}승, computer: {result.count('computer')}승") if result.count('player') >= 2: return "player" elif result.count('computer') >= 2: return "computer" else: None
5be931344cf36e71783a9c881405b04e6b1cda5e
93,922
def transition(color1, color2, position): """Generates a transitive color between first and second ones, based on the transition argument, where the value 0.0 is equivalent to the first color, and 1.0 is the second color.""" r1, g1, b1 = color1 >> 16, color1 >> 8 & 0xff, color1 & 0xff r2, g2, b2 = color2 >> 16, color2 >> 8 & 0xff, color2 & 0xff r = int(r1 + ((r2 - r1) * position) // 1) << 16 g = int(g1 + ((g2 - g1) * position) // 1) << 8 b = int(b1 + ((b2 - b1) * position) // 1) return r | g | b
86bab892fe39c640214fb172c15c2a87a0679c98
197,503
def get_substance(synset): """ Look up and return the substance meronyms of a given synset. """ substance = synset.substance_meronyms() substance = sorted(lemma.name() for synset in substance for lemma in synset.lemmas()) return substance
59ec5ccc40ad8b33b5dd2f949740794f0d8d1e0e
259,831
def partial_format(part): """ This is just a convenience function so rather than putting schema.thing.format(blah) everywhere, we just schema.thing(blah) """ def form(*args, **kwargs): return part.format(*args, **kwargs) return form
ee7c4b20b1a8e45ec50b89aeba7f2f06366f9dff
256,193
def make_edge(nodes, distance): """ :param nodes: A tuple of address strings :param distance: 'Distance' between edges :return: A mapping object will be used in D3.js """ name = "{}_{}".format(*nodes) return dict(type="edge", distance=distance, id=name, source=nodes[0], target=nodes[1])
e569cb3a3faafb1f234bc230c19aab5a94f9c4f4
540,389
def get_options_config_if_fewer_than_five_hundred(column_values): """ If there are fewer than 500 unique values for a column, return an Options configuration dictionary :param column_values: :return: """ unique_dict = {} for value in column_values: unique_dict[value] = True uniques = list(unique_dict.keys()) if len(unique_dict.values()) < 500: return { 'type': 'options', 'options': uniques }
7aaae7d633d374a941593decc0cc6d5f1e8a7ecb
111,181
def _make_closing(base, **attrs): """ Add support for `with Base(attrs) as fout:` to the base class if it's missing. The base class' `close()` method will be called on context exit, to always close the file properly. This is needed for gzip.GzipFile, bz2.BZ2File etc in older Pythons (<=2.6), which otherwise raise "AttributeError: GzipFile instance has no attribute '__exit__'". """ if not hasattr(base, '__enter__'): attrs['__enter__'] = lambda self: self if not hasattr(base, '__exit__'): attrs['__exit__'] = lambda self, type, value, traceback: self.close() return type('Closing' + base.__name__, (base, object), attrs)
fed163bf5f0352b0eadc44db09dc88d5bea1616d
305,649
import functools import operator def get_in(keys, coll, default=None): """ Reaches into nested associative data structures. Returns the value for path ``keys``. If the path doesn't exist returns ``default``. >>> transaction = {'name': 'Alice', ... 'purchase': {'items': ['Apple', 'Orange'], ... 'costs': [0.50, 1.25]}, ... 'credit card': '5555-1234-1234-1234'} >>> get_in(['purchase', 'items', 0], transaction) 'Apple' >>> get_in(['name'], transaction) 'Alice' >>> get_in(['purchase', 'total'], transaction) >>> get_in(['purchase', 'items', 'apple'], transaction) >>> get_in(['purchase', 'items', 10], transaction) >>> get_in(['purchase', 'total'], transaction, 0) 0 """ try: return functools.reduce(operator.getitem, keys, coll) except (KeyError, IndexError, TypeError): return default
3d82585e1873930b12fa74fecb547e4b7e28ca9b
114,412
def parse_node_coverage(line): # S s34 CGTGACT LN:i:7 SN:Z:1 SO:i:122101 SR:i:0 dc:f:0 # "nodeid","nodelen","chromo","pos","rrank",assemb """ Parse the gaf alignment Input: line from gaf alignment Output: tuple of nodeid, nodelen, start_chromo, start_pos, coverage """ line_comp = line.strip().split() nodeid = line_comp[1] nodelen = len(line_comp[2]) start_chromo = line_comp[4].split(":")[2] start_pos = line_comp[5].split(":")[2] rrank = line_comp[-2].split(":")[2] coverage = line_comp[-1].split(":")[2] return nodeid, nodelen, start_chromo, start_pos, rrank, coverage
b8d2c5eaad33fdee0e9f004982ec9a27f2a40726
685,700
def TransformCollection(r, undefined=''): # pylint: disable=unused-argument """Returns the current resource collection. Args: r: A JSON-serializable object. undefined: This value is returned if r or the collection is empty. Returns: The current resource collection, undefined if unknown. """ # This method will most likely be overridden by a resource printer. return undefined
b303164bf633530c8843d8ffb87f60085bc64401
486,581
def is_user(request): """Check if the incoming request is from the appropriate_user.""" return request.authenticated_userid == request.matchdict['username']
2ed218c70d712d6b03d470e7ebe228e872d20a0b
612,195
def factorial(number, show=False): """ Calcula o fatorial de um núumero :param number: o número a ser calculado o fatorial :param show: mostrar o cálculo :return: fatorial """ fact = 1 for count in range(number, 0, -1): fact *= count if show: print(count, end='') if count == 1: print(' = ', end='') else: print(' x ', end='') return fact
a55a17cb084e6055f630e5df5f876abc7b2adebf
347,619
def ask_for_continuation(iteration: int) -> bool: """ Ask the user if we can proceed to execute the sandbox. :param iteration: the iteration number. :return: True if the user decided to continue the execution, False otherwise. """ try: answer = input( "Would you like to proceed with iteration {}? [y/N]".format(iteration) ) if answer != "y": return False else: return True except EOFError: return False
93f007c7ac40bf618eee04dea01e25c2a85cc005
647,540
def custom_path_handler(instance, filename: str) -> str: """ Handle path and name to save file in storage """ dir_ = instance.hash[:2] name = instance.hash if '.' in filename: file_extension = f'.{filename.split(".")[-1]}' return f'{dir_}/{name}{file_extension}' else: return f'{dir_}/{name}'
2aa6626f7fb439e516901fde4edff24328abd6d9
485,418
def _normalize_whitespace(s): """Replaces consecutive whitespace characters with a single space. Args: s: The string to normalize, or None to return an empty string. Returns: A normalized version of the given string. """ return ' '.join((s or '').split())
cad713d5956b76c410bbfc538ffaeecbdd1f7f0f
182,376
from typing import Optional def is_world_language(lang_code: Optional[str] = None) -> bool: """ Determines if code is a world language code """ if lang_code in ("eng", "und", "zxx", None): return False else: return True
116314970d485d40bb30b94b2a98cc9b60262a91
412,112
def get_dict_path(base, path): """ Get the value at the dict path ``path`` on the dict ``base``. A dict path is a way to represent an item deep inside a dict structure. For example, the dict path ``["a", "b"]`` represents the number 42 in the dict ``{"a": {"b": 42}}`` """ path = list(path) level = path.pop(0) if path: return get_dict_path(base[level], path) return base[level]
2aa4930077258a6bac45717b2e2138ae8897a9a6
667,216
def pres_units(units): """ Return a standardized name (hPa or Pa) for the input pressure units. """ hpa = ['mb', 'millibar', 'millibars', 'hpa', 'hectopascal', 'hectopascals'] pa = ['pascal', 'pascals', 'pa'] if units.lower() in hpa: return 'hPa' elif units.lower() in pa: return 'Pa' else: raise ValueError('Unknown units ' + units)
4e0f8b14b6744adaadea8c294b437a4722476638
372,563
import math import struct def OSCString(next): """Convert a string into a zero-padded OSC String. The length of the resulting string is always a multiple of 4 bytes. The string ends with 1 to 4 zero-bytes ('\x00') """ OSCstringLength = math.ceil((len(next)+1) / 4.0) * 4 return struct.pack(">%ds" % (OSCstringLength), str(next).encode('latin1'))
8b8dceffd11059bbe54b28701f82e07917939326
510,855
from typing import List def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
f0ad8cb6208616d274ee8749fb5b4a51391b0c8d
648,504
def parse_header_entry(entry: str) -> dict: """Parses a header entry Args: entry (str): The header entry Returns: dict: The parsed entry (dict with keys: module, value, dimension, unit) """ assert isinstance(entry, str), "entry must be a string" _categories = ["module", "value", "dimension", "unit"] _split_by_colon = entry.split(":") assert len(_split_by_colon) == 4, f"expected 4 colon-separated elements in entry" _dict = dict(zip(_categories, _split_by_colon)) _dict["quantity"] = _dict["module"].split("_")[0] if "_" in _dict["module"] else "" _dict["method"] = _dict["module"].split("_")[1] if "_" in _dict["module"] else "" return _dict
8c675ba46c5863720e7f0083304925811611bc0b
494,016
import time def wait_for_all_nodes_state(batch_client, pool, node_state): """Waits for all nodes in pool to reach any specified state in set :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient` :param pool: The pool containing the node. :type pool: `batchserviceclient.models.CloudPool` :param set node_state: node states to wait for :rtype: list :return: list of `batchserviceclient.models.ComputeNode` """ print('waiting for all nodes in pool {} to reach one of: {!r}'.format( pool.id, node_state)) i = 0 while True: # refresh pool to ensure that there is no resize error pool = batch_client.pool.get(pool.id) if pool.resize_errors is not None: resize_errors = "\n".join([repr(e) for e in pool.resize_errors]) raise RuntimeError( 'resize error encountered for pool {}:\n{}'.format( pool.id, resize_errors)) nodes = list(batch_client.compute_node.list(pool.id)) if (len(nodes) >= pool.target_dedicated_nodes and all(node.state in node_state for node in nodes)): return nodes i += 1 if i % 3 == 0: print('waiting for {} nodes to reach desired state...'.format( pool.target_dedicated_nodes)) time.sleep(10)
caaf59d191179bea60d6a62b0f22f42b19683bc6
97,046
def decode_database_key(s): """Extract Guage_id, Reading_type, Datestr form provided keystring. """ lst = s.split("-") gid = lst[0] rdng = lst[1] dstr = lst[2] return (gid, rdng, dstr)
365b829b86f31507314d6aa3eb1b72eee6ce3d75
524,016
import pathlib def create_missing_dir(path): """Creates specified directory if one doesn't exist :param path: Directory path :type path: str :return: Path to directory :rtype: str """ path = pathlib.Path(path) if not path.is_dir(): path.mkdir() return path
ff4df4ca4e5ddc6d03e0d2007eb3a8404044f900
111,013
def _center_strip_right(text: str, width: int) -> str: """Returns a string with sufficient leading whitespace such that `text` would be centered within the specified `width` plus a trailing newline.""" space = (width - len(text)) // 2 return space * " " + text + "\n"
ee858fc5fa1d9c37d263f6cc5ca6b5b2981164ea
618,622
def get_repository_version(pear_output): """Take pear remote-info output and get the latest version""" lines = pear_output.split('\n') for line in lines: if 'Latest ' in line: return line.rsplit(None, 1)[-1].strip() return None
d5351a604ec97d460b1938896e3243c102e1387b
358,640
from math import sqrt def heron(a, b, c): """Obliczanie pola powierzchni trojkata za pomoca wzoru Herona. Dlugosci bokow trojkata wynosza a, b, c.""" if a + b > c and \ a + c > b and \ b + c > a and \ a > 0 and b > 0 and c > 0: p = (a + b + c) / 2.0 area = sqrt(p * (p - a) * (p - b) * (p - c)) return area else: raise ValueError("I can't calculate area of this triangle")
e2004b72f1332cafae494f3d6ebec5da30e95c7f
78,581
import random def sample_filter(val, count=None): """Return a random sample from a list""" if count is None: # Return a single value try: return random.sample(list(val), 1)[0] except ValueError: return None else: # Return a list try: return random.sample(list(val), count) except ValueError: return []
985f82ab613f0d66601d380c42bf672f788b805c
292,691
def slurp(filename): """ Given a `filename` string, slurp the whole file into a string """ with open(filename, "r") as source: return source.read()
ebef1ed47975ac441dc42c570ca81e623e9ca9a3
371,378
from typing import Callable import logging def test_combination_wrapper( test_combination: Callable[..., bool]) -> Callable[..., int]: """Wraps a test function with post processing functionality. In particular, the wrapper invokes test_combination, logs the test and its status, and returns a boolean to indicate the status of passing (True) or failing (False). Args: test_combination: A Callable object for invoking the test with one combination of the test parameters, and returns a boolean to indicate the status of passing (True) or failing (False). Returns: A wrapper of the given test_combination function. """ def wrapper(*args) -> int: passed = test_combination(*args) status_str = "passed" if passed else "failed" test_name = "_".join([str(i) for i in args]) logging.info(f"test_{test_name} {status_str}.") return passed return wrapper
831250a9dcfe6b43fd18ddace45450ddaafaae89
386,824
def section(name, underline_char='='): """ Generate reST section directive with the given underline. :Examples: >>> section('My section') ''' My section ========== <BLANKLINE> ''' >>> section('Subsection', '~') ''' Subsection ~~~~~~~~~~ <BLANKLINE> ''' """ name_len = len(name) return '\n'.join(( '', name, underline_char * name_len, '', ))
8bfa1a9e7fbe893d1808ed8dd0e70aa8cf412f1a
560,076
from typing import List import math def rotate_point(x: float, y: float, cx: float, cy: float, angle: float) -> List[float]: """ Rotate a point around a center. :param x: x value of the point you want to rotate :param y: y value of the point you want to rotate :param cx: x value of the center point you want to rotate around :param cy: y value of the center point you want to rotate around :param angle: Angle, in degrees, to rotate :return: Return rotated (x, y) pair :rtype: (float, float) """ temp_x = x - cx temp_y = y - cy # now apply rotation angle = math.radians(angle) cos_angle = math.cos(angle) sin_angle = math.sin(angle) rotated_x = temp_x * cos_angle - temp_y * sin_angle rotated_y = temp_x * sin_angle + temp_y * cos_angle # translate back rounding_precision = 2 x = round(rotated_x + cx, rounding_precision) y = round(rotated_y + cy, rounding_precision) return [x, y]
5996429c4cdfc56793c1726fcf1be8e19f3e09a8
422,173
def class_filter(dataset, classes, is_superclass=False, proportion=1.0): """ Handles filtering of (super)classes for use with tf.Dataset. Arguments: dataset: An instance of the Dataset class. classes: A list of classes (or superclasses). is_superclass: A flag indicate whether or not the "classes" param consists of superclasses. proportion: A float indicating the proportion of classes to retrieve. """ output_classes = [] try: if classes and is_superclass: output_classes = dataset.get_classes_by_superclass(classes, proportion) elif classes and not is_superclass: output_classes = [int(x) for x in classes] except: raise ValueError('Failed to filter classes.') return output_classes
6aee69302c6f53f574fece881e6e254bae77bcde
81,455
def calc_duration_time(num_groups, num_integrations, num_reset_frames, frame_time, frames_per_group=1): """Calculates duration time (or exposure duration as told by APT) Parameters ---------- num_groups : int Groups per integration num_integrations : int Integrations per exposure num_reset_frames : int Reset frames per integration frame_time : float Frame time (in seconds) frames_per_group : int, optional Frames per group -- always one except brown dwarves Returns ------- duration_time : float Duration time (in seconds). """ duration_time = frame_time * (num_groups * frames_per_group + num_reset_frames) * num_integrations return duration_time
c5a1581fd815f95409810cfe051c255dfcb0933b
553,420
def format_out(string_name, forecast_hour, value): """ formats polygon output :param string_name: name of output field :param forecast_hour: forecast hour of output :param value: value of output :returns: dict forecast hour, field name, and value """ return [{ 'Forecast Hour': forecast_hour, string_name: value }]
2a14c950c6290564491164385094c2aae8a418d7
391,706
def loadheader(filename): """ Load NAME file and parse header lines into dict. filename -- input NAME file """ header = {} with open(filename, 'r') as f: for line in range(1, 19): h = f.readline() if ":" in h: (key, val) = h.split(":", 1) key = key.strip() val = val.strip() header[key] = val return header
cc505761e9896bfb84692ca21311fb123c8f34e0
602,417
def calculate_stretch_factor(array_length_samples, overlap_ms, sr): """Determine stretch factor to add `overlap_ms` to length of signal.""" length_ms = array_length_samples / sr * 1000 return (length_ms + overlap_ms) / length_ms
66c3b5fadf7998b6ecbd58761242ec4c253fd2f5
675,982
def state_reward(state, action): """State transitions on action :param state: previous state :type state: tuple :param action: action :type action: tuple :return: new state and reward :rtype: tuple """ x, y = state dx, dy = action # A -> A' if (x, y) == (0, 1): return (4, 1), 10 # B -> B' if (x, y) == (0, 3): return (2, 3), 5 # new state x1, y1 = x + dx, y + dy # out of bounds if x1 in (-1, 5) or y1 in (-1, 5): return (x, y), -1 # normal case: inside grid, not A or B state else: return (x1, y1), 0
2bec9f0fcf0c40c435bc7585ac7de3d99243d878
216,895
def inherit_function_doc(parent): """Inherit a parent instance function's documentation. Parameters ---------- parent : callable The parent class from which to inherit the documentation. If the parent class does not have the function name in its MRO, this will fail. Examples -------- >>> class A(object): ... def do_something(self): ... '''Does something''' >>> >>> class B(A): ... @inherit_function_doc(A) ... def do_something(self): ... pass >>> >>> print(B().do_something.__doc__) Does something """ def doc_wrapper(method): func_name = method.__name__ assert (func_name in dir( parent)), '%s.%s is not a method! Cannot inherit documentation' % ( parent.__name__, func_name) # Set the documentation. This only ever happens at the time of class # definition, and not every time the method is called. method.__doc__ = getattr(parent, func_name).__doc__ # We don't need another wrapper, we can just return the method as its # own method return method return doc_wrapper
0d22610e66118363fdeda6139eab0a8065e6c354
21,481
def get_version_tuple(version): """ Return a tuple of version numbers (e.g. (1, 2, 3)) from the version string (e.g. '1.2.3'). """ if version[0] == "v": version = version[1:] parts = version.split(".") return tuple(int(p) for p in parts)
f7357b367aef64655a47e0701400517effd6da33
459,375
import csv def read_vote_data(filename): """ Reads a CSV file of data on the votes that were taken. """ f = open(filename, encoding='utf-8') csv_reader = csv.reader(f) votes = [] for row in csv_reader: vote = {} vote['date'] = row[0] vote['number'] = row[3] vote['motion'] = row[4] vote['name'] = row[6] vote['result'] = row[5] votes.append(vote) f.close() return votes
28c4e3d771298c45b169a9436205da69d62cb827
126,515
def check_card_played_active(laid_card): """ Function used to check if card is a special kind of card with additional rules. :param laid_card: tuple with last played card :return: bool value, True if card is special, False otherwise """ if laid_card in [('hearts', 'K'), ('pikes', 'K')]: return True value = laid_card[1] if value in '2 3 4 J A'.split(): return True return False
ebdbb24aee1663711de5392c4759a3f7ffd9598e
221,083
def _Spaced(lines): """Adds a line of space between the passed in lines.""" spaced_lines = [] for line in lines: if spaced_lines: spaced_lines.append(' ') spaced_lines.append(line) return spaced_lines
750929d11f7c106075dbe93695c7beecb94b1ba7
426,367
import functools from warnings import warn def deprecated(version, replacement): """Decorator to deprecate functions and methods Also handles docstring of the deprecated function. Parameters ---------- version : str Version in which the feature will be removed. replacement : callable | str Either a verbal description, or a pointer to the direct replacement function which takes the same arguments. In the latter case, the replacement is automatically called and the deprecated function is not used anymore. """ def dec(func): msg = f"{func.__name__} is deprecated and will be removed in version {version}" if isinstance(replacement, str): msg += '; ' + replacement call_func = func elif replacement is not None: msg += f"; use {replacement.__name__} instead" call_func = replacement else: raise TypeError(f"replacement={replacement!r}") func.__doc__ = msg @functools.wraps(func) def new(*args, **kwargs): warn(msg, DeprecationWarning) return call_func(*args, **kwargs) return new return dec
a8438989e906fe7ca3b3c0f6cf471c6e8bf79736
248,482
def getter_accessor(row, field): """Accessor for iterables whose items have implemented __getitem__, like Pandas/Spark dataframes. Returns ``row[field]``.""" return row[field]
de84b52266c5dba8fcfe21165998d33ec542d413
240,756
def median(iterable, sort=True): """ Returns the value that separates the lower half from the higher half of values in the list. """ s = sorted(iterable) if sort is True else list(iterable) n = len(s) if n == 0: raise ValueError("median() arg is an empty sequence") if n % 2 == 0: return float(s[(n // 2) - 1] + s[n // 2]) / 2 return s[n // 2]
cd69048720098864acf0d84e7cd1ac45023afaff
619,462
def read_data(filename): """ Reads raw space image format data file into a string """ data = '' f = open(filename, 'r') for line in f: data += line.strip('\n') f.close() return data
a705a62c3ef92ca1189e065018a2b6ee47a3fad6
680,681
def A_int(freqs, delt): """Calculates the Intermediate Amplitude Parameters ---------- freqs: array The frequencies in Natural units (``Mf``, G=c=1) of the waveform delt: array Coefficient solutions to match the inspiral to the merger-ringdown portion of the waveform """ return ( delt[0] + delt[1] * freqs + delt[2] * freqs ** 2 + delt[3] * freqs ** 3 + delt[4] * freqs ** 4 )
7faf0fbfc67825dc43a9bd221dde397fc8e3f75f
255,213
from typing import Callable def _scroll_screen(direction: int) -> Callable: """ Scroll to the next/prev group of the subset allocated to a specific screen. This will rotate between e.g. 1->2->3->1 when the first screen is focussed. """ def _inner(qtile): if len(qtile.screens) == 1: current = qtile.groups.index(qtile.current_group) destination = (current + direction) % 6 qtile.groups[destination].cmd_toscreen() return current = qtile.groups.index(qtile.current_group) if current < 3: destination = (current + direction) % 3 else: destination = ((current - 3 + direction) % 3) + 3 qtile.groups[destination].cmd_toscreen() return _inner
e778b6ef8a07fe8609a5f3332fa7c44d1b34c17a
6,280
def submit_gcp_connector_sync_action(api, configuration, api_version, api_exception, gcp_connector_id): """ Submits a synchronize action of a GCP connector. :param api The Deep Security API exports. :param configuration The configuration object to pass to the API client. :param api_version The API version to use. :param api_exception The Deep Security API exception module. :param gcp_connector_id The GCP connector ID of the target GCP connector. :return The created Action object which contains the ID and status of the action. """ # Create the GCPConnectorActionsApi instance and an Action object to synchronize the GCP connector api_instance = api.GCPConnectorActionsApi(api.ApiClient(configuration)) gcp_connector_action = api.Action() gcp_connector_action.type = "synchronize" try: # Call the create_gcp_connector_action API to create a synchronize action for the target GCP connector api_response = api_instance.create_gcp_connector_action(gcp_connector_id, gcp_connector_action, api_version) return api_response except api_exception as e: print("An exception occurred when calling GCPConnectorActionsApi.create_google_connector_action: %s\n" % e)
ac69abf5e01c889e1a8e233a5a3be396ce7c8776
101,468
from typing import OrderedDict def get_star_ids_from_upload_file(fullpath): """ Get and return all star ids from a given WebObs upload text file. :param fullpath: upload text file name [string]. :return: list of all star IDs, no duplicates, preserving order found in file [list of strings]. """ try: with open(fullpath) as f: lines = f.readlines() except FileNotFoundError: return list() # Ensure file declares itself to be either Extended or Visual format: type_line_found = False for line in lines: if line.upper().startswith('#TYPE='): type_line_found = True type_string = line.split('=')[1].strip() if type_string.upper() not in ['EXTENDED', 'VISUAL']: return list() if not type_line_found: return list() # Get delimiter, comma as default: delimiter = ',' # default if #DELIM line not found. for line in lines: if line.upper().startswith('#DELIM='): delimiter = line.split('=')[1].strip() if delimiter.lower() == 'comma': delimiter = ',' break # Extract and return star_ids: lines = [line for line in lines if not line.startswith('#')] # keep only observation text lines. star_ids_as_found = [line.split(delimiter)[0].strip() for line in lines] # may contain duplicates. star_ids = list(OrderedDict.fromkeys(star_ids_as_found)) # no duplicates, order preserved. return star_ids
82f172a1455e02b728d7337894805e68798abf04
52,334