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 ""...
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 ...
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 == ')': ...
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 seco...
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: ...
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: ...
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...
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 ...
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...
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 + tota...
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'...
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 fill...
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' >>> _GetAliasFor...
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 ...
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. ...
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 ':...
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 ...
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 ...
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(comb...
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 ...
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, otherw...
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 stri...
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: ...
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.repl...
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 ...
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 ======== Permutat...
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....
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 :p...
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( ["(" ...
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...
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...
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...
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,di...
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 ...
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 slcou...
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(__nam...
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. ...
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: ...
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 """ ...
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)]) ...
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 ...
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] +...
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() ...
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[...
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) + ...
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...
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()).rep...
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 ...
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 i...
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) ...
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...
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 ma...
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...
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']['me...
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, **resp...
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: dat...
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 C...
ee76411efc4a1bd8b0eccc67cbb035a4b7778792
213,576