content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import csv def parse_csv_dict(filename): """ Parses csv file and returns header columns and data. """ data = [] with open(filename) as csvfile: reader = csv.DictReader(csvfile) for row in reader: data.append(row) return reader.fieldnames, data
8ffc34a6906cf59926ef618076732eb24f0561fa
17,334
def combineRulesWithOperator(listOfRules, operator): """ Takes a list of rules and makes an overall rule that ties them together with the AND or the OR operator Parameters ---------- listOfRules: list A list of string representation of rules operator: str Should be either AND or OR Returns ------- total: str String representation of the rules combined using the given operator """ assert type(listOfRules) == list assert all(map(lambda r: type(r) == str, listOfRules)) assert operator.lower() in ['and', 'or'] if len(listOfRules) == 1: return listOfRules[0] operator = operator.lower() total = listOfRules[0] for i in range(1, len(listOfRules)): total = operator + "(" + total + ", " + listOfRules[i] + ")" return total
7dfc4988f9c56e05318704a7bd6990fc9b00d604
17,335
def make_product(digits, k, start): """ Compute k numbers product from start position. :param digits: :param k: :param start: :return: (product, next_start) """ index = 0 product = 1 while index < k and start + index < len(digits): if digits[start + index]: product *= digits[start + index] index += 1 else: # if 0 found, change start to position after 0 and compute product again start += index + 1 index = 0 product = 1 if index < k: # no k digit product without 0 return 0, start else: # return k digit product starting at start position return product, start
caa4b9da545c7c575291ed2af1ae2579a681930d
17,340
def _get_image_offsets(width, height, segments_x, segments_y): """ Gets offsets for the segments :param width: map width :param height: map height :param segments_x: number of x segments :param segments_y: number of y segments :return: lists of x offsets, lists of y offsets """ offsets_x = [] offsets_y = [] for i in range(segments_x): offsets_x.append((int(width / segments_x * i))) for i in range(segments_y): offsets_y.append((int(height / segments_y * i))) offsets_x.append(width) offsets_y.append(height) return offsets_x, offsets_y
97fbde70318ca592643f99af332cfa1862da00f0
17,346
import torch def compute_N_L(lambda_L, Gram_L, G_out): """Compute N_L using KRR Parameters ---------- lambda_L: float Last layer regularization parameter Gram_L: torch.Tensor of shape (n_samples, n_samples) Last layer Gram matrix G_out: torch.Tensor of shape (n_samples, n_samples) Output Gram matrix Returns ------- N_L: torch.Tensor of shape (n_samples, n_samples), default None Optimal last layer coefficients' dot products computed thanks to KRR """ n = Gram_L.shape[0] M_L = Gram_L + n * lambda_L * torch.eye(n, dtype=torch.float64) M_L_1 = torch.inverse(M_L) N_L = torch.mm(M_L_1, torch.mm(G_out, M_L_1)) # Should be independent from previous layers: .data return N_L.data
53ab4781898ae262e491d5a6ca577bcdd7fa8144
17,347
def Mceta(m1, m2): """Compute chirp mass and symmetric mass ratio from component masses""" Mc = (m1*m2)**(3./5.)*(m1+m2)**(-1./5.) eta = m1*m2/(m1+m2)/(m1+m2) return Mc, eta
fa55e1cfc669f3e180aed1a3cc838ed82147ddbc
17,349
def split_sents(notes, nlp): """ Split the text in pd.Series into sentences. Parameters ---------- notes: pd.Series series with text nlp: spacy language model Returns ------- notes: pd.DataFrame df with the sentences; a column with the original note index is added """ print(f'Splitting the text in "{notes.name}" to sentences. This might take a while.', flush=True) to_sentence = lambda txt: [str(sent) for sent in nlp(txt).sents] sents = notes.apply(to_sentence).explode().rename('text').reset_index().rename(columns={'index': 'note_index'}) print(f'Done! Number of sentences: {sents.shape[0]}') return sents
0aae3af46a2a0c29fff9c3bb5725b0ddcb8ed796
17,354
def _is_header_line(line: str) -> bool: """ Determine if the specified line is a globals.csv header line Parameters ---------- line : str The line to evaluate Returns ------- is_header_line : bool If True, `line` is a header line """ return "kT" in line
06f8ff10deeac60e92b2fd92059873d5abafa367
17,358
from typing import Set def parse_modes(modes: Set[str]) -> Set[str]: """A function to determine which modes to run on based on a set of modes potentially containing blacklist values. ```python m = fe.util.parse_modes({"train"}) # {"train"} m = fe.util.parse_modes({"!train"}) # {"eval", "test", "infer"} m = fe.util.parse_modes({"train", "eval"}) # {"train", "eval"} m = fe.util.parse_modes({"!train", "!infer"}) # {"eval", "test"} ``` Args: modes: The desired modes to run on (possibly containing blacklisted modes). Returns: The modes to run on (converted to a whitelist). Raises: AssertionError: If invalid modes are detected, or if blacklisted modes and whitelisted modes are mixed. """ valid_fields = {"train", "eval", "test", "infer", "!train", "!eval", "!test", "!infer"} assert modes.issubset(valid_fields), "Invalid modes argument {}".format(modes - valid_fields) negation = set([mode.startswith("!") for mode in modes]) assert len(negation) < 2, "cannot mix !mode with mode, found {}".format(modes) if True in negation: new_modes = {"train", "eval", "test", "infer"} for mode in modes: new_modes.discard(mode.strip("!")) modes = new_modes return modes
312467ea55d3d254f7b6cd601a2e8b999539508f
17,359
def _patch_center(patch, orient='v'): """ Get coordinate of bar center Parameters ---------- patch : matplotlib patch orient : 'v' | 'h' Returns ------- center : float """ if orient not in 'v h'.split(): raise Exception("Orientation must be 'v' or 'h'") if orient == 'v': x = patch.get_x() width = patch.get_width() xpos = x + width / 2 return xpos else: y = patch.get_y() height = patch.get_height() ypos = y + height / 2 return ypos
235da0e3fdca40d62dd0313d8e8a500a7c533b8d
17,361
import hashlib def get_sha256_of_string(the_string): """Returns SHA-256 hash for given string.""" new_hash = hashlib.new("sha256") new_hash.update(bytes(the_string, "utf-8")) return new_hash
1657bd433e62c9342d5474fae472fc9dff649575
17,364
import re def decamelize(s): """Decamelize the string ``s``. For example, ``MyBaseClass`` will be converted to ``my_base_class``. """ if not isinstance(s, str): raise TypeError('decamelize() requires a string argument') if not s: return '' return re.sub(r'([a-z])([A-Z])', r'\1_\2', s).lower()
fc30254742bcc79047dd6803d0d7b87c951a9f10
17,365
def match_with_batchsize(lim, batchsize): """ Function used by modify_datasets below to match return the integer closest to lim which is multiple of batchsize, i.e., lim%batchsize=0. """ if lim % batchsize == 0: return lim else: return lim - lim % batchsize
c37226946c51144df6192adeaf265326ee3bb701
17,376
def superset_data_db_alias() -> str: """The alias of the database that Superset reads data from""" return 'superset-data-read'
c6bab8ae745f915c442145bbc7c4bcffa4141310
17,380
def _fully_qualified_typename(cls): """Returns a 'package...module.ClassName' string for the supplied class.""" return '{}.{}'.format(cls.__module__, cls.__name__)
f290a5fb3394f151476f5cf3b4785c5935e942b1
17,387
def user_prompt(prompt_string, default=None, inlist=None): """ Takes a prompt string, and asks user for answer sets a default value if there is one keeps prompting if the value isn't in inlist splits a string list with commas into a list """ prompt_string = '%s [%s]: ' % ( prompt_string, default) if default else prompt_string output = input(prompt_string) output = default if output == '' else output if inlist: assert isinstance(inlist, list) while output not in inlist: output = input(prompt_string) output = [x.strip() for x in output.split(',')] if ( isinstance(output, str) and ',' in output) else output return output
5879c8cd7853426d9c94b763292f6b04e9f26e78
17,388
import re def remove_links(text): """ Method used to remove the occurrences of links from the text Parameters: ----------------- text (string): Text to clean Returns: ----------------- text (string): Text after removing links. """ # Removing all the occurrences of links that starts with https remove_https = re.sub(r"http\S+", "", text) # Remove all the occurrences of text that ends with .com # and start with http text = re.sub(r"\ [A-Za-z]*\.com", " ", remove_https) return text
0bf0208459f0c93e7bac2848476959791369b5c0
17,395
def rgb_to_hsl(rgb_array): """! @brief Convert rgb array [r, g, b] to hsl array [h, s, l]. @details RGB where r, g, b are in the set [0, 255]. HSL where h in the set [0, 359] and s, l in the set [0.0, 100.0]. Formula adapted from https://www.rapidtables.com/convert/color/rgb-to-hsl.html @param rgb_array RGB array [r, g, b]. @return HSL array [h, s, l]. """ r, g, b = rgb_array r, g, b = (r/255), (g/255), (b/255) min_color, max_color = min(r, g, b), max(r, g, b) h, s, l = None, None, ((max_color+min_color) / 2) if min_color == max_color: h = s = 0 # Color is grayscale/achromatic. else: color_range = max_color - min_color s = color_range / (1 - abs(2 * l - 1)) if max_color == r: h = ((g - b) / color_range) % 6 elif max_color == g: h = (b - r) / color_range + 2 else: h = (r - g) / color_range + 4 h = round(h*60) # Degrees. s = round(s*100, 1) # Percentage [0% - 100%] whole numbers. l = round(l*100, 1) # Percentage [0% - 100%] whole numbers. return [h, s, l]
2c197b7966f5248566fdff41a62bf3f89c222c48
17,396
def logstash_processor(_, __, event_dict): """ Adds @version field for Logstash. Puts event in a 'message' field. Serializes timestamps in ISO format. """ if 'message' in event_dict and 'full_message' not in event_dict: event_dict['full_message'] = event_dict['message'] event_dict['message'] = event_dict.pop('event', '') for key, value in event_dict.items(): if hasattr(value, 'isoformat') and callable(value.isoformat): event_dict[key] = value.isoformat() + 'Z' event_dict['@version'] = 1 event_dict['_type'] = event_dict['type'] = 'feedhq' return event_dict
f395bc7e4a7c09cdbe9ef29c3dbfdd45a448c21e
17,400
def normalise_series(series): """Normalise a Pandas data series. i.e. subtract the mean and divide by the standard deviation """ ave = series.mean() stdev = series.std() return (series - ave) / stdev
97d53c0697a56e5ab559d2564c5d7386125ed254
17,402
def is_empty_placeholder(page, slot): """A template filter to determine if a placeholder is empty. This is useful when we don't want to include any wrapper markup in our template unless the placeholder unless it actually contains plugins. """ placeholder = page.placeholders.get(slot=slot) return not placeholder.cmsplugin_set.exists()
032f6e1d038a10e0f6c5459648dcabaf7e4c0259
17,404
def anti_join(df1, df2, **kwargs): """ Anti-joins two dataframes. :param df1: dataframe :param df2: dataframe :param kwargs: keyword arguments as passed to pd.DataFrame.merge (except for 'how'). Specifically, need join keys. :return: dataframe """ return df1.merge(df2, how='left', indicator=True, **kwargs) \ .query('_merge != "both"') \ .drop('_merge', axis=1)
6fdc7481da6728b51549c072879204a6c3d2bcd6
17,410
import math def get_n(k, e, n_max): """ TS 38.212 section 5.3.1 """ cl2e = math.ceil(math.log2(e)) if (e <= (9/8) * 2**(cl2e - 1)) and (k / e < 9 / 16): n1 = cl2e - 1 else: n1 = cl2e r_min = 1 / 8 n2 = math.ceil(math.log2(k / r_min)) n_min = 5 n = max(min(n1, n2, n_max), n_min) return 2**n
4129821ac4c89c47d8c5b4391a77da83cfee2505
17,414
def architecture_is_64bit(arch): """ Check if the architecture specified in *arch* is 64-bit. :param str arch: The value to check. :rtype: bool """ return bool(arch.lower() in ('amd64', 'x86_64'))
4303a53c3d1c8c1e844593aed3203dbedb448d61
17,415
import re def match(text, pattern, limit = -1): """ Matches all or first "limit" number of occurrences of the specified pattern in the provided text :param text: A String of characters. This is the text in which we want to find the pattern. :param pattern: The pattern to look for. Expected to be a regular expression. :param limit: The number of occurrences of the pattern to be returned. If specified, the method returns the first "limit" number of occurrences of the pattern in the text(or all occurrences, whichever is lesser) :return: A list of matching strings and their starting and ending index values in the format (matching_text, start_index, end_index) """ matcher = re.compile(pattern) matches = [] iter = 0 for m in matcher.finditer(text): entry = (m.group(), m.start(), m.end()) matches.append(entry) iter += 1 if limit != -1 and iter == limit: break return matches
656c49ebd197e538acd1c57eb4bc1daf98e5639a
17,416
def _getVersionTuple(v): """Convert version string into a version tuple for easier comparison. """ return tuple(map(int, (v.split("."))))
57d6c1edbfb2ec66bfcc875fe511357266ffc816
17,421
def to_ssml(text): """Adds SSML headers to string. """ return '<speak>'+ text + '</speak>'
0f2fda09507e09c5fdf64d5df2e50630b26629ec
17,424
def remove_headers(markdown): """Remove MAINTAINER and AUTHOR headers from md files.""" for header in ['# AUTHOR', '# MAINTAINER']: if header in markdown: markdown = markdown.replace(header, '') return markdown
5e25c86c72819e42d09459d77e57fa3267748797
17,425
import time import logging def timed_func(process_name): """ Adds printed time output for a function Will print out the time the function took as well as label this output with process_name :param process_name: human name of the process being timed """ def decorator(f): def wrapper(*args, **kwargs): start = time.time() ret = f(*args, **kwargs) logging.getLogger("").info("Elapsed time for {}: {}".format(process_name, time.time()-start)) return ret return wrapper return decorator
e07c9b9a72df8b06308de0812d07428cf18af325
17,426
def is_start_byte(b: int) -> bool: """Check if b is a start character byte in utf8 See https://en.wikipedia.org/wiki/UTF-8 for encoding details Args: b (int): a utf8 byte Returns: bool: whether or not b is a valid starting byte """ # a non-start char has encoding 10xxxxxx return (b >> 6) != 2
8d27198671436c4e9accd80198dfe934c43f679b
17,427
def get_s3item_md5(item): """ A remote item's md5 may or may not be available, depending on whether or not it was been downloaded. If a download hasn't occurred, the checksum can be fetched using the files HTTP ETag. """ if item.md5 is not None: return item.md5 else: # Remove ETAG with any quotes removed: return item.etag.replace('"','').replace("'","")
121c2f3b5d2159e23f37a0770b54e818a7d712bd
17,429
from typing import List def list_params(pop: list, gen: int, lamarck: bool, multicore: bool, **extra_params: dict) -> List: """ Internal function to list execution parameters. For advanced users only. Parameters ---------- pop : list List of individuals. gen : int Number of generations. lamarck : bool If Lamarckian Evolution is used. multicore : bool If parallelism is used. **extra_params : dict Extra parameters. For details, please check: https://github.com/PonyGE/PonyGE2/wiki/Evolutionary-Parameters. Returns ------- param_list : List List of parameters. """ param_list = [] if 'population_size' not in extra_params.keys(): param_list.append('--population_size={0}'.format(str(pop))) if 'generations' not in extra_params.keys(): param_list.append('--generations={0}'.format(str(gen))) if multicore and 'multicore' not in extra_params.keys(): param_list.append("--multicore") if lamarck and 'lamarck' not in extra_params.keys(): param_list.append("--lamarck") for (key, val) in extra_params.items(): if val == "True": param_list.append("--"+key) elif val=="False" or val=="": continue else: param_list.append("--{0}={1}".format(key, val)) return param_list
d08629029f24a85df1adaeeb3db865c2b4a9507f
17,430
import re def isdatauri(value): """ Return whether or not given value is base64 encoded data URI such as an image. If the value is base64 encoded data URI, this function returns ``True``, otherwise ``False``. Examples:: >>> isdatauri('data:text/plain;base64,Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==') True >>> isdatauri('dataxbase64data:HelloWorld') False :param value: string to validate base64 encoded data URI """ data_uri = re.compile(r"\s*data:([a-zA-Z]+/[a-zA-Z0-9\-+]+(;[a-zA-Z\-]+=[a-zA-Z0-9\-]+)?)?(;base64)?,[a-zA-Z0-9!$&',()*+,;=\-._~:@/?%\s]*\s*$") return bool(data_uri.match(value))
43a50554c17b1fd180a9234f2a4631689f14c823
17,431
def list_all_items_inside(_list, *items): """ is ALL of these items in a list? """ return all([x in _list for x in items])
5f7f2b93d966a7e7fffeede3924a7c86309ef90f
17,433
def outer(x, y): """Compute the outer product of two one-dimensional lists and return a two-dimensional list with the shape (length of `x`, length of `y`). Args: x (list): First list, treated as a column vector. 1 dimensional. y (list): Second list, treated as a row vector. 1 dimensional. Returns: list: Outer product between x and y. """ return [[x_i * y_i for y_i in y] for x_i in x]
24f912d4a3152be96d8656f5a387fa526320fd19
17,435
def _get_step_inout(step): """Retrieve set of inputs and outputs connecting steps. """ inputs = [] outputs = [] assert step.inputs_record_schema["type"] == "record" for inp in step.inputs_record_schema["fields"]: source = inp["source"].split("#")[-1].replace("/", ".") # Check if we're unpacking from a record, and unpack from our object if "valueFrom" in inp: attr_access = "['%s']" % inp["name"] if inp["valueFrom"].find(attr_access) > 0: source += ".%s" % inp["name"] inputs.append({"id": inp["name"], "value": source}) assert step.outputs_record_schema["type"] == "record" for outp in step.outputs_record_schema["fields"]: outputs.append({"id": outp["name"]}) return inputs, outputs
d2cc2002792b83d01bcdb7566332c8f37c0aae99
17,436
def get_intersect_list(lst1, lst2): """ Find the intersection of two lists :param lst1: List One :param lst2: List Two :return: A list of intersect elements in the two lists """ lst3 = [value for value in lst1 if value in lst2] return lst3
c7895c948b3a5132bd769e9320e40139c8aac3ad
17,437
def get_instrument_survey_automated_invite(proj, id): """Given an instrument id return the automated invite definition if defined""" xpath = r"./Study/GlobalVariables/redcap:SurveysSchedulerGroup/redcap:SurveysScheduler[@survey_id='%s']" % id return proj.find(xpath, proj.nsmap)
cf458584f6fa6ab46c42bcdb11c5743639607030
17,449
def search_bt(t, d, is_find_only=True): """ Input t: a node of a binary tree d: target data to be found in the tree is_find_only: True/False, specifying type of output Output the node that contans d or None if is_find_only is True, otherwise the node that should be the parent node of d """ if t is None: return if d < t.data: next = t.left else: next = t.right if t.data == d: if is_find_only: return t else: return if not is_find_only and next is None: return t return search_bt(next, d, is_find_only)
4ac48982d17dc2d79ce86004a22167f314b8f99b
17,450
def rgb_to_hex(r, g=0, b=0, a=0, alpha=False): """ Returns the hexadecimal string of a color :param r: red channel :param g: green channel :param b: blue channel :param a: alpha channel :param alpha: if True, alpha will be used :return: color in a string format such as #abcdef """ if type(r) is not list: color = [r, g, b, a] else: color = r hex = "#" for channel in color[:(4 if alpha else 3)]: temp = channel if type(channel) is int else int(round(channel * 255)) hex += f'{temp:02x}' return hex
90e5854f06948bba35a4ae40a6bb77eaef5a1120
17,457
def get_supervisors(employee): """ Given an employee object, return a list of supervisors. the first element of list will be the intial employee. """ if employee.supervisor: return [employee] + get_supervisors(employee.supervisor) else: return [employee]
8b4fe897290834930096654dacdad2f480d11276
17,459
def mjd2jd(mjd): """ Converts Modified Julian Date to Julian Date. Definition of Modified Julian Date (MJD): MJD = JD - 2400000.5 Parameters ---------- mjd : float The Modified Julian Date Returns ------- jd : float :math:`$mjd + 2400000.5 = jd$`, the corresponding ordinary Julian Date """ return mjd + float(2400000.5)
e9250a61e1c3374f4989105ff24fd9efc825d7a1
17,462
def is_superincreasing(seq): """Return whether a given sequence is superincreasing.""" ct = 0 # Total so far for n in seq: if n <= ct: return False ct += n return True
836be03cb7dbb215baaa9a1ba5fd83c39de843d7
17,467
def bawl2(text): """ Return text in the following format. t e x t . e e x x t t . . """ return ' '.join(text) + ''.join('\n' + char + ' '*(2*idx + 1) + char for idx, char in enumerate(text[1:]))
887006a1cb18970ef9889b1b8f1d61ca4aaa69ed
17,472
from typing import List def check_interval_coverage(intvl_upper_limit: int, sub_intvl_positions: List[int], range_length: int = 1) -> bool: """ Method that checks if given sub-intervals are correctly situated to cover all the original segment. :param intvl_upper_limit: upper bound of the interval :param sub_intvl_positions: middle point positions of the sub-intervals :param range_length: range of the sub-interval from the middle point :return: True is the solution is valid, false otherwise """ if intvl_upper_limit == 0: raise ValueError('The upper limit of the interval has to be bigger than 0') covered = 0 for position in sub_intvl_positions: lower_bound = position - range_length upper_bound = position + range_length if lower_bound <= covered < upper_bound: covered = upper_bound if covered >= intvl_upper_limit: return True else: return False
cfaa5d60d6caf59edade474946e2b5b0a7b825f1
17,476
def python_3000_backticks(logical_line): """ Backticks are removed in Python 3000. Use repr() instead. """ pos = logical_line.find('`') if pos > -1: return pos, "W604 backticks are deprecated, use 'repr()'"
2c25077b71bc6b10dca0fb168c711ecdcffeab14
17,482
def ticklabel_format(value): """ Pick formatter for ytick labels. If possible, just print out the value with the same precision as the branch value. If that doesn't fit, switch to scientific format. """ bvs = str(value) if len(bvs) < 7: fp = len(bvs) - (bvs.index(".") + 1) if "." in bvs else 0 return f"%.{fp}f" else: return "%.1e"
7de96c52c527a5295d7ca6e832313386fd80564c
17,483
def transfer_function_Rec1886_to_linear(v): """ The Rec.1886 transfer function. Parameters ---------- v : float The normalized value to pass through the function. Returns ------- float A converted value. """ g = 2.4 Lw = 1 Lb = 0 # Ignoring legal to full scaling for now. # v = (1023.0*v - 64.0)/876.0 t = pow(Lw, 1.0 / g) - pow(Lb, 1.0 / g) a = pow(t, g) b = pow(Lb, 1.0 / g) / t return a * pow(max((v + b), 0.0), g)
7a2a2a2348d701e7fd7dd90c5d016dbf8a2e0c56
17,484
def gen_apsubset(AP, intrep): """Generate set of atomic propositions corresponding to integer >>> gen_apsubset(AP=("p", "q"), intrep=2) set(['q']) """ return set([AP[i] for i in range(len(AP)) if ((intrep >> i) & 1) != 0])
ab219b40c0eda5a0eef4f657f8b06da0f5d782d8
17,485
def does_classes_contain_private_method(classes, method): """ Check if at least one of provided classes contains a method. If one of the classes contains the method and this method has private access level, return true and class that contains the method. """ for class_ in classes: if hasattr(class_, method.__name__): if getattr(class_, method.__name__).__name__ in 'private_wrapper': return True, class_ return False, None
544bd9c5c3f03352ab8674b2665eb583328ac437
17,486
import re def parse_fatal_stacktrace(text): """Get useful information from a fatal faulthandler stacktrace. Args: text: The text to parse. Return: A tuple with the first element being the error type, and the second element being the first stacktrace frame. """ lines = [ r'(?P<type>Fatal Python error|Windows fatal exception): (?P<msg>.*)', r' *', r'(Current )?[Tt]hread [^ ]* \(most recent call first\): *', r' File ".*", line \d+ in (?P<func>.*)', ] m = re.search('\n'.join(lines), text) if m is None: # We got some invalid text. return ('', '') else: msg = m.group('msg') typ = m.group('type') func = m.group('func') if typ == 'Windows fatal exception': msg = 'Windows ' + msg return msg, func
20d26d3e0d69b5fd3bba1fbf1dbe6877b58b125a
17,489
from typing import Dict def dict_sort(d: dict, key=lambda item: item[1]) -> Dict: """sort a dictionary items""" return {k: v for k, v in sorted(d.items(), key=key)}
3686867a4b302fc9d9a5014b3cdadccbc8175d39
17,490
import re def extract_variables(sFormula): """ Extract variables in expression, e.g. {a}*x + {b} -> ['a','b'] The variables are replaced with p[0],..,p[n] in order of appearance """ regex = r"\{(.*?)\}" matches = re.finditer(regex, sFormula, re.DOTALL) formula_eval=sFormula variables=[] ivar=0 for i, match in enumerate(matches): for groupNum in range(0, len(match.groups())): var = match.group(1) if var not in variables: variables.append(var) formula_eval = formula_eval.replace('{'+match.group(1)+'}','p[{:d}]'.format(ivar)) ivar+=1 return variables, formula_eval
7ae5b836504876c815b15c87bad774334fd4dd80
17,493
def select_files(files, search): """Select files based on a search term of interest. Parameters ---------- files : list of str File list. search : str String to use to keep files. Returns ------- list of str File list with selected files kept. """ return [file for file in files if search in file]
91fc2e08645c349b14425b5f6e86c38906156601
17,496
def file_writer(filename): """ Open a file for writing. Args: filename: (string) the name of the path/file to open for writing. Returns: file object. Raises: IOError: If filename is not writeable. """ try: fileobj = open(filename, 'w') except IOError as e: raise IOError("{0}: {1}".format(e.strerror, filename)) return fileobj
c04e684b5cb35c8442d4a75762d63c0974745b9c
17,501
def doAddition(a,b): """ The function doAddition accecpts two integer numbers and returns the sum of it. """ return a+b
c4afcdab6c5e4570eff848b2f6a0aa07713f0dda
17,507
def get_binsize(bins): """ Infer bin size from a bin DataFrame. Assumes that the last bin of each contig is allowed to differ in size from the rest. Returns ------- int or None if bins are non-uniform """ sizes = set() for chrom, group in bins.groupby("chrom"): sizes.update((group["end"] - group["start"]).iloc[:-1].unique()) if len(sizes) > 1: return None if len(sizes) == 1: return next(iter(sizes)) else: return None
cd8a7127083a24bc24f79be4aa8225884efa643a
17,508
def _replace_revision(raw_header: bytes, revision: bytes) -> bytes: """Replace the 'revision' field in a raw header.""" return raw_header[:8] + revision + raw_header[8 + 4 :]
a9c251528ae7e374c815db5b83ce4fbd164a7afd
17,511
def keyword_list(value): """Ensure keywords are treated as lists""" if isinstance(value, list): # list already return value else: # csv string return value.split(',')
9ab8f75fed9d85164d2b450da2c2fcdfc6e070c1
17,512
from bs4 import BeautifulSoup def standardize_html(html): """Clean and format html for consistency.""" cleaned = html.replace(". ", ". ").replace(" ", "").replace("\n", "") parsed = BeautifulSoup(cleaned, "lxml").prettify().strip() return parsed
fd1d60f97ae7de313acb43fb327dee6864324109
17,514
import hashlib def get_model_hash(rvt_model_path): """ Creates a hash of provided rvt model file :param rvt_model_path: :return: hash string """ BLOCKSIZE = 65536 hasher = hashlib.sha256() with open(rvt_model_path, "rb") as rvt: buf = rvt.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = rvt.read(BLOCKSIZE) return hasher.hexdigest()
1ee0f2935112eda8729df84e41b1d0fee2d224a1
17,515
from typing import Tuple from typing import List def _check_dissipator_lists(gammas, lindblad_operators) -> Tuple[List, List]: """Check gammas and lindblad operators are lists of equal length.""" if gammas is None: gammas = [] if lindblad_operators is None: lindblad_operators = [] assert isinstance(gammas, list), \ "Argument `gammas` must be a list)]." assert isinstance(lindblad_operators, list), \ "Argument `lindblad_operators` must be a list." assert len(gammas) == len(lindblad_operators), \ "Lists `gammas` and `lindblad_operators` must have the same length." return gammas, lindblad_operators
4071be282667b6c688cffdf28cd3a5e4ce8f6dbf
17,517
def steps(current, target, max_steps): """ Steps between two values. :param current: Current value (0.0-1.0). :param target: Target value (0.0-1.0). :param max_steps: Maximum number of steps. """ if current < 0 or current > 1.0: raise ValueError("current value %s is out of bounds (0.0-1.0)", current) if target < 0 or target > 1.0: raise ValueError("target value %s is out of bounds (0.0-1.0)", target) return int(abs((current * max_steps) - (target * max_steps)))
0287efec583bfb8c37907a34ca5adf7c0aa61886
17,519
def findUniqueNumber(n: int): """ Given a set of numbers present twice except the unique number, it finds the unique number among the set of numbers. :param n : Size of the input :return : The unique integer """ ans = 0 vec = [int(x) for x in input("Enter set of numbers separated by space\n").split(' ')] for i in range(n): ans = ans ^ vec[i] return ans
bf9a64bf0474a354dec8f0b891a6f0134aa53c73
17,520
from typing import Any def expand_to_tuple(item: Any) -> tuple[Any, ...]: """Wraps anything but tuple into a tuple. Args: item: any sequence or a single item. Returns: a tuple. >>> from redex import util >>> util.expand_to_tuple((1,)) (1,) >>> util.expand_to_tuple((1,2)) (1, 2) """ return item if isinstance(item, tuple) else (item,)
7f7f072759ec4b5e493d5f55678f853eb99fe765
17,524
def add_zeros(x, length=4): """Zero pad x.""" strx = str(x) lenx = len(strx) diff = length - lenx for _ in range(diff): strx = '0' + strx return strx
ed46c2005dec2324229629341309148fecd7c14f
17,529
def get_plural(val_list): """ Get Plural: Helper function to return 's' if a list has more than one (1) element, otherwise returns ''. Returns: str: String of 's' if the length of val_list is greater than 1, otherwise ''. """ return 's' if len(val_list) > 1 else ''
b86387cb2abd3c5176f5dcefbf7bc3e1a49a346c
17,535
def _is_variable_argument(argument_name): """Return True if the argument is a runtime variable, and False otherwise.""" return argument_name.startswith('$')
cf74d6dfd1c0ea1b560bf3766e2fac8af1dbafda
17,537
def vote_smart_candidate_object_filter(one_candidate): """ Filter down the complete dict from Vote Smart to just the fields we use locally :param one_candidate: :return: """ one_candidate_filtered = { 'candidateId': one_candidate.candidateId, 'firstName': one_candidate.firstName, 'nickName': one_candidate.nickName, 'middleName': one_candidate.middleName, 'preferredName': one_candidate.preferredName, 'lastName': one_candidate.lastName, 'suffix': one_candidate.suffix, 'title': one_candidate.title, 'ballotName': one_candidate.ballotName, 'electionParties': one_candidate.electionParties, 'electionStatus': one_candidate.electionStatus, 'electionStage': one_candidate.electionStage, 'electionDistrictId': one_candidate.electionDistrictId, 'electionDistrictName': one_candidate.electionDistrictName, 'electionOffice': one_candidate.electionOffice, 'electionOfficeId': one_candidate.electionOfficeId, 'electionStateId': one_candidate.electionStateId, 'electionOfficeTypeId': one_candidate.electionOfficeTypeId, 'electionYear': one_candidate.electionYear, 'electionSpecial': one_candidate.electionSpecial, 'electionDate': one_candidate.electionDate, 'officeParties': one_candidate.officeParties, 'officeStatus': one_candidate.officeStatus, 'officeDistrictId': one_candidate.officeDistrictId, 'officeDistrictName': one_candidate.officeDistrictName, 'officeStateId': one_candidate.officeStateId, 'officeId': one_candidate.officeId, 'officeName': one_candidate.officeName, 'officeTypeId': one_candidate.officeTypeId, 'runningMateId': one_candidate.runningMateId, 'runningMateName': one_candidate.runningMateName, } return one_candidate_filtered
56fbbe3c2f128364d800d05fe6690eedb9f5f748
17,539
def get_capability(capabilities, capability_name): """Search a set of capabilities for a specific one.""" for capability in capabilities: if capability["interface"] == capability_name: return capability return None
4d83ec53a06b75313a47ea3ba618161ecd5f3782
17,543
import torch def mpjae(predicted, target): """ Mean per-joint angle error (3d bone vector angle error between gt and predicted one) """ assert predicted.shape == target.shape # [B,T, K] joint_error = torch.mean(torch.abs(predicted - target).cuda(), dim=0) # Calculate each joint angle print('each bone angle error:', joint_error) return torch.mean(joint_error)
07e2cadb9b38c39514558791b3d5c605a19a0dc4
17,545
def get_ciphers(fw_conn, service): """Get Ciphers Args: fw_conn (PanDevice): A panos object for device service (str): A string containing either mgmt or ha for ciphers Returns: results (Element): XML results from firewall """ base_xpath = ("/config/devices/entry[@name='localhost.localdomain']" "/deviceconfig/system/ssh/ciphers/{}".format(service)) results = fw_conn.xapi.get(xpath=base_xpath) return results
2fe9837c884d1257afb48982721c7e273ddf7fc9
17,548
def stdout_to_list(stdout): """Convert stdout (str) to list of stripped strings""" return [x.strip() for x in stdout.split('\n') if x.strip()]
ec641d29201bbfc60a083952daf0b9e696b786dc
17,550
def Cumfreq(symbol, dictionary): """ This Function Takes as inputs a symbol and a dictionary containing all the symbols that exists in our stream and their frequencies and returns the cumulative frequency starting from the very beginning of the Dictionary until that Symbol. Arguments: symbol {[type]} -- [the symbol we want to get the cumulative frequency for] dictionary {[type]} -- [the dictionary that contains the frequency of all symbols] Returns: p int -- [the upper bound ,which is the sum of all frequencies from the beginning of the dictionary till the specified symbol] """ P = 0 for sym in dictionary: P += dictionary[sym] if sym == symbol: break return P
b5dffb0512b4704bd76c49eac4bb3e9714ebbcb1
17,552
def parseCoords(coordList): """ Pass in a list of values from <coordinate> elements Return a list of (longitude, latitude, altitude) tuples forming the road geometry """ def parseCoordGroup(coordGroupStr): """ This looks for <coordinates> that form the road geometry, and then parses them into (longitude, latitude, altitude). Altitude is always 0. If the coordinate string is just the coordinates of a place, then return the empty list """ #print "coordGroupStr:", coordGroupStr coords = coordGroupStr.strip().split(" ") if len(coords) > 3: coords = map(lambda x: x.split(","), coords) coords = map(lambda x: tuple(map(float, x)), coords) coords = map(lambda x: (x[1], x[0]), coords) #print 'returning:', coords return coords else: return [] ret = [] #print "coordList:", coordList for coordGroup in coordList: ret += parseCoordGroup(coordGroup) return ret
7c358973fc4279e03cf8d535ff41de7571f0a7d2
17,554
from datetime import datetime def datetime_from_salesforce(d): """Create a Python datetime from a Salesforce-style ISO8601 string""" return datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f%z")
ca9cbeb5dff44860166a27c771da1cdb8f3d395a
17,560
def listGetShiftedGeometricMean(listofnumbers, shiftby=10.0): """ Return the shifted geometric mean of a list of numbers, where the additional shift defaults to 10.0 and can be set via shiftby """ geommean = 1.0 nitems = 0 for number in listofnumbers: nitems = nitems + 1 nextnumber = number + shiftby geommean = pow(geommean, (nitems - 1) / float(nitems)) * pow(nextnumber, 1 / float(nitems)) return geommean - shiftby
904bb38a199052b086b7a2c695ce675011f65019
17,561
def similarity_hash(hash_digests): # type: (list[bytes]) -> bytes """ Creates a similarity preserving hash from a sequence of equal sized hash digests. :param list hash_digests: A sequence of equaly sized byte-hashes. :returns: Similarity byte-hash :rtype: bytes """ n_bytes = len(hash_digests[0]) n_bits = n_bytes * 8 vector = [0] * n_bits for digest in hash_digests: h = int.from_bytes(digest, "big", signed=False) for i in range(n_bits): vector[i] += h & 1 h >>= 1 minfeatures = len(hash_digests) * 1.0 / 2 shash = 0 for i in range(n_bits): shash |= int(vector[i] >= minfeatures) << i return shash.to_bytes(n_bytes, "big", signed=False)
804619477bdea3f7a79c6473d47e55c5106a586a
17,564
import binascii def mkauth(username: str, password: str, scheme: str = "basic") -> str: """ Craft a basic auth string """ v = binascii.b2a_base64( (username + ":" + password).encode("utf8") ).decode("ascii") return scheme + " " + v
b9dd22c830e8c493ac4239ff6f4800e554d1e439
17,565
def eta_Mc_M(Mc, M): """ Computes the symmetric-mass-ratio from the Chirp Mass and total mass input: Mc, M output: eta """ return (Mc/M)**(5./3.)
535e2ac7cd08d4b0c7df49bbd1c69287012b65ca
17,566
import random def randit(it, rand=None): """ Random object from iterable. Return an occurrence at random from the given iterable, using `rand` if given or else a new `Random` object. """ return it[(rand or random.Random()).randrange(0, len(it))]
fa8c4bb78ae90923cd3149af4714a7e89f85afde
17,582
def calc_focal_length(distance, width, pixels): """ Calculates the focal length based off the input Parameters: distance(int): distance from camera to the object width(int): actual width of the object pixels(int): width in pixels of the object return: focal length of the camera based off the target object rtype: int """ return (distance * pixels) / width
5a8ba34ad7d1c408552ec50015aa3df7e18f555c
17,583
def create_greeting(moment): """Prints customized welcome string based on time Args: moment (timestamp): current time Returns: greeting (string): the final welcome string """ if moment.hour < 12: greeting = 'Good morning' elif moment.hour < 20: greeting = 'Good evening' else: greeting = 'Good night' return greeting
6dfc2d113b27a95c631186ee3688f7054e6cc923
17,584
import re def preprocess_summary(text): """Pre-process an episode summary string by removing repeated whitespaces, bracketed text, and citations.""" text = re.sub('[\(\[].*?[\)\]]', '', text) # remove brackets text = re.sub(' +', ' ', text) # remove multiple whitespaces text = re.sub('\s+\.\s+', '. ', text) # removed whitespaces from before dots # We want to get rid of the part after the first '\n' for summaries with multiple paragraphs text = text.split('\n')[0] # make sure the last sentence ends with '.', '!', or '?', if there is a half finished sentence that is usually a # citation or reference on Wikipedia if not (text.endswith('.') or text.endswith('?') or text.endswith('!')): last_closing = max([text.rfind('.'), text.rfind('?'), text.rfind('!')]) if last_closing > 0: text = text[:last_closing+1] if text.endswith(' .'): text = text[:-2]+'.' return text
ef950787a28487a29106a6a5ef959adbf52c3703
17,588
def create_segmented_sequence(length, seq_initializer): """ Create a segmented test_sequence A segment is a list of lists. `seq_initializer` is used to create `length` individual segments, which allows for the using any of the pre-supplied initializers for a regular genomic test_sequence, or for making your own. `length` denotes how many segments to generate. If it's an integer, then we will create `length` segments. However, if it's a function that draws from a random distribution that returns an int, we will, instead, use that to calculate the number of segments to generate. >>> from leap_ec.binary_rep.initializers import create_binary_sequence >>> segments = create_segmented_sequence(3, create_binary_sequence(3)) >>> assert len(segments) == 3 :param length: How many segments? :type length: int or Callable :param seq_initializer: initializer for creating individual sequences :type seq_initializer: Callable :return: test_sequence of segments :rtype: list """ if callable(length): num_segments = length() else: num_segments = length segments = [seq_initializer() for _ in range(num_segments)] return segments
bfe4296a91b0ea122c20501347cfd68fbc8ff16c
17,589
import re def convert_keys(input_value): """ Convert all of the keys in a dict recursively from CamelCase to snake_case. Also strips leading and trailing whitespace from string values. :param input_value: :return: """ retn = None if isinstance(input_value, list): retn = [] for list_item in input_value: if isinstance(list_item, (dict, list)): retn.append(convert_keys(list_item)) else: if isinstance(list_item, str): retn.append(list_item.strip()) else: retn.append(list_item) elif isinstance(input_value, dict): retn = dict() for k, v in input_value.items(): new_key_s = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", k) new_key = re.sub("([a-z0-9])([A-Z])", r"\1_\2", new_key_s).lower() if isinstance(v, (dict, list)): retn[new_key] = convert_keys(v) else: if isinstance(v, str): retn[new_key] = v.strip() else: retn[new_key] = v return retn
c0727ac011362f2449d2e5ced694752df529dfeb
17,590
def search_colorspaces(config, aces_id): """ Search the config for the supplied ACES ID, return the color space name. """ for cs in config.getColorSpaces(): desc = cs.getDescription() if aces_id in desc: return cs.getName() return None
b47f7b9105db178904ce272ad8b0002412d96f82
17,591
def get_upload_folder_structure(file_name): """ Return the structure in the upload folder used for storing and retrieving uploaded files. Two folder levels are created based on the filename (UUID). The first level consists of the first two characters, the second level consists of the third character of the uuid. Example: ``9cd7b281-2c70-42eb-86ec-e29fc755cc1e.jpg`` is stored to ``9c/d/9cd7b281-2c70-42eb-86ec-e29fc755cc1e.jpg``. Args: file_name (str): The name of the file. Returns: list. A list of the folders or an empty list if there was a problem with the file name. """ try: return [file_name[0:2], file_name[2:3]] except TypeError: return []
3a231d820de6a67d8d9a0af77055092cc24c3a48
17,601
def find_matching_edge(m, i, j): """Return corresponding edge for a given arc. """ if (i,j) in m.edge: return (i,j) else: return (j,i)
4bbc182116c210dd9cdb3ca4719a6bc1be8e882e
17,602
def sanitize_result(data): """Sanitize data object for return to Ansible. When the data object contains types such as docker.types.containers.HostConfig, Ansible will fail when these are returned via exit_json or fail_json. HostConfig is derived from dict, but its constructor requires additional arguments. This function sanitizes data structures by recursively converting everything derived from dict to dict and everything derived from list (and tuple) to a list. """ if isinstance(data, dict): return dict((k, sanitize_result(v)) for k, v in data.items()) elif isinstance(data, (list, tuple)): return [sanitize_result(v) for v in data] else: return data
6058f5ec32fadd2de6869f91747d7968c4437ce9
17,603
def abbrev_key ( key: str, ) -> str: """ Abbreviate the IRI, if any key: string content to abbreviate returns: abbreviated IRI content """ if key.startswith("@"): return key[1:] key = key.split(":")[-1] key = key.split("/")[-1] key = key.split("#")[-1] return key
6cb2058f32d6320f1be118d8831cc074cd0cc56f
17,608
from typing import Tuple def split_platform(platfrm: str) -> Tuple[str, str, str]: """ Split a platform string into its (os, architecture, variant) form. """ parts = platfrm.split("/", maxsplit=2) return ( parts[0], parts[1] if len(parts) > 1 else "", parts[2] if len(parts) > 2 else "", )
75b4594a874c03cc5977472b396ecc94d41206e3
17,612
def basic_ttr(n_terms, n_words): """ Type-token ratio (TTR) computed as t/w, where t is the number of unique terms/vocab, and w is the total number of words. (Chotlos 1944, Templin 1957) """ if n_words == 0: return 0 return n_terms / n_words
3d56fd414d6d462c722a2d29bd15bb7ef8bf7559
17,621
import torch from typing import OrderedDict def load_statedict(model_path): """Loads model state dict. Args: model_path: model path Returns: state dict """ print(f"Loading model from {model_path}.") state_dict = torch.load(model_path, map_location=lambda storage, loc: storage) print("Loaded model.") # Remove distributed naming if model trained in distributed mode model_state_dict = OrderedDict() for k, v in state_dict["model"].items(): if k.startswith("module."): name = k[len("module.") :] model_state_dict[name] = v else: model_state_dict[k] = v return state_dict, model_state_dict
d556db551dca3176ffcfa88af99fc89f36d9b444
17,622
def GetCacheKeyPolicy(client, args, backend_bucket): """Returns the cache key policy. Args: client: The client used by gcloud. args: The arguments passed to the gcloud command. backend_bucket: The backend bucket object. If the backend bucket object contains a cache key policy already, it is used as the base to apply changes based on args. Returns: The cache key policy. """ cache_key_policy = client.messages.BackendBucketCdnPolicyCacheKeyPolicy() if (backend_bucket.cdnPolicy is not None and backend_bucket.cdnPolicy.cacheKeyPolicy is not None): cache_key_policy = backend_bucket.cdnPolicy.cacheKeyPolicy if args.cache_key_include_http_header is not None: cache_key_policy.includeHttpHeaders = args.cache_key_include_http_header if args.cache_key_query_string_whitelist is not None: cache_key_policy.queryStringWhitelist = ( args.cache_key_query_string_whitelist) return cache_key_policy
202d1cce49478051255bd48f0b9e117dd19ed63f
17,624
def multi_powmod(bases, exponents, modulus): """ raise all bases in xs to the respective powers in ys mod n: :math:`\prod_{i=1}^{len(bases)} base_i^{exponent_i} \pmod{modulus}` :param bases: the bases :param exponents: the exponents :param modulus: the modulus :return: the calculated result """ if len(bases) != len(exponents): raise ValueError("xs and ys don't have the same size") result = 1 for base, power in zip(bases, exponents): result = (result * pow(base, power, modulus)) % modulus return result
b8b0bcc32e7938996d20044fcd4e0649273d0ee5
17,626
def ticks(group): """Wrapper function for .add_steps method. """ pheno, steps, sim_id = group pheno.add_steps(steps) return pheno, sim_id
f567d9e14d7421fb196921543bab9587ca040fa4
17,632
def update_output_div(input_value): """Format the input string for displaying""" return 'You\'ve entered "{}"'.format(input_value)
615a671775ed836712978485230403d9a331f366
17,635
def get_xy_coords(storms): """ Takes Polygons of storm masks as paired coordinates and returns seperated x and y coordinates Args: storms: List of polygon storms [x, y] Returns: x: list of x coordinates y: list of y coordinates """ x, y = [], [] [(x.append(list(polygon.exterior.coords.xy[0])), y.append(list(polygon.exterior.coords.xy[1]))) for polygon in storms] return x, y
444ba53cf8ffabe1f9e4bea5a7d8a70d6b41a056
17,636
def reducemap(func, sequence, initial=None, include_zeroth = False): """ A version of reduce that also returns the intermediate values. :param func: A function of the form x_i_plus_1 = f(x_i, params_i) Where: x_i is the value passed through the reduce. params_i is the i'th element of sequence x_i_plus_i is the value that will be passed to the next step :param sequence: A list of parameters to feed at each step of the reduce. :param initial: Optionally, an initial value (else the first element of the sequence will be taken as the initial) :param include_zeroth: Include the initial value in the returned list. :return: A list of length: len(sequence), (or len(sequence)+1 if include_zeroth is True) containing the computed result of each iteration. """ if initial is None: val = sequence[0] sequence = sequence[1:] else: val = initial results = [val] if include_zeroth else [] for s in sequence: val = func(val, s) results.append(val) return results
7c3fbd5e60777ecaf82ff2d7745aafab879abd10
17,637