content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import requests def get_user_info(token): """ Gets user information from Eventbrite Arguments: token -- the Eventbrite user OAuth token, used to authenticate with Eventbrite's API. Returns: resp -- the response from the API """ # set token in request header headers = {"Authorizat...
5f3ed5b9ae91ab113fc30d0ee54dfb7e62c40442
608,958
import re def convertpstring(string): """ converts a string of the form 7p5 to 7.5 float Parameters ---------- string : str String needing replacement Returns ------- f : float Converted value """ regex = r"(\d+)p(\d+)" m = re.search(regex, string) if...
a2c3890c45f4e2038f2560b234cfeb1fbe8adc79
608,963
from functools import reduce def n_choose_k(n, k): """Return the number of combinations for n choose k. Args: n (int): the total number of options . k (int): The number of elements. Returns: int: returns the binomial coefficient """ if n == 0: return 0 else: ...
8056b77c30aaa2b360aa28eff5a5f30100ed5844
608,965
def get_base_units() -> dict[str, int]: """return mapping {label: seconds} for standard base units of time""" return { '1s': 1, '1m': 60, '1h': 60 * 60, '1d': 60 * 60 * 24, '1w': 60 * 60 * 24 * 7, '1M': 60 * 60 * 24 * 30, '1y': 60 * 60 * 24 * 365, }
f8b976af051385ab41e5b20e8a86f52d7bbda3b9
608,967
import hashlib def sha224(content): """Finds the sha224 hash of the content.""" return hashlib.sha224(content).hexdigest()
7d108e35d47adcd22440265e6dcb790935e48eb6
608,971
from typing import Union def safe_ord(byte: Union[bytes, int]) -> int: """If `byte` argument is byte character, returns ord(byte), otherwise returns argument. """ return byte if isinstance(byte, int) else ord(byte)
5506cfe93a31694cc4dde4add839253ed7c3a258
608,972
def get_facility_data(df,num): """ Fetch all the data where Federal Provider number matches NUM Return: - None if Nothing Found else a dataframe """ new = df[df['Federal Provider Number'].str.match(num)] if len(new) == 0: print("No Data Found") return None return new
a7f893e9c2312fcd05a604b04a91e4d4e84caf79
608,975
import time def diff_timestamps(timestamp1, timestamp2): """Compute time delta in seconds from the two string timestamps.""" t1 = time.mktime(time.strptime(timestamp1)) t2 = time.mktime(time.strptime(timestamp2)) return t2 - t1
1640500544257be69f3a160c712287e63e118f82
608,977
def arithmetic(left_operand, right_operand, operation): """ Применяет заданную в параметре operation математичечскую операцию к left_operand и right_operand. Операция должна быть бинарной. :param left_operand: левый операнд. :param right_operand: правый операнд. :param operation: символ операции...
69ab1fb86c06d56176d5250b921b067252611afa
608,982
import functools import operator def output_dimensionality(X, y, **kwargs): """ It represents the total number of output values in the dataset (i.e. the dimensionality of the output vector.) """ if y is None: return 0 else: return functools.reduce(operator.mul, y.shape[1:], 1)
18d301049b098fdcdde0ae29745a1beacfe9b641
608,983
def read_log(fname): """Read a log file. Args: fname (str): Name of log file Returns: str. Command log """ log_file = open(fname, 'r') log = log_file.read() return log
aa3f2a34251a968b05b90cb7bb21cb4267dfb52a
608,985
def isint(value): """ Check if value can be converted to int :param value: input value :return: True/False """ try: int(value) return True except ValueError: return False
60cfd41ba4f999a59fb9921253bcbebccb4c0b7e
608,988
def bool_from_str(val): """Convert a string representation of a bool into a bool value.""" if not val: return False try: return bool(int(val)) except ValueError: if val.lower() in ['true', 'yes', 'y']: return True if val.lower() in ['false', 'no', 'n']: ...
303cc2e7b6abd590ab263e16517b78a0565915b5
608,990
def get_first_element(dict_, key, default=None): """ Take one value by key from dict or return None. >>> d = {"foo":[1,2,3], "bar":7} >>> get_first_element(d, "foo") 1 >>> get_first_element(d, "foobar") is None True >>> get_first_element(d, "foobar", "") == "" ...
f516e1a55b552a5eb849057fd48205f96fb8eaaf
608,993
def remove_keys(doc, keys): """Return a new document with keys in keys removed >>> doc = {'a':1, 'b':2} >>> remove_keys(doc, ['a']) {'b': 2} >>> # Show that the original document is not affected >>> doc['a'] 1 """ return dict( (k, v) for k, v in doc.items() if k not in keys)
dbee370982d6f3884dc2f4d137ba6b3e38791398
608,997
def intensity_factor(n_power, ftp): """ Compute the intensity factor with the following: IF = Intensity Factor NP = Normalized Power FTP = Functional Threshold Power by doing: IF = NP / FTP """ return round(n_power / ftp, 2)
9c962bdfe6849eb65cf7c93db7518822bd31f6b6
608,998
def contains_pseudoknot(bplist): """Checks if a list of base pairs contains a pseudoknot. Returns boolean""" for a1, a2 in bplist: for b1, b2 in bplist: if (a1 < b1 < a2 < b2) or (a2 < b1 < a1 < b2) or (a2 < b2 < a1 < b1): return True return False
cd025ba7051189a5848ea8202eb0ae2dc230ec9a
608,999
def arguments_to_args_renames(arguments): """ The doc-opt parsed arguments include the - and -- and certain names are different. In order to have an apples-to-apples comparison with the new argparse approach, we must rename some of the keys. """ args = {} for k, v in arguments.items(): ...
bdc817e0e666efb6e8fe9d5a7b07637e2b525b48
609,001
import requests def get_census_variable_descriptions(dataset, year, variables): """ Download descriptions of census variables from the API """ url_template = "https://api.census.gov/data/{year}/{dataset}/profile/variables/{variable}.json" variable_descriptions = {} for variable in variables: ...
e87bd8890a46907f03182d0633e1508c562d8f82
609,004
from typing import Union def media(muestra: list[Union[int, float]]) -> float: """Calcula el promedio aritmético de una muestra. Parameters ---------- muestra Arreglo de datos Returns ------- float Media """ return sum(muestra)/len(muestra)
e1a7f307fd36a58be05c055d941d4ac65bd4db11
609,005
def get_grandma(clause_atom, api): """Return a wayyiqtol/yiqtol/imperative from a clause tree. Recursively climbs up a clause's ancestorial tree. Stops upon identifying either wayyiqtol or a yiqtol|impv grand(mother). Returns: a string of the ancestor's tense, or None. """ F, E, L...
100fa98829ff2f0573ca71f2769b97d70363a53c
609,011
def format_size(size): """Format a byte count as a human readable file size. >>> format_size(0) '0 bytes' >>> format_size(1) '1 byte' >>> format_size(5) '5 bytes' >>> format_size(1024) '1 KiB' """ size_sign = "" if size > 0 else "-" size = abs(size) size_units = [(10...
76b017c4422b990428db3532e02bb68abd5cde5e
609,012
import re def clean_text(text): """ Prepare question text for tokenization: lowercase, remove punctuation, and remove episode numbers (these are added during Spark pipeline) e.g., "Who plays in Seinfeld: The Contest S10E8?" ==> "who plays in seinfeld the contest" :param question: string representing question ...
231b45b79e0cb427ad3a6147e04fe56416823ec8
609,013
def format_quantity(q, fmt="{:g}", ufmt="{:s}", u=None, basefmt="{value:s} {unit:s}"): """Use format strings to format a quantity. :param astropy.units.Quantity q: The quantity object to format. :param str fmt: The value format string. :param str ufmt: The unit format string. :param u: The unit...
4001290cb7e246c6db5c638a803004b1c282fd04
609,014
def remove_escapes(msg) -> str: """ Returns a filtered string removing \r """ filtered = msg.replace(r'\r', '') return filtered
84edc1920c8d9bc4376d63561a91ce56eba19102
609,017
from typing import List def f(grado: int, coeficientes: List[int], x: float) -> float: """Calcula el valor de un polinomio de grado n :param grado: grado del polinomio :grado type: int :param coeficientes: coeficientes del polinomio :coeficientes type: List[int] :param x: valor de x :...
8198baabaf766a6a74701d7dbaaeb103543c8cee
609,020
def _operation_to_style_map(style, operation, dict_of_log_msg): """ Operations need to be updated in cases that: 1) no operator is provided and the goal is to == or != 2) the style is exclude yet we are checking for contains/within/not contains """ if style == 'excluded': if...
958e6e3e473f395f9adfe2b6774e2c59ae2c1152
609,027
def reddit_url(api_response): """Return the post url from the reddit API response.""" # This is because of reddit's insane return values return api_response['jquery'][-1][3][0]
538daa2d6c69de51eee344f4f74bb1bc9668ee74
609,028
import struct def swap_rgb(i): """ Swap a 32bit RRGGBB (integer) to BBGGRR. """ return struct.unpack("<I", struct.pack(">I", i))[0] >> 8
b9c4c9938d35a24dbc51541fd87e7f9c8f27de8b
609,029
def menu(value): """ Menu function for game loop. """ print( f""" What is your next move? ................... r roll the dice. q quit the game. .................................................. Your current dice hand value: {value} .................................................. """ ...
3c0a3e473e2860206377c53df35135f229a62eee
609,030
def split_text_segment_id(text_segment_id): """ Get the bnc part and fragment id given a text segment id. """ bnc_part, frg_n = text_segment_id.split('-') assert len(bnc_part) == 3, text_segment_id assert frg_n.startswith('fragment') return bnc_part.upper(), int(frg_n[8:])
6b26ad04962c331e57c3a731c52ac3eb6e9ca996
609,036
def all_orig(f,c): """ Do all members of c satisfy f? """ for i in c: if not f(i): return False return True
27d6272cf53e76f412aee071af7dbf8251669367
609,040
from typing import Optional from typing import Dict from typing import Any def update_draft( access_key: str, url: str, owner: str, dataset: str, *, draft_number: int, state: Optional[str] = None, title: Optional[str] = None, description: Optional[str] = None, ) -> Dict[str, Any]: ...
57566bdf3d953ec52134dcb177b49ed62e955f8b
609,044
import torch def project_1D(w, d): """ Project vector w to vector d and get the length of the projection. Args: w: vectorized weights d: vectorized direction Returns: the projection scalar """ assert len(w) == len(d), 'dimension does not match for w an...
d737b415d47eb6b75ae33019f481fbac514d2e71
609,048
from typing import List import codecs def read_data(file_path: str, drop_first: bool = False) -> List[str]: """ Function to read textual data with simple newline formatting Args: file_path (str): path to file drop_first (bool): drop first row given it is a header Returns: col...
233a99e3b2008cd6a881adf8547af5e24c0ab776
609,050
from datetime import datetime def datetime_to_time(x): """Convert a datetime into a time""" if isinstance(x, datetime): return x.time() return x
81a151fac661a7f683a7931e50e0c245c0e5133a
609,051
def _parse_td(row): """Return the td elements from a row element. Parameters ---------- row : node-like A DOM <tr> node. Returns ------- list of node-like These are the elements of each row, i.e., the columns. """ # Look for direct children only: the "row" element he...
9f4a2a55749a4f2016e71d243189e1b99ca9bf08
609,056
def mixmat_to_columns(mixmat): """ Flattens a mixing matrix taking only elements of the lower triangle and diagonal. To revert this use `series_to_mixmat`. """ N = mixmat.shape[0] val = [] for i in range(N): for j in range(i+1): val.append(mixmat[i,j]) return val
37f840d0cd4a1d54e078fe8e0ec6a5641a889cd5
609,059
def is_cjk(character): """ Python port of Moses' code to check for CJK character. >>> CJKChars().ranges [(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215), (63744, 64255), (65072, 65103), (65381, 65500), (131072, 196607)] >>> is_cjk(u'\u33fe') True >>> is_cjk(u'\uFE5F') False...
fee25f935a23cdaa242fe8a8d5c3127647a38ccf
609,060
from functools import reduce def _get_fragments_coord(frags): """Return the letter coordinate of the given list of fragments (PRIVATE). This function takes a list of three-letter amino acid sequences and returns a list of coordinates for each fragment had all the input sequences been flattened. ...
8948c16e68048e9b3b4a4fe7455cff816d1cb736
609,066
from typing import List def parse_sample_top(parts: List[str]): """ Structure: $corpus.sample.top.$seed.$metric Example: test.sample.top.2.meteor :param parts: :return: """ corpus, sample_origin, decoding_method, seed, metric = parts num_samples = "1" length_penalty_alpha = "...
c16ba9cc5f445dd65b84fa59014a536319e34d5d
609,067
def privacy_check(postal_code: str) -> bool: """ Helper function for the callbacks. Checks if postal code is private. --- Args: postal_code (str): Area postal code. Returns: True (bool): When postal code is in the private_list False (bool): When postal code is not foun...
15313eab1cc1316b29c8901e53124030f2893821
609,068
def convert_tweets_to_list(timeline): """Converts a list tweet objects into string object for easier parsing in downstream algorithms. Args: timeline ([tweet]): list of tweets Returns: [string]: list of tweets converted into string """ list_tweets = [] for tweet in timelin...
d049b60c4b426e8c594c040977e847cc475bface
609,069
def _is_num(data): """Verify if data is either int or float. Could be replaced by: from numbers import Number as number isinstance(data, number) but that requires Python v2.6+. """ return isinstance(data, int) or isinstance(data, float)
940ab3eb907a73bb5da2c807c1b30aff1ba8e4d9
609,073
def getGatewayIntf(ch): """ Looks at the key:networkInterfaces for the chute and determines what the gateway should be including the IP address and the internal interface name. Returns: A tuple (gatewayIP, gatewayInterface) None if networkInterfaces doesn't exist or ...
fe5b161899200525192f43c8f5f7a57b6b4c3142
609,074
def set_bit(current, epaddr, v): """ >>> bin(set_bit(0, 0, 1)) '0b1' >>> bin(set_bit(0, 2, 1)) '0b100' >>> bin(set_bit(0b1000, 2, 1)) '0b1100' >>> bin(set_bit(0b1100, 2, 0)) '0b1000' >>> bin(set_bit(0b1101, 2, 0)) '0b1001' """ if v: return current | 1 << epadd...
88b91bccf8949e50039a4db8e67adfe3d63dd427
609,075
def sim_to_label(similarity): """Convert similarity to edge label. Parameters ---------- similarity : float Similarity between two answers. Returns ------- str Label of the edge. Similarity in percentage i.e 90%. """ return str(round(similarity*100)) + '%'
71cfeeb28b7f05b1abb0dec8766f204118b3b937
609,076
from typing import Dict from typing import Any from typing import Tuple from typing import List def is_valid(data: Dict[str, Any]) -> Tuple[bool, List[str]]: """ Verify that the `data` (which should be obtained from a YAML file using `load_data()` contains a well-formed List of disjunct memory regions ord...
4f4df292603e409828f9a6be1f0380e22f505446
609,078
def format_timedelta(delta): """Return XdYhZm string representing timedelta.""" return '%dd%dh%dm' % ( delta.days, delta.seconds / 3600, (delta.seconds % 3600) / 60)
263c1eb07c1e07941dcaa401d583a40b989a47cd
609,079
def divide(x: int, y: int) -> float: """divide one number by another Args: x (int): first number in the division y (int): second number in the division Returns: int: division of x and y """ return x / y
fc748fe4ddb01f41739663b036fe1521d0185706
609,081
def _theta_hat_amc_lh88(sinlat, sinlat_1, theta_hat_1, theta_ref, del_h_over_ro): """Lindzen and Hou 1988 Eq. 7.""" return (theta_hat_1 - 0.5*theta_ref*del_h_over_ro * (sinlat**2 - sinlat_1**2)**2 / (1 - sinlat**2))
ba5f2ab5c174d4ccca1c1355f46756c5dc526f36
609,084
def greater_than(x, y): """Returns True if x is greater than y, otherwise False.""" if x > y: return True else: return False
7931e5fdf133957031a68b2e4b64386d833c376e
609,087
import torch def softmax(correlation_maps: torch.Tensor): """Applies a 2D spatial softmax operation on the dense correlation maps. Args: * correlation_maps: The batch of the dense correlation maps, of size [N x H x W] Returns: * The correspondence maps. """ batch, height, width = c...
fa4bf42c3d510ccefd43eeb24c820958a9b8e897
609,089
def find_without_whitespace(string, substring): """Returns True if string contains substring, disregarding whitespace, False otherwise.""" strlist = string.strip().split() sublist = substring.strip().split() strnorm = ' '.join(strlist) subnorm = ' '.join( sublist ) return strnorm.find(subnor...
b546aee17f3b659ceeefedcc838a5fd85634ca2e
609,094
def get_evergreen_versions(evg_api, evg_project): """Return the list of evergreen versions by evergreen project name.""" return evg_api.versions_by_project(evg_project)
d6a413ae83f660144cb221452117a3a2bf7fd191
609,095
def test_id(request): """Generates a unique identifier for a test. Used for marking up logs and workspaces used by a test so the generated artifacts can be isolated from other tests Args: request (pytest.fixture.SubRequest): metadata describing the currently running tests Retu...
cc1ab46b984ced85cd13b853b1dc37df5b2b0442
609,099
from typing import List from typing import Dict def sort_items(items: List[Dict]) -> List[Dict]: """ Sort a list of dict items associated with packages. :param items: list of dicts that represent items. :return: sorted list. """ return sorted(items, key=lambda k: k["name"])
9bbb62dafc52a4232d5b385444fdaef30912afbe
609,101
from typing import List import random def shuffle_concurrent_lists(l: List[List[object]]): """ Shuffles multiple concurrent lists so that pairs of (x, y) from different lists are still at the same index. :param l: A list of concurrent lists :return: The list of shuffled concurrent lists """ ...
59ebf2a9d7ecbf84f2489613376724931d782d45
609,106
def quick_sort(seq): """Quicksort method.""" if isinstance(seq, list): if len(seq) <= 1: return seq piv, seq = seq[0], seq[1:] low, high = [x for x in seq if x <= piv], [x for x in seq if x > piv] return quick_sort(low) + [piv] + quick_sort(high) else: rai...
47e5691b6808993d8e4387f1f10f03ab656be443
609,109
def add_label(key, value, k8s_yaml): """Add 'domain: `domain`' label to k8s object. Args: key (str): Label key. value (str): Label value. k8s_yaml (dict): Loaded Kubernetes object (e.g. deployment, service, ...) """ k8s_yaml["metadata"]["labels"][key] = value return k8s_yaml
86235cd0dfdd9c66dd815a72799a24fd1cc8aafa
609,112
import math def distance(p1, p2): """ Calculates the distance between two points. :param p1, p2: points :return: distance between points """ p1x, p1y = p1 p2x, p2y = p2 return math.sqrt((p1x - p2x) ** 2 + (p2y - p2y) ** 2)
13cc6d2c2007441478fec8f4b17f08113cbdc2e6
609,113
def calculate_num_groups(conf, num_networks=None): """ Calculates how many prefix groups we can have per AWS zone. Takes into account that we need a route for each prefix group and we can't have more than 48 route total. """ num_zones = len(conf['aws']['zones']) num_nets = len(conf['netw...
e53a67a6e4b69215b8753568ddd64e17c9f4fc94
609,114
def interleave(l1: list, l2: list) -> list: """Interleave two lists. >>> interleave([1,2,3], ['a', 'b', 'c']) [1, 'a', 2, 'b', 3, 'c'] Reference: https://stackoverflow.com/a/11125298/3516684 """ return [x for t in zip(l1, l2) for x in t]
244865f54b22eb3a286121e96f254debdb74ccf5
609,117
def request_count(response): """Count the number of request on this route""" return "count", 1
09216e10286ee2cd4e42951bb1075adcc2c9dd7d
609,118
import socket def gethostbyname(host, prefer_ipv4=True, require_ipv4=False): """Like socket.gethostbyname, but may return an IPv6 address.""" if require_ipv4: family = socket.AF_INET else: family = 0 results = socket.getaddrinfo( host, None, family, socket.SOCK_STREAM, socket.I...
cfedf2962508d7f48c4f78327e1fbc46b1393fc4
609,119
def unindenter(string, spaces = 3): """ Returns string with each line unindented by 3 spaces. If line isn't indented, it stays the same. >>> unindenter(" foobar") 'foobar\\n' >>> unindenter("foobar") 'foobar\\n' >>> unindenter('''foobar ... foobar ... foobar''') 'foobar\\nfo...
666e229c620569b0c7545367adb36ccbaf8da113
609,120
def jaccard_distance_numeric(x_or_y: float, x_and_y: float) -> float: """ Calculated the jaccard distance between two series using pre-computed area values. Parameters ---------- x_or_y, x_and_y: float precomputed x_or_y and x_and_y, respectively. """ return (x_or_y - x_and_y) / x_or_y
a0636b20e45c906b32c76ef9511ed5cbbaf4d161
609,123
def _get_prepend(compiler, osname): """Return the appropriate prepend for a compiler switch for a OS. Parameters ------- compiler : str compiler name osname : str lower case OS name Returns ------- str : str prepend string for a compiler switch for a OS """...
cfb92ec2b6d2148b61dab650631241d284f7c25d
609,125
def getValue(dictionary, key, value): """ Returns the value for the key in the dictionary or the default. :param dict dictionary: :param object key: :param object value: :return object: """ if not key in dictionary.keys(): return value else: return dictionary[key]
341ad01e6c534d7a6676a949112d5a4be0fe7f21
609,132
def rule_attrs(ctx, aspect): """Gets a rule's attributes. As per https://docs.bazel.build/versions/master/skylark/aspects.html when we're executing from an aspect we need to get attributes of a rule differently to if we're not in an aspect. Args: ctx (ctx): A rule's context object aspe...
8bff31cca8ba74f693b3f4e1aa6fed0b16c5b61e
609,136
def method_int_to_str(method_number): """ Function to convert validation- hyperparametertuning method number to string. Parameters ---------- method_number: int number of validation- hyperparametertuning method (1 = grid-search, 2 = random-search) Returns ------- validation_meth...
e0744319381934e52a1aed9e0431d23491f4c198
609,142
def get_primes_under_n(n): """ Return list of primes less than n >>> get_primes_under_n(23) [2, 3, 5, 7, 11, 13, 17, 19] """ if n <= 1: return [] flags = [False, False] + [True for _ in range(2, n + 1)] for p in range(2, n // 2 + 1): if flags[p]: for q in ra...
724fc3d6bcdd76429fd24b89ec1450e20c464759
609,145
def factorial(number: int) -> int: """ >>> factorial(5) 120 >>> factorial(0) 1 >>> import random >>> import math >>> numbers = list(range(0, 50)) >>> for num in numbers: ... assert factorial(num) == math.factorial(num) >>> factorial(-1) Traceback (most recent call las...
a63bb3c547411e265184eda954c4616d29a759e5
609,147
import math def format_positional_error( line: int, pos: int, string: str, message: str, prior_lines: int = 3 ) -> str: """Format a positional error generated by Scrolls. Args: line: The line the error was generated on. pos: The character the error was generated on. ...
5866d71edc67021fc578f3ac50de9fd3c964aba3
609,149
def umich_email_detection(potential_email): """ This function tests whether a string is a University of Michigan email address. If it is, it returns the uniqname before the '@umich.edu' (e.g., 'janesmith@umich.edu' would return 'janesmith'). If it is not a umich email address, this function should retur...
c4c9b1c3526123249eecd1bf89c42f3c005d401b
609,152
import struct def summary_simple_value(summary_value): """Returns the scalar parsed from the summary proto tensor_value bytes.""" return struct.unpack("<f", summary_value.tensor.tensor_content)[0]
2b4ee5b4c5f8cd29f61c38a59d63a034e68be533
609,156
import io import base64 def pilImgToBase64(pilImg): """Encodes PIL image to base64 Arguments: pilImg {PIL} -- PIL image Returns: string -- Encoded base64 image string """ pilImg = pilImg.convert('RGB') imgio = io.BytesIO() pilImg.save(imgio, 'PNG') img...
6f8762aab4c20632aa84fd07a975282797e7e6fe
609,157
def build_ignorables_mapping(copyrights, holders, authors, urls, emails): """ Return a sorted mapping of ignorables built from lists of ignorable clues. """ ignorables = dict( ignorable_copyrights=sorted(copyrights or []), ignorable_holders=sorted(holders or []), ignorable_author...
ff59c7abb151b6d8dd2eadfef7e2d37c19652f63
609,158
def gray_code_gen(N): """Generates the sequence of binary gray codes of width N Parameters ---------- N : integer Width of the binary gray codes Returns ------- data : list The list of generated binary gray codes of width N """ data = [] for i in range(0, 1 << N...
aa723930a7a62c3a3042728fe8ef1fd80a60003b
609,159
def parse_row(row): """ Takes a row of MOS data and returns the variable and a list of values. Parameters ----------- row : string The rows where the data collected is stored. Returns -------- var : string Value spaces that are part of the rows vals : list ...
fca90f49e7fb8a3eaf1bb9b164812daa2a01a5bd
609,161
def GenerateFirefoxCommandLine(firefox_path, profile_dir, url): """Generates the command line for a process to run Firefox Args: firefox_path: String containing the path to the firefox exe to use profile_dir: String containing the directory of the profile to run Firefox in url: String containing url to...
0fe18e2ecd69cfb75b17e4c7e0f0dedd089a3d2d
609,164
def _no_tiebreak(winners, n=1): """ Given an iterable of `winners`, return None if there is a tie. """ if len(winners) <= n: return winners else: return [None]
303c35264ea8c7bc38cafd670cd7b95b9982d0e8
609,166
def make_triangle(triangle_height, offset = 0, tree_cutoff = 0, triangle_background = ' ', triangle_fill = '*'): """ triangle_height: how many rows the triangle will have. offset: how many spaces (or background fill) the triangle will have. triangle_cutoff: how many rows to delete from the t...
171a68e3ae1ddc6fea759a0e432d45f9dd73c689
609,167
def green(string): """ Convert a string to green text :string: the string to convert to green text """ return f'\033[92m{string}\033[0m'
ae4567afe4d9882d08bc8de4f277bf91e19d624c
609,168
def normalize_proportions(proportions): """ Proportions specified in config file are all just relative - this normalizes them to a proportion out of 1.0 :param proportions: The proportions dictionary generated by parse_config_file :return: A dictionary in the same format as that generated by parse_confi...
b95e293227d3cce804981d7ea6df3fabc74a0757
609,169
def type_name(typ): """Returns a string representation of a type. Args: typ: The type to get a representation of. May be an instance of type or a tuple of types. Returns: A string representation of typ. Raises: TypeError: Wrong input arguments. """ if typ == str: return 'string' ...
975d30859833241d9d0ca06f6f27759c97cde0a2
609,171
def get_resume_block(block): """ Gets the deepest block marked as 'resume_block'. """ if block.get('authorization_denial_reason') or not block.get('resume_block'): return None if not block.get('children'): return block for child in block['children']: resume_block = get_...
5b52d7a7ec4a49f0a99c380b1085855bec6c8842
609,176
def peel_off_prefix(file_name): """ Takes a file name, rsplits off the ".ext" then replaces it with ".fa" """ pf_name = file_name.rsplit('.') fa_file_name = pf_name[0] + ".fa" return fa_file_name
b7cb5cb7bf9d9e805e0c282bd4b0a36192b14db0
609,182
def area(gdf): """Returns area of GeoDataFrame geometries in square kilometers.""" return gdf.to_crs(epsg=3035).area.div(1e6)
dfcd35c363699fe27052e2a4c8b3c3d24580513d
609,188
def fib(n, a=0, b=1): """nth fibonacci number (tail-recursive)""" if n == 0: return a return fib(n-1, b, a+b)
07933db3fafc757542b0dfcd725ad4bb11e4251d
609,190
def get_el_feedin_tariff_chp(q_nom, el_feedin_epex=0.02978, vnn=0.01): """ Calculates feed-in tariff for CHP-produced electricity. Parameters ---------- q_nom : nominal thermal power of chp in kW el_feedin_epex : epex price for electricity in Euro/kWh vnn : avoided grid charges ("vermiedene...
d25c28aa678a5b30a2c13f143b3cfb46cd9d2edb
609,194
def registerConfig(name, registry, target): """A decorator that adds a class as a ConfigClass in a Registry, and associates it with the given configurable. """ def decorate(cls): registry.register(name, target=target, ConfigClass=cls) return cls return decorate
2b9bf3235887891c37478ba4881f825708125923
609,196
def merge_contiguous(index_bounds): """ Combines any contiguous index bounds. Args: index_bounds (list): a list of bounding index tuples for each potentially non-maximal C-contiguous block of data selected. Returns: maximal_index_bounds (list): a list of bounds equivalent to ...
ad970124a9147b10b1f138d4268435b39f1469eb
609,198
def to_dict(dict_like): """ Converts an object that inherits from dictionary to a plain dictionary. This is useful for CommentedMap objects. :param dict_like: The dictionary like object :returns: A plain dictionary """ d = dict(dict_like) for key in d: if isinstance(d[key]...
96d0e862413a10cd75509e6aef2a499883e81a16
609,199
def lines_extractor(widget, data): """Extract textarea value as list of lines. """ extracted = data.extracted if not extracted: return list() return extracted.split('\n')
ed6fe4fdf5e74722b8986de54087492ff55b3ffe
609,204
from uuid import uuid1 def unique_filename(prefix): """ Provides a filename with a unique id appended Args: prefix (str): the prefix of the file Returns: str: filename """ unique_id = str(uuid1().hex) return prefix + unique_id
c1c948b9fa891daff6751dc57a7baf086119995f
609,206
def _filter_zeros(xs): """Return a list of numbers with 0s removed from the list.""" return list(filter(lambda x: x != 0, xs))
cbee226061a315fb14f73bd7c46f6cd1f19ef2ca
609,207
from typing import List from typing import Any from typing import Tuple import math def analyze_data_type(data_list: List[Any]) -> Tuple[List[Any], bool]: """Look at the data, remove any null-like values, sort, and tell if it's numerical.""" def is_nullish(val: Any) -> bool: if isinstance(val, str): ...
d6d52ea68ad664d6d425d98f15e5984d292bf8af
609,212
import textwrap def normtext(block): """ makes a block of text have no unnecessary indentation, begin with a non-newline, and end with a newline """ return textwrap.dedent(block).strip('\n') + '\n'
15553879360eb869204c0b2f79f16db430e118f7
609,217
def example_function(param="param"): """ Prints hello world and returns param. Good link on how to write these napolean docs: https://sphinxcontrib-napoleon.readthedocs.io/en/latest/ Parameters ---------- param A string to be prtined. Very creative. Returns ------- stri...
fe0c641495fe088304d554dfa99a0772c73a1de3
609,218