content
stringlengths
42
6.51k
def _is_erhua(pinyin): """ Decide whether pinyin (without tone number) is retroflex (Erhua) """ if len(pinyin) <= 1 or pinyin[:-1] == 'er': return False elif pinyin[-2] == 'r': return True else: return False
def _build_summary(event_data): """ Returns a summary string for the build data found in the event data block. """ summary = "for repository %s [%s]" % (event_data["repository"], event_data["build_id"][0:7]) return summary
def shape_to_HWCK(shape): """ Convert from KCHW|KCW => HWCK """ if len(shape) == 4: # KCHW => HWCK return [shape[2], shape[3], shape[1], shape[0]] if len(shape) == 3: # KCW => 1WCK return [1, shape[2], shape[1], shape[0]] return shape
def sum_readings(readings): """Sum the number of non-zero readings.""" tot = 0 for i in readings: tot += i return tot
def is_retryable_code(response_code: int) -> bool: """ Determine if response is retryable """ return bool(response_code in ( 206, # Retriable 408, # Timeout 429, # Throttle, too Many Requests 439, # Quota, too Many Requests over extended time 500, # Internal ...
def GetJobForLine(depotPaths, line): """ Interprets a line of a diff (patch format) looking for affected files. If a file header statement has a perforce path matching one of the paths relevant to a Jenkins job, returns that job. @param depotPaths Dict mapping perforce paths to a jenkins job @p...
def _build_mlflow_run_cmd( uri, entry_point, storage_dir, use_conda, run_id, parameters): """ Build and return an array containing an ``mlflow run`` command that can be invoked to locally run the project at the specified URI. """ mlflow_run_arr = ["mlflow", "run", uri, "-e", entry_point, "--...
def fn_Z_C_1(omega,C_1): """Readout capacitor impedance as a function of angular frequency omega and capacitance C_1.""" return 1/(1j * omega * C_1)
def check_coupon(coupon): """ checks if a given coupon content is a valid coupon :param coupon: coupon content :return: True if coupon content is valid (not a 404 page and not a blank page) """ return len(coupon) != 52286 and len(coupon) != 1008
def get_base(x): """Returns b | b ** i == x[i], or None""" x = tuple(x) if len(x) >= 2 and x[0] == 1: base = x[1] for i, xi in enumerate(x): if base ** i != xi: return return base
def updateInPlace(a, b): """Return updated object. Simple function for updating a value in place. Keyword arguments: a -- object to update b -- object to merge in """ a.update(b) return a
def make_code_inline(text: str) -> str: """ Returns the text surrounded by ` """ return "`" + text + "`"
def isabs(path: str): """Check if path is an absolute pathname.""" return path.find("/") == 0
def check_value(val): """ This function helps to avoid empty calories values. In case one is found we assumed 0 calories """ try: return int(val) except: return 0
def is_list(text: str) -> bool: """ Does the given type represent a list? """ return text[-1] == "]" or text[:4] == "Vec<"
def is_string(obj): """ Checks if an object is a string. :param obj: Object to test. :return: True if string, false otherwise. :rtype: bool """ return isinstance(obj, str)
def ipvalid(ipstring): """ checks string for validity as IP address input: single string output: - list of intergers if valid - UserWarning if invalid >>> ipvalid("10.0.0.0"); Analysing ip address ip address is valid [10, 0, 0, 0] """ iplist = ipstring.split("."...
def trimboth(l, proportiontocut): """ Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., con...
def power_mod(val, power, m_value): """ Calculate power mod the efficent way """ if power <= 100: return (val ** power) % m_value if power % 2 == 0: return (power_mod(val, power // 2, m_value) ** 2) % m_value return (power_mod(val, power // 2, m_value) * power_mod(val, power ...
def get_dict_max(d): """ Helper function that calculates the maximum value in a dictionary. Parameters: ----------- d: dict of float The dictonary of float to be checked for maximum value Returns: -------- The key corresponding to the maximum value and th...
def floor_log2(number: int) -> int: """ Returns infimum of powers-of-two which are not greater than the number, equivalent of ``floor(log2(number))``. >>> floor_log2(1) 0 >>> floor_log2(2) 1 >>> floor_log2(3) 1 >>> floor_log2(4) 2 """ return number.bit_length() - 1
def string2index(string): """ Convert a string to int so that it can be used as index in an array Parameter --------- string: string string to be converted Return ------ index: int index corresponding to the string """ if string == 'BENIGN': index = 0 ...
def sympy_config(mpl_backend): """Sympy configuration""" if mpl_backend is not None: lines = """ from sympy.interactive import init_session init_session() %matplotlib {0} """.format(mpl_backend) else: lines = """ from sympy.interactive import init_session init_session() """ return lines
def check_pattern(patterns, pattern_dic): """ desc check if the your input on the pattern exist in the pattern file Input patterns, pattern_dic output True or False """ # print(patterns, pattern_dic) for pattern in patterns: try: pattern_dic[pattern] except...
def get_tile_url(x, y, zoom, url='https://maps.wikimedia.org/osm-intl'): """ Creates the tile url based upon the coordinates, the zoom and the base url Url is of the form {url}/{zoom}/{x}/{y}.png :param x: X coordinate :param y: Y coordinate :param zoom: Zoom level :param url: Base url, defa...
def join(sep, xs): """Returns a string made by inserting the separator between each element and concatenating all the elements into a single string""" return str(sep).join(xs)
def _tamper_date(resp): """ Alter instagram response so that it returns some unexpected data """ resp['user']['media']['nodes'][0]['date'] = "not_a_timestamp" return resp
def round_list(input, ndigits=3): """ Takes in a list of numbers and rounds them to a particular number of digits """ return [round(i, ndigits) for i in input]
def or_function(first_member): """Return True if the first member is True. Args: first_member (bool): the first member of the or Returns: bool: False if the first argument is True, else None """ if first_member is True: return True else: return None
def byteToInt(byte): """ byte -> int Determines whether to use ord() or not to get a byte's value. """ if hasattr(byte, 'bit_length'): # This is already an int return byte return ord(byte) if hasattr(byte, 'encode') else byte[0]
def _get_files_glob(filenames, max_differences = 1, show_differences = False): """Tries to generate a glob-string for a set of filenames, containing at most 'max_differences' different columns. If more differences are found, or if the length of filenames vary, None is returned.""" # File lengths must be...
def _to_absolute_minutes(start_time: str) -> int: """Convert hh:mm to absolute minutes.""" split = start_time.split(":") hour = int(split[0]) * 60 minute = int(split[1]) return hour + minute
def num_or_string(v, d=None): """Loads a value from MO into either an int or string value. String is returned if we can't turn it into an int. """ try: return int(str(v))#.replace(',', '') except (ValueError, TypeError): try: _value = float(str(v).replace(',', '.')) if _value == 0: ...
def fabonacci(n): """ Return the n'th number of the fabonacci sequence """ if n == 0: return 0 elif n == 1: return 1 else: return fabonacci(n-1) + fabonacci(n-2)
def mass_kmv(kinetic_energy,velocity): """Usage: Find mass from kinetic energy and velocity""" result = (2*kinetic_energy)/velocity**2 return result
def merge_and_sort(rev_list): """ We are going to look for name matches and add Gross Revenue Total Units Then delete the non-merged entry Move to next index Sorts the list in a descending manner """ counter = 0 for g_line in rev_list: inner_counter = 0 f...
def safe_repr(obj, max_length=None, repr=repr): """ A safe version of repr that is guaranteed to never raise exceptions. """ # noinspection PyBroadException try: data = repr(obj) except Exception as ex: cls_name = type(obj).__name__ ex_name = type(ex).__name__ dat...
def _to_guess(parameters_with_variability, initial_conditions_with_variability): """ Creates a list of variables to infer, based on the values in vary/varyic (0=fixed, 1=optimised). This should contain all variables that are varied as it would be passed to optimisation method. :param param: list of st...
def get_palette(num_classes): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_classes palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] = 0 pale...
def variance(values): """ Returns the variance of a set of variables """ average=sum(values)/len(values) def square(x): return x*x return sum([square(x-average) for x in values])/len(values)
def quadratic_series(z, a, delta1, delta2): """ returns a + (a + delta1 + delta2) * z + (a + 2 * delta1 + 4 * delta2) * z ** 2 + .... """ z1 = 1 - z z1z1 = z1 * z1 return (a * z1z1 + z * (delta1 + delta2 - (delta2 - delta1) * z)) / (z1 * z1z1)
def find_occurences_in_list_of_dicts(list_dict, in_val): """ return number of occurences of value in dict """ n = 0 for item in list_dict: for k in item.keys(): if item[k] == in_val: n += 1 return n
def group_by_key(key_file_pairs): """ [(k1,f1), (k2,f2),..] -> {k1:[f1,..,fn], k2:[f2,..,fm],..}. """ d = {} [d.setdefault(k, []).append(v) for k,v in key_file_pairs] return d
def get_prime_factors(n): """Generate the prime factors of n Args: n (int): the number to factorise """ factors = [] while n % 2 == 0: factors.append(2) n /= 2 m = 3 while n != 1: if n % m == 0: factors.append(m) n /=...
def q_conjugate(q): """Quaternion inverse""" w, x, y, z = q return (w, -x, -y, -z)
def extend(s, var, val): """ Given a dictionary s and a variable and value, this returns a new dict with var:val added to the original dictionary. >>> extend({'a': 'b'}, 'c', 'd') {'a': 'b', 'c': 'd'} """ s2 = {a: s[a] for a in s} s2[var] = val return s2
def get_type_filename(**kws): """Get annotation filename and type, if provided""" if 'gpad' in kws: return 'gpad', kws['gpad'] if 'gaf' in kws: return 'gaf', kws['gaf'] if 'gene2go' in kws: return 'gene2go', kws['gene2go'] if 'id2gos' in kws: return 'id2gos', kws['id2...
def convert_time(ut): """ Convert the sun_time float value to a string. """ if ut < 0: return "XX:XX:XX" hrs = int(ut) mns = int((ut - hrs)*60) secs = int((ut - hrs - mns/60.0)*3600) return "%02u:%02u:%02u" % (hrs, mns, secs)
def construct_path(vertex, reverse_paths): """Returns the shortest path to a vertex using the reverse_path mapping.""" path = [] while vertex is not None: path.append(vertex) vertex = reverse_paths[vertex] return list(reversed(path))
def replace_resource_dict(item, value): """ Handles the replacement of dicts with values -> the needed value for HWC API""" if isinstance(item, list): items = [] for i in item: items.append(replace_resource_dict(i, value)) return items else: if not item: ...
def sol(n): """ b is the break point after which only one ctrl+c and ctrl+v will happen and the remaining will be all ctrl+v therefore it starts at the end from n-3 Now, say if b is the break point then n-b is left on the right side, of which 2 strokes will be consumed in select and copy, and t...
def inv_log(x): """Inverse log calculator""" return ((10**-x)/(1e-6))
def area(base,height): """Return the area of a triangle with dimension base and height """ return base * height/2
def AsSortedTuple(return_value): """Converts any iterable into a sorted Python tuple.""" return tuple(sorted(return_value))
def move_action_dict(moves): """ returns a lookup table with the move as key and the policy index as value :param moves: all possible moves :return: """ lookup_table = {} for i, label in enumerate(moves): lookup_table[label] = i return lookup_table
def js_file_with_configs(fpath, configs): """ Take in a js filepath and a dictionary of configs to be passed in as global vars """ js = '' for k,v in list(configs.items()): if type(v) == str: js += 'var %s = "%s"\n' % (k,v) elif type(v) in [int, float]: js += 'var %s = %s\n' % (k,v) js +...
def _map_keyword_theme_constants_to_infos(client, keyword_theme_constants): """Maps a list of KeywordThemeConstants to KeywordThemeInfos. Args: client: an initialized GoogleAdsClient instance. keyword_theme_constants: a list of KeywordThemeConstants. Returns: a list of KeywordTheme...
def any(sequence, test_func = None): """ Returns 1 if for any member of a sequence, test_func returns a non-zero result. If test_func is not supplied, returns 1 if any member of the sequence is nonzero (e.g., not one of (), [], None, 0). """ for item in sequence: if test_func: ...
def secsToNearestMilli(value): """\ Return value converted to the nearest number of milliseconds :param value: seconds as a floating point number :return: value expressed in integer number of milliseconds (rounded) """ return int(round(value * 1000))
def roman_2_int(n: str) -> int: """ Converts roman number to integer. :param n: roman number :return: integer representation """ conv_table = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} c = [conv_table[x] for x in n] return sum(-x if i < len(n) - 1 and x < c[i + 1...
def reverse_words(input_str: str) -> str: """ Reverses words in a given string >>> reverse_words("I love Python") 'Python love I' >>> reverse_words("I Love Python") 'Python Love I' """ return " ".join(input_str.split()[::-1])
def cast_to_bool(s): """Cast the specified value to a bool. It can be a string. """ if isinstance(s, str): s = s.lower() return s in [True, "t", "true"]
def str_ms2seconds(val): """ Convert time in milliseconds to float seconds :type val: str or int :rtype: float """ return int(val) / 1000.0
def shorten(s, l, index=-1, token="..", token_length=None): """Return given string truncated to given length. >>> shorten('bonjour', 10) 'bonjour' >>> shorten('bonjour tout le monde', 10) 'bonjour ..' >>> shorten('bonjour tout le monde', 10, index=4) 'bonj..onde' >>> shorten('bonjour...
def _ensure_trailing_slash(url: str) -> str: """Return url guaranteed to end in a slash""" return url if url.endswith("/") else f"{url}/"
def write_emperor( pcoa: str, qzv: str, meta: str ) -> str: """ Generates an interactive ordination plot where the user can visually integrate sample metadata. https://docs.qiime2.org/2019.10/plugins/available/emperor/ Parameters ---------- pcoa qzv meta ...
def insert_bn(names): """Insert bn layer after each conv. Args: names (list): The list of layer names. Returns: list: The list of layer names with bn layers. """ names_bn = [] for name in names: names_bn.append(name) if 'conv' in name: position = nam...
def avg(nums, weights=None, default=0): """Calculates the average of a list of numeric types. If the optional parameter weights is given, calculates a weighted average weights should be a list of floats. The length of weights must be the same as the length of nums default is the value returned if nums ...
def nb_open_ends(x, y, dx, dy, nb_consec, position): """Number of empty intersections (0, 1 or 2) next to the `nb_consec` stones (starting from (x,y) and using slope (dx, dy)) in the board position `position`. Parameters ---------- x: int x-coordinate of the start position y: int x-coordinate of ...
def get_boardsize(dic_of_positions): """ Returns the size of the board with an max value of x and y Parameters: dic_of_positions (dictionarys) - Dictionary of players and there piece positions. Returns: xMax (int) - Max value on the x-axis yMax (int) - Max value on the y-axis """ xMax, yMax = 0, 0 for key,v...
def update_mean(value, mean, count): """ Update value of a streaming mean. :param value: New value. :param mean: Mean value. :param count: Number of values averaged. :return: """ return (value - mean) / (count + 1)
def get_expert_annoation_stats(annotations): """take the average of the 3 calculations from each expert annotator""" if annotations: coherence = [] consistency = [] fluency = [] relevance = [] for annotate in annotations: coherence.append(annotate['coherence']...
def fix_natural_language(name): """ Fixes NaturalNameWarning given by trying to write an hdf5 column name """ for ch in r"\`*{}[]()>#+-.!$": if ch in name: name = name.replace(ch,"_") return name
def subset_sum_td(items, target, n, mem): """ The key was to have target as the size of the array instead of the index. That makes sense because the value that we want to reuse is the target """ if target == 0: return True if n<0 or target < 0: return False if mem[target] is not None: return m...
def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(v...
def batch_by_property(items, property_func): """ Takes in a list, and returns a list of tuples, (batch, prop) such that all items in a batch have the same output when put into property_func, and such that chaining all these batches together would give the original list (i.e. order is preserved) ...
def most_likely_view(views): """Picks the most likely view from a dictionary of views, keyed on view ID. Returns the view ID.""" largest_view = -1 lvid = -1 for i in views.items(): if largest_view < len(i[1]): largest_view = len(i[1]) lvid = i[0] return lvid
def make_subpackages(module): """ foo.bar.ham >>> foo foo.bar foo.bar.ham Parameters ---------- module : str Returns ------- out : list[str] """ p = module.split('.') out = [] for i in range(1, len(p) + 1): out.append('.'.join(p[:i]))...
def format_bytes(size): """ Convert bytes to a human-friendly units.. """ if size < 0x400: return '{:d} B'.format(size) size = float(size) / 0x400 for prefix in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB'): if size < 0x400: return '{:0.02f} {}'.format(size, prefi...
def isValidRAID(raids): """ Compare slots quantity vs rules min/max. Return True if OK, else return an error message. """ rules = { 0: [1, 999], 1: [2, 2], 5: [3, 999], 6: [4, 999], 10: [4, 999], 50: [6, 999], 60: [8, 999] } if len(raids) <...
def no_limits(nparams,npeaks): """ No limits on nparameters for npeaks. """ return [[(None,None)]*npeaks]*nparams
def get_from_cache(cache, element): """Gets a node from a list (cache) if there is already the same node in this list. If not, give back the original node""" try: return cache[cache.index(element)] except ValueError: return element
def _make_list(values): """Generate a list suitable to pass to templates.""" return '[%s]' % ', '.join('"%s"' % item for item in values)
def value_to_output(value, output): """ Push last created value to output Sig: string, listof number -> string """ if value != "": output.append(value) return ""
def get_instance_type(entity_name, instance_dict=None): """ :param entity_name: name of an entity; :param instance_dict: dictionary that contains the instance type of each entity; :return: the instance type of the provided entity; Get the instance type of a given entity, as specified by t...
def rimin(*args): """ Rounded integer min """ return min(int(round(x)) for x in args)
def parse_instruction(line): """Parse line with instruction to tuple representing it.""" instruction, element, *parts = line.split() if parts: return (instruction, element[:-1], int(parts[0])) if element.isalpha(): return (instruction, element) return (instruction, int(element))
def extract_args_and_options(argv): """Extrait la liste ds arguments et des options, retourne 2 listes.""" # Tout ce qui commence par "--" est une option options = list( filter(lambda x : x.startswith('--'), argv[1:]) ) # Tout ce qui n'est pas une option est un argument arguments =...
def wid_to_gid(wid): """Calculate gid of a worksheet from its wid.""" widval = wid[1:] if len(wid) > 3 else wid xorval = 474 if len(wid) > 3 else 31578 return str(int(widval, 36) ^ xorval)
def complex_math(x: int, y: int) -> int: """Very complex math calculation. This function will add two numbers and return the result of the calculation. Args: x (int): first number to be calculated. y (int): second number to be calculated. Returns: int: the answer to the calculation...
def quote_ident(text): """ Replace every instance of '"' with '""' *and* place '"' on each end. """ return '"' + text.replace('"', '""') + '"'
def circ_subtract(circ1, circ2): """ Let circ1 and circ2 be lists of depth-1 circuits. This function subtracts the gates in the k'th depth-1 circuit of circ2 from that of circ1. Note that this function may lead to misbehaviors if circ2 is not a sub-circuit of circ1. Args: circ1, circ2(l...
def get_rpk_score(protein_length): """Calculates RPK score of a single hit (number of reads per kilobase of reference gene) Args: protein_length (int): length of a reference protein Returns: ret_val (float): RPK score of the hit """ return 1000/3/protein_length
def could_be_mongo_object_id(test_id:str = "") -> bool: """ Tests if passed-in string is 24 lower-case hexadecimal characters. Parameters ---------- test_id : str String representing a possible mongodb objectId Returns ------- test_val : bool True if test_id is 24 l...
def _add_slash(s): """ Adds slash to end of string """ return s if s[-1] == "/" else s + "/"
def to_unicode(s, encoding='utf-8'): """ convert a string or unicode to unicode """ if isinstance(s, str): return s else: return str(s, encoding=encoding)
def get_train_valid_test_split_(splits_string, size): """ Get dataset splits from comma or '/' separated string list.""" print(splits_string) splits = [] if splits_string.find(',') != -1: splits = [float(s) for s in splits_string.split(',')] elif splits_string.find('/') != -1: splits...
def add_single_animation(name, sub_name, img_path_list, playback_list=[], animation_path_lib=None): """Add a single sub-animation to an animation path library.""" if not animation_path_lib: animation_path_lib = {name: {}} else: if not animati...
def flipping_bits(n): """Hackerrank Problem: https://www.hackerrank.com/challenges/flipping-bits/problem You will be given a list of 32 bit unsigned integers. Flip all the bits (1 -> 0 and 0 -> 1) and print the result as an unsigned integer. Solve: format the integer into a binary and then ite...
def edit_distance(w1, w2): """Code taken from https://github.com/maxwell-schwartz/PUNchlineGenerator Levenshtein distance modified such that deletions and addition are cost 2 and deletions cost 1 """ cost = [] if (w1 is None) or (w2 is None): # Return a number that' huge r...