content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def get_orgname(recIDstr: str) -> str: """ Splits a faster header by \s and '_' to return orgname """ orgname = recIDstr.split()[0].split('_')[1] return(orgname)
248e1318dbba50b62455098043fe6ec8e5db942c
88,750
import math def nCr(n: int, r: int) -> float: """Computes nCr Args: n: Total number r: Number to sample Returns: nCr """ if r > n or n < 0 or r < 0: return 0 f = math.factorial return f(n) // f(r) // f(n - r)
fcdaa2db1a71644faa881e18c080e655ecbfd5c2
63,357
def splitStringIntoChunks( string, length=25 ): """ Split string into chunks of defined size """ if len(string) <= length: return [ string ] else: return [ string[ 0+i : length+i ] \ for i in range( 0, len( string ), length ) ]
ff91557d06927727868fd8b157272286b72f1d5f
667,615
def is_at_del(row): """Encodes if the indel is an deletion with 'A' or 'T' Args: row (pandas.Series): a Series with 'is_ins'(bool) and 'indel_seq'(str) indexes Returns: is_at_del (bool): 1 for 'A' or 'T' deletion 0 otherwise """ if row["is_ins"] == 0 and row["indel_seq"] == "A": is_at_del = 1 elif row["is_ins"] == 0 and row["indel_seq"] == "T": is_at_del = 1 else: is_at_del = 0 return is_at_del
f0d8ce798cc2c403a97494133399d5fdd3aa91f6
455,204
def row_decomposition(in_array, num_chunks, ghost_zone_size): """ Parameters: ----------- in_array: np.ndarray the input array. should have shape (bands, rows, columns) num_chunks: int the number of chunks to split the data into. ghost_zone_size: int in the case of focal map algebra computations, the ghost_zone_size indicates the number of additional rows to append to each chunk to ensure the focal operations are computed accurately (i.e. so that each computation receives it's neighbors for accurate and complete calculations). This should be in number of pixels. NOTE: there is the potential of copying a large amount of redundant data between data chunks if the num_chunks is not chosen carefully. It should be chosen with the size of the input array in mind. Returns: --------- chunks: nested list holds information about the bounds of the data chunks that will be processed start_row_idx and end_row_idx are indices that indicate the topmost and bottommost rows for processing features. These indices also take into account the buffer needed for computing multiscale features [[dataid, start_row_idx, end_row_idx], [dataid, start_row_idx, end_row_idx]] """ # 1. first get the number of rows in the interior (total rows - buffer pixels for multiscale computations) # 2. ensure that the number of interior rows is divisible by the block size # 3. if not # tot_rows = in_array.shape[1] tot_cols = in_array.shape[2] rows_in_interior = tot_rows - ghost_zone_size*2 chunk_size = rows_in_interior // num_chunks remaining = rows_in_interior % num_chunks start_idx = 0 end_idx = 0 chunk_id = 0 chunks = [] while end_idx < tot_rows: end_idx = start_idx+chunk_size+(ghost_zone_size*2) if remaining > 0: end_idx += 1 remaining -= 1 #chunks.append([chunk_id,in_array[:,start_idx:end_idx,:]]) chunks.append([chunk_id, start_idx, end_idx]) # don't actually need the data, just the location for slices chunk_id+=1 start_idx = (end_idx)-(ghost_zone_size*2) return chunks
ada1d5db08b03172ac7429417d905f640572e678
230,979
def readByte (file): """ Read a byte from file. """ return ord (file.read (1))
4e82d1b688d7742fd1dd1025cd7ac1ccb13bbca0
709,655
def find_parens(s): """Get indices of matching parantheses in a string.""" # Source: https://stackoverflow.com/questions/29991917/indices-of-matching-parentheses-in-python toret = {} pstack = [] for i, c in enumerate(s): if c == '(': pstack.append(i) elif c == ')': if len(pstack) == 0: raise IndexError("No matching closing parens ')' at: " + str(i) + s) toret[pstack.pop()] = i if len(pstack) > 0: raise IndexError("No matching opening parens '(' at: " + str(pstack.pop())+s) return toret
d1634f72cad52da84e14acba057dd570e1917aee
375,951
def square_right(x: int) -> int: """Square x, correctly.""" return x**2
744633f64546e336bd21673c4a4dd9b15c94b029
366,492
def is_rule(line: str, starting_chr: str = '*', omit: str = 'NOTE') -> bool: """If the first character of the line is the selected character and the line doesn't contain the omitted text (case-sensitive).""" return True if line.startswith(starting_chr) and line.find(omit) == -1 else False
7d3d1bffbfad1f103a7c130b65c18fd6a7a9d9b4
129,092
def clean_ingredients(dish_name, dish_ingredients): """ :param dish_name: str :param dish_ingredients: list :return: tuple of (dish_name, ingredient set) This function should return a `tuple` with the name of the dish as the first item, followed by the de-duped `set` of ingredients as the second item. """ ingredients = set(dish_ingredients) return (dish_name, ingredients)
69e5872a1736575bbd7255af5d0901bd4f5bb8c2
466,311
def integerlog(n, b): """computes largest integer k>=0 such that b^k <= n""" kmin, kmax = 0, 1 while b**kmax <= n: kmax *= 2 while True: kmid = (kmax + kmin) // 2 if b**kmid > n: kmax = kmid else: kmin = kmid if kmax - kmin <= 1: break return kmin
54359f2ca333c5d2736a065fc9ce36a7f005367a
414,325
import requests import json def get_jsonparsed_data(url): """ Receive the content of `url`, parse it as JSON and return the object. Parameters ---------- url : str given by API-syntax Returns ------- dict or list of dicts """ r = requests.get(url) if r.ok: data = json.loads(r.text, encoding='utf-8') return data else: print('Connection Failed')
115419086ed32d559457aef86aa0c62f32d74d62
603,744
def typematch(ty, impl): """ See whether type instance `ty` is a type for value instances of `impl`. >>> @jit('Foo[a, b]') ... class Foo(object): ... pass ... >>> typematch(Foo[int32, 2], Foo) True """ return isinstance(ty, type(impl.type))
80f2db0d0fe214ef5949b725f481bf615061ed75
406,335
def validate_on_batch( network, loss_fn, X, y_target ): """Perform a forward pass on a batch of samples and compute the loss and the metrics. """ # Do the forward pass to predict the primitive_parameters y_hat = network(X) loss = loss_fn(y_hat, y_target) return ( loss.item(), [x.data if hasattr(x, "data") else x for x in y_hat], )
9502bd0f04bc4c8504442e6952f514dbe3044e1d
656,199
from typing import Dict from typing import Any def make_keydict(key_to_type: Dict[str, Any]) -> str: """ Returns the python code for declaring a dictionary that changes the returned strings to their correct types Parameters ---------- key_to_type: dict keys are the field names in the returned structure, values are the functions to call to cast to correct type Returns ------- keydict_declare: str String to paste into stub function to create the desired dictionary """ accum = "{" for key, val in key_to_type.items(): # no need to cast str to str if val != "str": accum += f"'{key}':{val},\n" accum += "}" return f"keydict : Dict[str,Any] = {accum}"
51f8f022f5208e88e884e2c0b7fbed9ccf436453
106,016
from typing import Any def value_or_default(dictionary: dict, key: str, default: Any): """ Either returns the item of the "dictionary" corresponding to the given "key" or the given default value, if no such key exists within the dict. CHANGELOG Added 14.07.2019 :param dictionary: :param key: :param default: :return: """ if key in dictionary.keys(): return dictionary[key] else: return default
f3672b82587fbb571438809a1704efa2c991d9da
450,763
import math def totalTreeStepsFinder(nt, sl): """totalTreeStepsFinder() takes a newickTree and a stepLength and finds the total number of steps in the entire tree. """ numSteps = 0 if nt is None: return int(numSteps) numSteps = math.ceil(nt.distance / sl) return int(numSteps + totalTreeStepsFinder(nt.right, sl) + totalTreeStepsFinder(nt.left, sl))
4e533bd1b260e0d90d6d0bf3b07404924e59620a
612,688
import requests def offline_token_using_password(token_endpoint, client_id, username, password): """Get offine token using password.""" response = requests.post( token_endpoint, data={ 'grant_type': 'password', 'scope': ['offline_access', 'openid'], 'client_id': client_id, 'username': username, 'password': password, }) return response.json()
db802596940a9d020bb13e93b0546ce9a48aea40
605,290
def trim_stopwords(words, stop_words_set): """ 去除切词文本中的停用词 :param words: :param stop_words_set: :return: """ new_words = [] for w in words: if w in stop_words_set: continue new_words.append(w) return new_words
0625edaf014fe8105bad54ae040049ebe07ab8e5
272,139
def to_dict(response): """ Converts elasticsearch responses to dicts for serialization """ r = response.to_dict() r['meta'] = response.meta.to_dict() return r
2fc7561bfc78ac9e88310afe728678e1ef2fc1d8
433,541
import re def is_switch_statement(line: str) -> bool: """Checks if the line is switch statement""" pattern = r'\s*(switch)\s*(\S*):' return True if re.fullmatch(pattern, line) else False
e3905b95aecc638f782d71f903d4fdb8c0a0812a
227,515
def is_blank(line): """ Returns true iff the line contains only whitespace. """ return line.strip() == ""
c67d51289d9e41fdcea75e78af80004902eeb245
56,905
def _get_headings(soup): """Get the href/id of all of the headings in the given html.""" headings = list() headings.extend([link['href'] for link in soup.findAll('a', {'class': 'headerlink'})]) return headings
67187cb6ef4ad6e500b36d49ade0d41451ed1051
355,652
def tabulate_summary(certificates, kubeconfigs, etcd_certs, router_certs, registry_certs): """Calculate the summary text for when the module finishes running. This includes counts of each classification and what have you. Params: - `certificates` (list of dicts) - Processed `expire_check_result` dicts with filled in `health` keys for system certificates. - `kubeconfigs` - as above for kubeconfigs - `etcd_certs` - as above for etcd certs Return: - `summary_results` (dict) - Counts of each cert type classification and total items examined. """ items = certificates + kubeconfigs + etcd_certs + router_certs + registry_certs summary_results = { 'system_certificates': len(certificates), 'kubeconfig_certificates': len(kubeconfigs), 'etcd_certificates': len(etcd_certs), 'router_certs': len(router_certs), 'registry_certs': len(registry_certs), 'total': len(items), 'ok': 0, 'warning': 0, 'expired': 0 } summary_results['expired'] = len([c for c in items if c['health'] == 'expired']) summary_results['warning'] = len([c for c in items if c['health'] == 'warning']) summary_results['ok'] = len([c for c in items if c['health'] == 'ok']) return summary_results
02e9311911e2b243e2a28cde1a42985368c4c79b
543,502
def _GetAliasForIdentifier(identifier, alias_map): """Returns the aliased_symbol name for an identifier. Example usage: >>> alias_map = {'MyClass': 'goog.foo.MyClass'} >>> _GetAliasForIdentifier('MyClass.prototype.action', alias_map) 'goog.foo.MyClass.prototype.action' >>> _GetAliasForIdentifier('MyClass.prototype.action', {}) None Args: identifier: The identifier. alias_map: A dictionary mapping a symbol to an alias. Returns: The aliased symbol name or None if not found. """ ns = identifier.split('.', 1)[0] aliased_symbol = alias_map.get(ns) if aliased_symbol: return aliased_symbol + identifier[len(ns):]
1685f422c3271037d4bd6d8e24ba64d5ec5510ac
157,555
import math def euclidean_dist_2_pts(p1, p2): """ Return euclidean distance between 2 points :param p1: tuple(X,Y) of the first point's coordinates :param p2: tuple(X,Y) of the second point's coordinates :return: distance in the same metrics as the points """ x1, y1 = p1 x2, y2 = p2 return math.sqrt((float(x1) - float(x2)) ** 2 + (float(y1) - float(y2)) ** 2)
d90e4d4cf672539ae7d614c5b32e26774060ed40
602,184
def identity(arg): """ This function simply returns its argument. It serves as a replacement for ConfigParser.optionxform, which by default changes arguments to lower case. The identity function is a better choice than str() or unicode(), because it is encoding-agnostic. """ return arg
a5a5adfbc87ec25619eb4540dda995e49a03ba7a
23,314
def from_url_to_filename(url): """convert web url to a filename Args: url (str): string representing the url Returns: str: filename parsed from url """ return url.split("://")[1].replace("/", "_").replace(".", "_")
ead403138fbef4b0ba4d2f4adb770e22dada9868
277,213
import random def parallel_shuffle(mylists): """ Shuffles parallel lists together Args: mylists (list of list of obj): The list of parallel lists to shuffle. Note that the format is [l1, l2, ..., ln] Returns: list of list of obj: The list of shuffled parallel lists. Notes: Random should be seeded beforehand. """ num = len(mylists) length = len(mylists[0]) length_array = list(range(length)) random.shuffle(length_array) shuffled_lists = [] for i in range(num): shuffled_lists.append([]) for order in length_array: for i in range(num): shuffled_lists[i].append(mylists[i][order]) return shuffled_lists
926e023f40e7dad59dc321524a03d0ce387e7e39
413,973
def ZwiftCatEmoji(zcat=None): """ Return str to emoji for backpedal server :param zcat: str A+ A B C D E :return: str zcat emoji for backpedal server """ if zcat == None: return None if zcat == 'A+': return ':zcataplus:' if zcat in ['A','B','C','D','E']: return ':zcat' + zcat.lower() + ':'
bb50577e9f0d2f1a30c81e4ac6f980b865921749
412,417
from typing import List def convert_records_to_dict(records: List[tuple]) -> dict: """Converts pyscopg2 records list to a dict.""" dict = {} for record in records: # Add record tuple data to dict. dict[record[0]] = record[1] return dict
523efb6c040779c3b885acdbf304177556e04c67
664,427
def num_digits(number): """ Returns number of digits in an integer. :param number: Integer :return: Number of digits """ return len(str(number))
c026468131e019f731012216e73b9c17f4d3bafd
69,469
import math import colorsys def step(r: int, g: int, b: int, repetitions=1) -> tuple: """ Helper function to generate step sorted color diagram. Credits go to: https://www.alanzucconi.com/2015/09/30/colour-sorting/ """ lum = math.sqrt( .241 * r + .691 * g + .068 * b ) # weighting by luminosity h, s, v = colorsys.rgb_to_hsv(r,g,b) h2 = int(h * repetitions) v2 = int(v * repetitions) if h2 % 2 == 1: v2 = repetitions - v2 lum = repetitions - lum return (h2, lum, v2)
5779be8f78918db042558de79ded89b9df4c70c3
433,326
import gzip import io def get_gzip_uncompressed_size(filepath): """Get uncompressed size of a .gz file Parameters ---------- filepath: string Path to input file Returns ------- filesize: int Uncompressed file size """ with gzip.open(filepath, "rb") as file_obj: return file_obj.seek(0, io.SEEK_END)
328846ef296ce72a353c24b241028bd80ad121d9
460,060
def calculate_accuracy(combined_decisions, Y_test_1): """calculates percentage accuracy of a combined decisions array Args: combined_decisions: predicted values for combined model Y_test_1: True values Returns: percentage accuracy of predictions """ total_decisions = len(combined_decisions) correct_decisions = 0 for index, decision in combined_decisions: if decision == Y_test_1[index]: correct_decisions +=1 return correct_decisions / total_decisions * 100
7494ef3bc017e628f9621f803c27bd2c77ccff2b
38,312
def schema_input_type(schema): """Input type from schema :param schema: :return: simple/list """ if isinstance(schema, list): return 'list' return 'simple'
cdcc9b724005083995f26a767d9b2ab95645ad79
14,602
import hashlib def get_file_hash(file_path): """ Get the file hash (SHA-1) """ chunk_size = 65536 hasher = hashlib.sha1() with open(file_path, 'rb') as f: buff = f.read(chunk_size) while len(buff) > 0: hasher.update(buff) buff = f.read(chunk_size) file_hash = hasher.hexdigest() return file_hash
0bbed2a559108b457d280cc988a4975d06a5fd40
284,682
def lookup_dict_path(d, path, extra=list()): """Lookup value in dictionary based on path + extra. For instance, [a,b,c] -> d[a][b][c] """ element = None for component in path + extra: d = d[component] element = d return element
84380773c9c4a446d22587d41113136588458160
76,579
import re def separa_sentencas(texto: str) -> list: """ The function receives a text and returns a list of sentences within the text. """ sentencas = re.split(r"[.!?]+", texto) if sentencas[-1] == "": del sentencas[-1] return sentencas
555d4a986a654f3c9915fde05d70018ab692cefc
197,506
def track_processed(args): """ Track processed if there might be a delete timeout or interval specified :param args: :return: """ return args.delete or (args.interval and args.interval > 0)
9542f227316e96b22d9cb236ebb6196bd059618d
586,756
import re def get_platform(source = '<PLT_1>'): """A function to extract the platform from a source string. Args: source (str, optional): source string that is usually contains the platform that is used to post the tweet. Defaults to '<PLT_1>'. Returns: str: the platform if found, otherwise the stamp PLT_1. This stamp is used for any further updates. """ platform = 'PLT_1' try: platform = re.sub('[<>]', '\t', source).split('\t')[2] platform = platform.replace('Twitter for','').replace('Twitter','') except: platform = 'PLT_1' return platform.strip()
c12c7fd02b53b24a70a6f5343f9bc031c5d0f513
43,510
def dot_product(a,b): """calculate dot product from two lists""" # optimized for PyPy (much faster than enumerate/map) s = 0 i = 0 for x in a: s += x * b[i] i += 1 return s
077a7e1fc97a344d68fd5509191c989e23f626b2
610,009
from typing import Iterable from typing import Any def list2str(the_list: Iterable[Any], sep: str = ',') -> str: """ Convert an iterable, such as a list, to a comma separated string. :param the_list: The iterable to convert to a string. :param sep: Separator to use for the string. :return: Comma separated string """ return sep.join([str(x) for x in the_list])
166b55e407e16b41aeea648445eb6b2786cb45af
134,467
def contar_letras (cadena: str, letras: str): """Cuenta la cantidad de letras especificas en la cadena Argumentos: cadena (str) -- cadena sobre la que contar letra (str) -- letra que quiero contar """ cuenta = 0 for caracter in cadena: if caracter == letras: cuenta += 1 return cuenta
dafbf667654f5662d8cdae1460b0fadd9f034c2b
304,513
def _escape_string(string): """ Escape Lucene escape characters in string :param string: string to escape :return: escaped string """ escape_chars = ['+', '-', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '&&', '||'] for char in escape_chars: string = string.replace(char, '\\\\{}'.format(char)) return string
dd9b7aa0d5d40c72e2eddc93b33cf181a5e34e04
517,862
def make_round_pairs(sequence): """ Given a sequence [A, B, C] of size n, creates a new sequence of the same size where each new item is the pair of the item at a given position paired up with next item. Additionally, last item is paired with the first one: [(A, B), (B, C), (C, A)]. :param sequence: original sequence :return: paired sequence """ length = len(sequence) return [ (sequence[i], sequence[(i + 1) % length]) for i in range(length) ]
aebb4db852fea30de597170f5f23b013703a1a35
230,847
from typing import Optional def strip_parent_path(path: str, parent_path: Optional[str]) -> str: """Remove a parent path from a path.""" stripped_path = path if parent_path and path.startswith(parent_path): stripped_path = path[len(parent_path):] return stripped_path
45c2df8b847b1587d93d0dfbc7be27d8764ee5e6
243,208
def _af_commutes_with(a, b): """ Checks if the two permutations with array forms given by ``a`` and ``b`` commute. Examples ======== >>> from sympy.combinatorics.permutations import _af_commutes_with >>> _af_commutes_with([1,2,0], [0,2,1]) False See Also ======== Permutation, commutes_with """ return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
b42b7928df67c729fc669dd804d1e951c7c87c1a
580,877
from typing import Tuple def particle_elastic_collision( ux1: float, uy1: float, ux2: float, uy2: float, m1: float, m2: float ) -> Tuple[float, float, float, float]: """2D elastic collision of two particles. The model assumes the particles have zero radius. The larger the particles are, the less accurate this model is. Args: ux1: x-velocity of particle 1 uy1: y-velocity of particle 1 ux2: x-velocity of particle 2 uy2: y-velocity of particle 2 m1: mass of particle 1 m2: mass of particle 2 Return: resulting velocities (vx1, vy1, vx2, vy2) """ vx1 = (ux1 * (m1 - m2) / (m1 + m2)) + (ux2 * 2 * m2 / (m1 + m2)) vx2 = (ux1 * 2 * m1 / (m1 + m2)) + (ux2 * (m2 - m1) / (m1 + m2)) vy1 = (uy1 * (m1 - m2) / (m1 + m2)) + (uy2 * 2 * m2 / (m1 + m2)) vy2 = (uy1 * 2 * m1 / (m1 + m2)) + (uy2 * (m2 - m1) / (m1 + m2)) return (vx1, vy1, vx2, vy2)
05989a25854ff618640cfbf3ecdcbc8acdef6f2d
237,642
def arg_key_diff(s1, s2): """ Finds the difference between two sets of strings. Args: s1 (:obj:`set`): Set 1 s2 (:obj:`set`): Set 2 Returns: :obj:`set` """ return s1 - s2
fb6664a1ad53812f2346fc8136cca726158775b4
343,137
def get_player_name(number, players, team, home_team): """ This function is used for the description field in the html. Given a last name and a number it return the player's full name and id. :param number: player's number :param players: all players with info :param team: team of player :param home_team: home team :return: dict with full and and id """ venue = "Home" if team == home_team else "Away" # Get the info when we get the same number for that team player = [{'name': name, 'id': players[venue][name]['id'], 'last_name': players[venue][name]['last_name']} for name in players[venue].keys() if players[venue][name]['number'] == number] # Control for when the name can't be found if not player: player = [{'name': None, 'id': None, 'last_name': None}] return player[0]
e1c21a5138e68c3afde2dd7617bdd6ff13e0f927
360,675
def end_page(page_list): """ Last page/node in a list of page hits :param page_list: list of page hits :return: last page """ return page_list[-1]
8d774dd3ba66177d4f8720f3bef0d4cd1e396c84
560,719
import gzip def fopen(p, flag="r"): """Opens as gzipped if appropriate, else as ascii.""" if p.endswith(".gz"): if "w" in flag: return gzip.open(p, "wb") else: return gzip.open(p, "rt") else: return open(p, flag)
dc9eaaf69e7ce8bc4d148b4e586ea6decbb75a38
619,065
def min_distance(queue, dist): """ Returns node with smallest distance in queue """ min_node = None for node in queue: if min_node is None: min_node = node elif dist[node] < dist[min_node]: min_node = node return min_node
cb486b26c5b6d0c5ad1e0b1fb1670b06739f5d09
465,705
def get_insert_rows_field_data(row_data): """ Generates the row wise query segments needed to insert rows into a table. :param row_data: Ordered collection of row values :return: Row insertion query segements like '('val1', 123, 'val2'), ('valA', 456, 'valB')' """ return ", ".join( ["(" + ", ".join(map(str, row)) + ")" for row in row_data] )
09c6518dea3370b9628753b1ced6898f9c009cd2
334,320
import csv def matrix(filename): """ :param filename: The csv file :return: A matrix with csv contents """ file = open(filename) reader = csv.reader(file) csv_matrix = list(reader) return csv_matrix
130ab51aa637fca7ba3cb84947fd573d53bf5ac5
523,421
def compute_nonzero_mean_intensity(image_data): """Compute the nonzero mean of a specific fov/chan pair Args: image_data (numpy.ndarray): the image data for a specific fov/chan pair Returns: float: The nonzero mean intensity of the fov/chan pair (`np.nan` if channel contains all 0s) """ # take just the non-zero pixels image_data_nonzero = image_data[image_data != 0] # take the mean of the non-zero pixels and assign to (fov, channel) in array # unless there are no non-zero pixels, in which case default to 0 if len(image_data_nonzero) > 0: nonzero_mean_intensity = image_data_nonzero.mean() else: nonzero_mean_intensity = 0 return nonzero_mean_intensity
fdc828e22413d1a226490521523017a9a7ecd689
221,493
import requests def getLatLon(location): """ Uses the "Google-style geocoder" API at datasciencetoolkit.org to return the latitude and longitude for a location """ if not isinstance(location, str): raise ValueError url = 'http://www.datasciencetoolkit.org/maps/api/geocode/json?sensor=false&address=' response = requests.get(url+location) location = response.json()['results'][0]['geometry']['location'] return (location['lat'], location['lng'])
ad07c6b3a5150d591b8c6a9f42b6c9852b21df21
369,024
def get_imindices_str(fovbounds): """ This returns a string representing the FOV indices Args: ----- fovbounds - list of [rowmin, rowmax, colmin, colmax] Returns: -------- string representation of indices """ return "_rowmin{}".format(fovbounds[0]) + \ "_rowmax{}".format(fovbounds[1]) + \ "_colmin{}".format(fovbounds[2]) + \ "_colmax{}".format(fovbounds[3])
0fa0e9bb38ff9ca9f24915a5a1bdfb9b4955c4d1
286,436
def split_df(df): """ This will split a VOiCES index dataframe by microphone and distractor type Inputs: df - A pandas dataframe representing the index file of the dataset, with the default columns of VOiCES index files. Outputs: df_dict - A dictionary where keys are (mic,distractor type) and values are dataframes corresponding to slices of df with that mic and distractor value pair. """ distractor_values =df['distractor'].unique() mic_values = df['mic'].unique() df_dict = {} for m_val in mic_values: for dist_val in distractor_values: sub_df = df[(df['mic']==m_val) & (df['distractor']==dist_val)] df_dict[(m_val,dist_val)]=sub_df return df_dict
289e28cda52e01933fb9228986dcff1e5a1590fd
98,307
def filter(arg_list, nsitemin, nsitemax): """Filters so nsites is within nsitemin and nsitemax. Parameters: arg_list (list): list of materials. nsitesmin (int): min of nsites. nsitemax (int): max of nsites. Returns: list: filtered list. """ respond_filter_list = [] for i,el in enumerate(arg_list): nsites = el["nsites"] if nsites > nsitemax or nsites < nsitemin: pass else: respond_filter_list.append(el) return respond_filter_list
733854c2c5eabc3ebe787d2d49f770a2c5a9380c
288,891
from typing import List def sum_list(lst: List[int]) -> int: """Takes a list of numbers, and returns the sum of the numbers in that list. Cannot use the built in function `sum`. Args: lst - a list of numbers Returns: the sum of the passed in list """ result = 0 slcounter = len(lst) - 1 while slcounter >= 0: result = result + lst[slcounter] slcounter = slcounter - 1 return result
aa52ffd7128bf8e7a145ddd87adfdc31c8caafe1
193,189
def chebyshev_distance(a, b): """ Calculate the Chebyshev distance of two vectors. """ distances = [] for x, y in zip(a, b): distances.append(abs(x - y)) distance = max(distances) return distance
aa6fccc804ccbeb312e0bb41693feb05787d84f4
22,081
import logging def getlog(name : str): """Create logger object with predefined stream handler & formatting Parameters ---------- name : str module __name__ Returns ------- logging.logger Examples -------- >>> from __init__ import getlog >>> log = getlog(__name__) """ fmt_stream = logging.Formatter('%(levelname)-7s %(lineno)-4d %(name)-26s %(message)s') sh = logging.StreamHandler() sh.setLevel(logging.INFO) sh.setFormatter(fmt_stream) log = logging.getLogger(name) log.setLevel(logging.INFO) log.addHandler(sh) return log
05e02488db030f2f60d106de8cd0e247072d435a
602,174
def get_spec_name(label): """Converts the label of bazel rule to the name of podspec.""" assert label.startswith("//absl/"), "{} doesn't start with //absl/".format( label) # e.g. //absl/apple/banana -> abseil/apple/banana return "abseil/" + label[7:]
810ebe8231042ea631c0188f4681b55b27327714
305,396
def select_rows_where_list_equal(df, column, items): """Select rows in the dataframe whose column has a list of values. Args: df (pd.DataFrame): Dataframe. column (str): Column name. items (list): List of items. Returns: pd.DataFrame: Dataframe with selected rows. Examples: >>> df = pd.DataFrame({"letters":["a","b","c"], "numbers":[1,2,3]}) >>> select_rows_where_list_equal(df, "letters", ["a","b"]) letters numbers 0 a 1 1 b 2 """ return df.loc[df[column].isin(items)]
b577056426ed4b07521dc2861512e03b79e755e5
275,395
def find_repeated(values): """Find repeated elements in the inputed list Parameters ---------- values : list List of elements to find duplicates in Returns ------- set Repeated elements in ``values`` """ seen, repeated = set(), set() for value in values: if value in seen: repeated.add(value) else: seen.add(value) return repeated
bf4c3168ff9823b71581984105d8807695349fd5
148,546
def _dummyJit(*args, **kwargs): """ Dummy version of jit decorator, does nothing """ if len(args) == 1 and callable(args[0]): return args[0] else: def wrap(func): return func return wrap
665efd1e64f3c1c6a01e65e2f2371a4fb390a51a
250,649
def eth_rpc_host(request): """ RPC hostname or IP. defaults to `localhost`, but can be overridden with `--rpc-host` cli flag """ return request.config.getoption('--rpc-host')
bc801aea7595420b727550a1335992819c72f1ea
439,365
def get_explict_dest(pdf, dest_list): """ Find explict destination page number and rectangle. :param pdf: pdfplumber.pdf.PDF object :param dest_list: A explict destination list, e.g. [page, /XYZ, left, top, zoom] :return: A list of destination contains page number and rectangle coordinates """ dest_page_num = None # find page number from page id dest_page_id = dest_list[0].objid for page in pdf.pages: if dest_page_id == page.page_obj.pageid: dest_page_num = page.page_number # explict destination support a lot possibilities to describe like [page, /XYZ, left, top, zoom], or [page, /Fit] # according to TABLE 8.2 Destination syntax of PDF Reference 1.7 if dest_list[1].name == 'XYZ': dest_rect_x = dest_list[2] dest_rect_y = dest_list[3] else: dest_rect_x = 0 dest_rect_y = dest_list[0].resolve()['MediaBox'][3] # page top return [dest_page_num, dest_rect_x, dest_rect_y]
e6f2abebc2c036ad3f1b3f8a42259b3805b64f02
668,482
def sublist(l, batch_size): """ Helper function to divide list into sublists """ return [l[i:i+batch_size] for i in range(0,len(l), batch_size)]
c0f337821af7ad13d3421c55c775e40f6c07fe6e
355,444
def solution(A): # O(NlogN) """ Given a list of tuples, merge the tuples to show only the non-overlapping intervals. >>> solution([(1, 3), (2, 6), (8, 10), (15, 18)]) [(1, 6), (8, 10), (15, 18)] >>> solution([(1, 4), (4, 8), (2, 5), (14, 19)]) [(1, 8), (14, 19)] """ A.sort(key=lambda value: value[0]) # O(NlogN) merged = [] # O(1) target = () # O(1) for i in A: # O(N) if not target: # O(1) target = i # O(1) elif target[1] >= i[0]: # O(1) target = (target[0], max(target[1], i[1])) # O(1) else: # O(1) merged.append(target) # O(1) target = i # O(1) if target: # O(1) merged.append(target) # O(1) return merged # O(1)
0d57898c5d9f50bfa120be1f550aefe5f67bae75
126,756
def get_unique(frame, column_name): """ Helper function to get unique count for column """ return frame[column_name].value_counts().compute()
5a32b53897658a6ba4b0aebabc1670c6460c16b8
669,174
def checkWinner(board, width, default_value=' '): """ Function to check winner of tic-tac-toe IF your board is a single array that represents all the slots, i.e. [....] We are NOT going to validate that this is a square, we are trusting the user input. The only limitation is that the width * width == len(board) - Checks all rows - Checks all columns - Checks forward diagonal - Checks backwards diagonal If there is a winner, returns the winning mark. """ winner = None # Have to check rows and columns for row in range(width): # A place to collect rows and columns curRow = [] curCol = [] # Formula is width*row + col -> row collection # width*col + row -> column collection for col in range(width): curRow.append(board[(row * width) + col]) curCol.append(board[(col * width) + row]) # Set function returns a collection of unique items # in an enumerable type (list in this case). If the count # is 1 then we have a winner. Save the winners mark. if len(set(curRow)) == 1 and curRow[0] != default_value: winner = curRow[0] if len(set(curCol)) == 1 and curCol[0] != default_value: winner = curCol[0] if winner: break # Now check the diagonals if a row/column didnt do it. if not winner: # Collections for forward/backward diagonal forward = [] backward = [] # Collect them, formulas: # Forward = row * width + row # Backwards = (row * width) + (width - row - 1) for row in range(width): forward.append(board[row * width + row]) backward.append(board[(row * width) + (width - row - 1)]) # Again use set() to figure out if we have a winner. if len(set(forward)) == 1 and forward[0] != default_value: winner = forward[0] if len(set(backward)) == 1 and backward[0] != default_value: winner = backward[0] # returns the winners mark, if this is empty no winner. return winner
977e198e472ab03f32eda29752d341c746a4fbd4
503,827
import json def load_json(path_model): """Loads json object to dict Args: path_model: (string) path of input """ with open(path_model) as f: data = json.load(f) return data
9dcab4abfd82c5e2a5fc362780d9be8cdcb513cb
74,244
def balanced_parts(L, N): """\ Find N numbers that sum up to L and are as close as possible to each other. >>> balanced_parts(10, 3) [4, 3, 3] """ if not (1 <= N <= L): raise ValueError("number of partitions must be between 1 and %d" % L) q, r = divmod(L, N) return r * [q + 1] + (N - r) * [q]
a12c09fd3c07f809849b9e44070ff5aae5fc33d2
535,598
def main2(temp_df): """helper function that aggregates the input by count and sum for plot_main_4""" transformed = temp_df # time(temp_df) label = "loss" # print(transformed.columns) s = ["Second", label] p_sum_agg = transformed.groupby(s)["total_pkts"].agg(["count", "sum"]).reset_index() # print(p_sum_agg.columns) b_agg = transformed.groupby(s)["total_bytes"].agg(["count", "sum"]).reset_index() # p_agg = transformed.groupby(s)['total_pkts'].agg(['count', 'sum']).reset_index() # print("all aggregations made") return [p_sum_agg, b_agg]
225587eb0e9d91644c4ff363ea13ee103a7a7ccf
238,141
def complement(sequence): """Get complementary DNA sequence. Args: sequence (str): DNA sequence: Returns: str: Complementary sequence. """ complement_bases = {'A': 'T','T': 'A', 'C': 'G', 'G': 'C'} return ''.join(complement_bases[base] for base in sequence.upper())
dc9c4fd6e8c140a9c41195055027bd8e55bb4223
342,569
import importlib def get_driver(driver_class): """ Get Python class, implementing device driver, by its name. :param str driver_class: path to a class, e.g. ``ducky.devices.rtc.RTC``. :returns: driver class. """ driver = driver_class.split('.') driver_module = importlib.import_module('.'.join(driver[0:-1])) driver_class = getattr(driver_module, driver[-1]) return driver_class
470a6cd18aef0cc5034479782d3045f1d0142b15
129,130
def trapzint(f, a, b, n): """Estimates integral by the construction of n evenly spaced trapezoids on the interval [a, b]""" h = (b-a) / float(n) sum = 0 for i in range(n): #h serves double duty as both the x-distance width and the x-distance increment sum = sum + (1.0/2)*h*(f(a + h*i) + f(a + h*(i + 1))) return sum
9d7c7e7572d92ca2d2e78b1f7280e0635ac26321
432,972
def build_texts_from_gems(keens): """ Collects available text from each gem inside each keen in a list and returns it :param keens: dict of iid: keen_iid :return: texts: dict of iid: list of strings with text collected from each gem. """ texts = {} for keen in keens.values(): for gem in keen.gems: sents = [gem.text, gem.link_title, gem.link_description] sents = [s for s in sents if s] # filters empty sentences if sents: texts[gem.gem_id] = sents return texts
b9b94f4a1035f03746bd3b18755c02b19a97b27b
694,759
def unique_node_name_from_input(node_name): """Replaces invalid characters in input names to get a unique node name.""" return node_name.replace(":", "__port__").replace("^", "__hat__")
2f6b18298ec44fcb899ba0ebdb02ed38c66a2300
258,186
import math def degrees(rad_angle) : """Converts and angle in radians to degrees, mapped to the range [-180,180]""" angle = rad_angle * 180 / math.pi #Note this assume the radians angle is positive as that's what MMTK does while angle > 180 : angle = angle - 360 return angle
df366e3eef93f0f51feca48b83072bf8b13eba78
39,603
import time def create_anonymous_node_name(node_name="node") -> str: """ Creates an anonoymous node name by adding a suffix created from a monotonic timestamp, sans the decimal. Returns: :obj:`str`: the unique, anonymous node name """ return node_name + "_" + str(time.monotonic()).replace('.', '')
94459ac3c9c03318b5d9215bc82ce5855e653e85
146,411
def MATERIALS_PROPERTIES_0(ELEMENTS, MATERIALS, I_ELEMENT, AUX_1): """ This function creates a vector with the material information of the I_ELEMENT element TYPE_ELEMENT = 0 (Frame element). Input: ELEMENTS | Elements properties | Py Numpy array | ID, Node 0 ... Node (N_NODES - 1), Material ID , | | Geometry ID, Hinge ID node 1, Hinge ID node 2 | MATERIALS | Materials properties | Py Numpy array | ID, Young, Poisson, Density, Thermal coefficient | I_ELEMENT | i element in looping | Integer AUX_1 | ID material | Integer Output: MATERIAL_IELEMENT | Material I_ELEMENT properties | Py list[5] | [0] - Young | | [1] - Shear modulus | | [2] - Poisson | | [3] - Thermal coefficient | | [4] - Density | """ MATERIAL_ID = int(ELEMENTS[I_ELEMENT, AUX_1]) E = MATERIALS[MATERIAL_ID, 0] NU = MATERIALS[MATERIAL_ID, 1] PHO = MATERIALS[MATERIAL_ID, 2] ALPHA = MATERIALS[MATERIAL_ID, 3] G = E / (2 * (1 + NU)) MATERIAL_IELEMENT = [E, G, NU, ALPHA, PHO] return MATERIAL_IELEMENT
49715c783ad78f7fea53947fbc8a8a852c789582
334,427
import torch def dist_tensor(p1, p2): """ Return the euclidean distance between two points. :param p1: First point. :param p2: Second point. :return: Euclidean distance. """ return torch.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
21e750f2c9ba39d202ce2fd602df992ab233ad79
180,266
def dfs_topological_sort(arr, n): """ Topological sort with DFS. Return an empty list if there is a cycle. """ graph = [[] for _ in range(n)] for u, v in arr: graph[u].append(v) visited, stack = [0] * n, [] def dfs(u): if visited[u] == -1: return False if visited[u] == 1: return True visited[u] = -1 for v in graph[u]: if not dfs(v): return -1 stack.append(u) visited[u] = 1 return True for u in range(n): if not dfs(u): return [] return stack[::-1]
8c917f372029a7a4e7f132a5141d05a69d8fb227
652,999
import random import math def rGeom(p): """Generate a geometrically distributed random number. p is the success probability. The numbers are in the range {0, 1, 2,...}""" # CDF = 1-(1-p)^(k+1) (CDF of geometric distribution) # (1-p)^(k+1) = 1-CDF (... solve for k ...) # k+1 = log(1-CDF)/log(1-p) # k = (log(1-CDF)/log(1-p)) - 1 # insert a uniform random number in [0;1] for CDF to # obtain geometrically distributed numbers u = random.random() if p == 1 : return 0 return math.ceil( (math.log(1-u,1-p))-1 )
7eb1d3bbac0c79e1341abb2fa9528ea8c6c88e84
32,755
import re def GetTimeServers(File): """ Extract the timeservers from ntp.conf Args: File - Module to access ntp config file Returns: ntp_servers - List of configured servers as indicated by ntp.conf """ ntp_conf = File("/etc/ntp.conf") # Remove any configuration options that come after the server/pool name all_ntp_servers = map(lambda x: re.sub(" .*", "", x), re.findall("\n(?:server|pool)\s*(.*)", ntp_conf.content_string)) # Filter fallback NTP server from configuration file. user_ntp_servers = filter(lambda x: x != 'ntp.ubuntu.com', all_ntp_servers) return user_ntp_servers
5bcc38c9b8e0f313185b5563024435ed810578ca
471,781
import six def call_module(module, one_hots, row_lengths, signature): """Call a tf_hub.Module using the standard blundell signature. This expects that `module` has a signature named `signature` which conforms to ('sequence', 'sequence_length') -> output To use an existing SavedModel file you may want to create a module_spec with `tensorflow_hub.saved_model_module.create_module_spec_from_saved_model`. Args: module: a tf_hub.Module to call. one_hots: a rank 3 tensor with one-hot encoded sequences of residues. row_lengths: a rank 1 tensor with sequence lengths. signature: the graph signature to validate and call. Returns: The output tensor of `module`. """ if signature not in module.get_signature_names(): raise ValueError('signature not in ' + six.ensure_str(str(module.get_signature_names())) + '. Was ' + six.ensure_str(signature) + '.') inputs = module.get_input_info_dict(signature=signature) expected_inputs = [ 'sequence', 'sequence_length', ] if set(inputs.keys()) != set(expected_inputs): raise ValueError( 'The signature_def does not have the expected inputs. Please ' 'reconfigure your saved model to only export signatures ' 'with sequence and length inputs. (Inputs were %s, expected %s)' % (str(inputs), str(expected_inputs))) outputs = module.get_output_info_dict(signature=signature) if len(outputs) > 1: raise ValueError('The signature_def given has more than one output. Please ' 'reconfigure your saved model to only export signatures ' 'with one output. (Outputs were %s)' % str(outputs)) return list( module({ 'sequence': one_hots, 'sequence_length': row_lengths, }, signature=signature, as_dict=True).values())[0]
efd8a7b991c2f8c95abbed55566d882a4af750c2
589,442
import math def distanceModulus(i, j, pos_X, pos_Y): """ Measures the distance modulus between two particles i, j """ i = int(i) j = int(j) dist_X = pos_X[j] - pos_X[i] dist_Y = pos_Y[j] - pos_Y[i] dist = math.sqrt(dist_X**2 + dist_Y**2) return dist
1a2c2bb3a5db0fd23d8aab044457269ad23b901d
184,424
import click def confirm_destroy(name, abort=True): """Confirm the user wants to destroy the machine.""" return click.confirm('Are you sure you want to destroy the "{0}" machine?'.format(name), abort=abort)
0ebc13b023fd341e29df08a11d0872654d2b157c
162,060
def containsNonAlphaNum(word_list): """ Does list of words contain any special characters? Parameters: word_list: list of words Returns: bool: whether any word in the list contains a special character """ chars = ["-", "_", "."] allow_chars = set(chars) for word in word_list: for char in word: if not(char.isalnum()) and char not in allow_chars: return True return False
7a87c706eaec5cd4ee10fa0ccc027a4850430eb3
27,230
import requests def get_latest_message(group, token): """Gets the most recent message from a group. Token must be valid for the group.""" GROUP_URI = 'https://api.groupme.com/v3/groups/' + str(group) r = requests.get(GROUP_URI + '/messages?token=' + token + '&limit=1') return r.json()['response']['messages'][0]
47d0f374747917b4b81c812264d2b0139cb2ae90
228,192
def _get_headers_from_args( method=None, url=None, body=None, headers=None, retries=None, redirect=None, assert_same_host=True, timeout=None, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw ): """ extract headers from arguments """ # pylint: disable=unused-argument # not using '_' in arg names so unrolling will be smoother return headers
ba1137130d0bf12007518462b2488772394c0ff9
180,400
def animals(chickens: int, cows: int, pigs: int) -> int: """Return the total number of legs on your farm.""" return sum([(chickens * 2), (cows * 4), (pigs * 4), ])
65046ff425e90b885571f46dabd3d2325713c93d
442,923
def getmatchingfiles(pattern1, pattern2, list): """ From a list of files get a new sorted list of files matching both patterns 1 and 2 :param pattern1: :param pattern2: :param list: :return: """ return [file for file in sorted(list) if pattern1 in file and pattern2 in file]
7575bb9bb7c74b78f07da5739720ea99169230ba
449,578
def _group_by_size_histogram_data(dataframe, group_by_key): """Returns a histogram of the number of elements per group. If you group by sequence_name, the dictionary you get returned is: key: number of predictions a sequence has value: number of sequences with `key` many predictions. Args: dataframe: pandas DataFrame that has column group_by_key. group_by_key: string. The column to group dataframe by. Returns: dict from int to int. """ return dataframe.groupby(group_by_key).size().to_frame('size').groupby( 'size').size().to_dict()
8f0e101ffbbb9f8967e08517790ac68cbaedd040
601,021
def get_type(value): """ Return the name of the type for a value. This is used when displaying values via HTML templates. """ return type(value).__name__
fe45050a229b536db2f5e9c42ae8605cef94cd93
540,716
def StringToInt(handle_automatic=False): """Create conversion function which converts from a string to an integer. Args: handle_automatic: Boolean indicating whether a value of "automatic" should be converted to 0. Returns: A conversion function which converts a string to an integer. """ def Convert(value): if value == 'automatic' and handle_automatic: return 0 return int(value) return Convert
ee76411efc4a1bd8b0eccc67cbb035a4b7778792
213,576