content
stringlengths
42
6.51k
def load_mac(devices=None): """Load dictionary using MAC address as key.""" if not devices: return None mac_devices = {} for device in devices: if "mac-address" in device: mac = device.pop("mac-address") mac_devices[mac] = device return mac_devices
def convertToMapPic(byteString, mapWidth): """convert a bytestring into a 2D row x column array, representing an existing map of fog-of-war, creep, etc.""" data = [] line = "" for idx,char in enumerate(byteString): line += str(ord(char)) if ((idx+1)%mapWidth)==0: data.append(...
def ajouterLettre(lst, lst_s, lettre): """lst x list x str -> Bool Ajoute les lettres correspondant. Renvoie False s'il n'y en a aucune""" trouve = False for k in range(len(lst)): if lst[k].lower() == lettre.lower() : lst_s[k] = lst[k] trouve = True return trouve
def selection_sort(L): """Implementation of selection sort.""" n = len(L) if n < 2: return L for i in range(n - 1): smallest_idx = i for j in range(i + 1, n): if L[j] < L[smallest_idx]: smallest_idx = j if smallest_idx != i: L[small...
def convert_seconds_to_time_str(value): """ Converts the given seconds to a time string of format m:ss """ minutes, seconds = divmod(value, 60) return str(int(minutes)) + ':' + str(int(seconds))
def prec(x, y, s, d): """ prec(x, y, s, d) handle the precedences the task x must be finished before task y begin """ return (s[x] + d[x] <= s[y])
def try_ex(func): """ Call passed in function in try block. If KeyError is encountered return None. This function is intended to be used to safely access dictionary. Note that this function would have negative impact on performance. """ try: return func() except KeyError: re...
def word_article_count_list_to_dict(word_counts): """ Converts list of tuples of words and counts of articles these occur in into list of dictionaries of lists of words and counts. List is of form: [("word, word, ...", count), ...] Dictionary is of form: { "words": [<WOR...
def filesizeToBytes(data: bytes) -> bytes: """ This function returns the size of data in 8 bytes """ return (len(data)).to_bytes(8, byteorder='big')
def is_altitude(value: str) -> bool: """Returns True if the value is a possible altitude""" if len(value) < 5: return False if value[:4] == "SFC/": return True if value[:2] == "FL" and value[2:5].isdigit(): return True first, *_ = value.split("/") if first[-2:] == "FT" an...
def map_characters(k_map, alphabet_map, mapping): """Apply character mapping as specified. Parameters ---------- k_map : str String of mapped characters. alphabet_map : type Description of parameter `alphabet_map`. mapping : type Description of parameter `mapping`. ...
def dm_fibonancci(n): """ The following function determines the Fibonacci Sequence using a Recursive Function. Finding the dm_Fibonacci sequence with seeds of 1, 1, 2 for n = 0, 1, 2 respectively. The sequence is 0,1,1,2,3,5,8,13,..., where the recursive relation is dm_fibonancci(n) = dm_fibonancci(n-1) + 2* dm...
def get_polynomial_points(coefficients, num_points, prime): """ Calculates the first n polynomial points. [ (1, f(1)), (2, f(2)), ... (n, f(n)) ] """ points = [] for x in range(1, num_points + 1): # start with x=1 and calculate the value of y y = coefficients[0] # calcula...
def fixChromName(name, orgn="medicago"): """ Convert quirky chromosome names encountered in different release files, which are very project specific, into a more general format. For example, in Medicago Convert a seqid like `Mt3.5.1_Chr1` to `chr1` `Mt3.5_Chr3` to `c...
def pull_ref(pull): """Turn a PR number of list of refs into specific refs to fetch and check out.""" if isinstance(pull, int) or ',' not in pull: return ['+refs/pull/%d/merge' % int(pull)], ['FETCH_HEAD'] pulls = pull.split(',') refs = [] checkouts = [] for ref in pulls: change_...
def store(query, new_tar_name): """ :param query: :param new_tar_name: :return: """ query = f'STORE({query}, "{new_tar_name}")' return query
def get_tag_keys(key_list): """ Return a dict of tags with non-null values """ return {i['Key']:i['Value'] for i in key_list if i['Value']}
def find_roots(id2children): """ Find the set of roots - the top nodes of all trees in the graph """ id2parent = {} id2root = {} for parent_id, children_ids in id2children.items(): for child_id in children_ids: id2parent[child_id] = parent_id def find_root(node_id, stack=None):...
def to_jaden_case(string): """ parameter: string return: string in UpperCase first letter Used join on list comprehension where the string is splitted into words """ return " ".join([s.capitalize() for s in string.split()] )
def armour_damage_reduction(armour, damage): """ Calculates the damage reduction from armour. .. note:: The final damage reduction may differ; there are other stats that can grant damage reduction and damage reduction is capped. Parameters ---------- armour : int Armou...
def format_attr_name(attrname, nsmap): """ Returns the human readable attribute name (like metal:define-macro) """ for name, uri in nsmap.items(): attrname = attrname.replace('{%s}' % uri, name and (name + ':') or '') attrname = attrname.replace('{http://www.w3.org/XML/1998/namespace}', '') ...
def getLeafSpeciesFromLeafName(leafName, sepSp = "_"): """ Takes: - leafName (str) : name of a leaf, in the format: species separator gene - sepSp (str) [default = "_" ] : separator between species name and gene name Returns: (str) : species name """ return leafName.parti...
def guess_fileformat(aUri): """ Simple file format guessing (using rdflib format types) based on the suffix see rdflib.parse [https://rdflib.readthedocs.org/en/latest/using_graphs.html] """ if aUri.endswith(".xml"): return "xml" elif aUri.endswith(".nt"): return "nt" elif a...
def prod(*args: int) -> int: """ This function is wrapped and documented in `_polymorphic.prod()`. """ prod_ = 1 for arg in args: prod_ *= arg return prod_
def get_z_prime(tau, alpha_z, beta_z, g, y, z, f): """ Equation [2](2.1.1) :param tau: time constant """ return (1.0 / tau) * (alpha_z * (beta_z * (g - y) - z) + f)
def checkedge(x, x0, x1): """Determeine if the value x is over the edge of an image """ x=int(x) if x < x0: return x0 if x > x1: return x1 return x
def from_vis_js_key_names(d): """ dict -> dict Convert key names from vis_js default key names, i.e. "value" for the size of the node. Delete id key name, otherwise it will be duplicated mydict[new_key] = mydict.pop(old_key) | change key name """ d["computed importance factor"] = d.pop("v...
def rename_bitransformer_inputs(json_config): """ In "BiTransformer" model, rename input "characters" -> "bytes" and update subfields. """ [task] = json_config["task"].values() model = task.get("model") if model and len(model) == 1 and "BiTransformer" in model: model_val = list(model.va...
def _with_a(name: str) -> str: """ Try to work out whether to use 'a' or 'an'. The rule is that we should use 'an' where the word starts with a vowel sound. This is not the same as starting with a vowel (e.g. 'an hour', 'a unit'). Apply a heuristic that should work most of the time, with a special case ...
def arithmetic_progression(el_1, el_2, n): """Finds the nth element of Given the first two elements of an arithmetic progression. NOTE: nth term for arithmetic progression is a sub n = (n-1)*d + a where n is the nth term, d is difference, a is the first element of the arithmetic progression. """...
def _in_cis(chrom, pos, gene_id, tss_dict, window=1000000): """Test if a variant-gene pair is in cis""" if chrom==tss_dict[gene_id]['chr']: tss = tss_dict[gene_id]['tss'] if pos>=tss-window and pos<=tss+window: return True else: return False else: retu...
def _route_cmd(action, dest, gw): """Construct commands to manipulate routes.""" cmd = ['route', '-q', action, dest, gw] return cmd
def _normalize(string): """ Normalize whitepace in a string according to PDS4 Standards. Notes ----- There are a number of ways to implement this method. The employed implementation is generally either the fastest or close to the fastest between the various platforms. Parameters ----------...
def _dump_polygon(obj, fmt): """ Dump a GeoJSON-like Polygon object to WKT. Input parameters and return value are the POLYGON equivalent to :func:`_dump_point`. """ coords = obj['coordinates'] poly = 'POLYGON (%s)' rings = (', '.join(' '.join(fmt % c for c in pt) for pt in ring) ...
def calc_inertial_power(V, A, test_mass, f_inertial): """ Power demands of the cycle accelerations, Annex 2-3.1. :param test_mass: .. jsonschema:: data-schema.yaml#/properties/test_mass :param f_inertial: .. jsonschema:: data-schema.yaml#/properties/f_inertial """ return (A * V ...
def check_client(config, client_dn): """Check if client dn is in whitelist""" # If config is None then all clients are not allowed if config is None: return False if config.get('allow_all', False) is True: return True allowed = config.get('allowed') if client_dn is None or not i...
def normalize_location_cot(location_str): """ When geocoding intersections, the City of Toronto geocoder maintained by GCC expects input of the form "Street 1 and Street 2", but some Ped Delay files use "at" and "over" (the latter for overpasses). We normalize these to use "and". """ return location_str....
def _get_value(dict, key): """ Returns the value for corresponding key. If key is not present return None """ if key in dict.keys(): return dict[key] return None
def _get_swsft_coeff_index(ell, m): """Get index in coefficient array. Returns the index corresponding to (ell, m) in the coefficient array in the format returned by swsft_forward_naive() Args: ell: Degree (int). m: Order (int). Returns: An index (int). """ return ell**2 + m + ell
def fruit_function(fruit1, fruit2): """ fruits = fruit1 + " " + fruit2 return fruits """ lst = []; lst.append(fruit1) lst.append(fruit2) return lst
def usage_percent(used, total, _round=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (used / total) * 100 except ZeroDivisionError: ret = 0 if _round is not None: return round(ret, _round) else: return ret
def get_by_key_chain(mapping, keys): """Get a value from nested mapping by a chain of keys. :param mapping: the mapping from which the value is extracted. :param keys: a sequence of keys used to locate the requested value. :returns: a value resulting from getting a value from the mapping by the...
def normalize_interface(name): """Return the normalized interface name """ if not name: return def _get_number(name): digits = "" for char in name: if char.isdigit() or char in "/.": digits += char return digits if name.lower().startswith...
def combine_prediction_metadata_batches(metadata_list): """Combines a list of dicts with the same keys and lists as values into a single dict with concatenated lists for each corresponding key Args: metadata_list (list): list of dicts with matching keys and lists for values Returns: ...
def codegen_reload_data(): """ Parameters required reload codegen for the fn_main_mock_integration package """ return { "package": u"fn_main_mock_integration", "message_destinations": [u"fn_main_mock_integration", u"fn_test_two"], "functions": [u"a_mock_function_with_no_unicode_c...
def convertFloatToString(value): """ Returns a string representation of a float value. """ return "%f%%" % (value * 100.0)
def get_predecessors(blocks, blacklist=set()): """ Get set of predecessor blocks of a given set of blocks. Optionally, it can be filtered with set of blacklisted blocks. """ preds = set() for block in blocks: preds |= set(block.preds()) preds = preds.difference(blacklist) return ...
def order_numbers(number1, number2): """This function compares two numbers and returns them in increasing order.""" if number2 > number1: return number1, number2 else: return number2, number1
def cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. https://portingguide.readthedocs.io/en/lat...
def list_to_dict(entries, nrows, ncols, rows=True): """ Given a list of entries, create a dictionary whose keys are coordinate tuples and values are the entries. EXAMPLES:: sage: from sage.matrix.matrix_space import list_to_dict sage: d = list_to_dict([1,2,3,4],2,2) sage: d[(0,...
def triple_and_filter(nums): """Return new list of tripled nums for those nums divisible by 4. Return every number in list that is divisible by 4 in a new list, except multipled by 3. >>> triple_and_filter([1, 2, 3, 4]) [12] >>> triple_and_filter([6, 8, 10, 12]) [24, 36] ...
def is_gameover(players): """ checks whether game is over or not players: dict (name -> [beed,position]) returns: Boolean """ for i in players: if players[i][1] >= 100: return (False,i) return (True,"")
def nested_dict(opts, value): """create a nested dictionary given a list of keys and a value """ if len(opts) > 1: return {opts[0]: nested_dict(opts[1:], value)} elif len(opts) == 1: return {opts[0]: value} else: ValueError
def issue329(*args): """ Don't emit unbalanced tuple unpacking if the rhs of the assignment is a variable-length argument, because we don't know the actual length of the tuple. """ first, second, third = args return first, second, third
def find_indexes(s, ch='\n'): """Finds all instances of given char and returns list of indexes """ return [i for i, ltr in enumerate(s) if ltr == ch]
def dna2vec(dna): """ converts the digits to the dna alphabet and returns dna string """ str = [] for i in range(len(dna)): if dna[i] == 'A': str.append(0) elif dna[i] == 'C': str.append(1) elif dna[i] == 'G': str.append(2) else: ...
def none_handler(command): """Returns command bytes for command with not arguments. Arguments: command -- the command description dict """ return command["command"]
def _parse_url_work_relation(response): """ response is {'resource': 'https://imslp.org/wiki/7_Bagatelles,_Op.33_(Beethoven,_Ludwig_van)', 'relations': [{'source-credit': '', 'target-credit': '', 'type-id': '0cc8527e-ea40-40dd-b144-3b7588e759bf', 'type': 'download for free', 'end': None, 'direct...
def get_intervals(l): """For list of lists, gets the cumulative products of the lengths""" intervals = len(l) * [0] intervals[0] = 1# Initalize with 1 for k in range(1, len(l)): intervals[k] = (len(l[k]) + 1) * intervals[k - 1] return intervals
def printPath(path): """Assumes path is a list of nodes""" result = '' for i in range(len(path)): result += str(path[i]) if i != len(path) - 1: result += '->' return result
def convert_value(value): """ None and boolean values are not accepted by the Transip API. This method converts - None and False to an empty string, - True to 1 """ if isinstance(value, bool): return 1 if value else '' if not value: return '' return value
def get_segmentation_ids_from_net_list(networks): """Get busy segmentation IDs from provided networks list. We need to handle duplicates in segmentation ids. Neutron has different validation rules for different network types. For 'gre' and 'vxlan' network types there is no strong requirement for '...
def clean_names(function): """Clean function names. Args: function (str): a function name. Returns: str: A string with all characters lowered and only the last word if there are multiple period joined words. """ if function is not None: out = function.lower() ...
def prettyprint_dictionary(d): """ Produce a nice string representation of a dictionary, for printing. :param d: Dictionary to be printed. :type d: Dict[Optional[Any]] :return: String representation of :param d:. :rtype: str """ return "{\n%s\n}" % "\n".join( " %s: %s" ...
def count(string): """Return dict as a result.""" # Used defaultdict b/c a regular dict return KeyError during for loop # The function code should be here from collections import defaultdict res = defaultdict(int) for i in string: res[i] += 1 return res
def splitPath(path, unknown_sep=None): """Try to split path with difference sep style @return (SPLICED_PATH, SEP). SEP can be path separator or None if not able to detect separator style. @example >>> splitPath(r'C:\XXX\YYY\ZZZ') (['C:', 'XXX', 'YYY', 'ZZZ'], '\\\\') >>> splitPath(r'XXX') (['XXX'], ...
def occurs_count(lst,obj): """returns the number of times obj occurs in lst""" count = 0 for x in lst: if x == obj: count += 1 return count
def are_pairwise_disjoint(it, raise_error=False): """ Determines whether a collection of elements are pairwise disjoint. :param it: iterable of elements :param raise_error: if a (descriptive) error shall be raised in case the elements iterables are not disjoint :return: true if all elements are...
def tolist(x): """convert input to list if it is not already a list or tuple""" if type(x) in [list,tuple]: return x return [x]
def linreg(X, Y): """ Summary Linear regression of y = ax + b Usage real, real, real = linreg(list, list) Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value """ if len(X) != len(Y): raise ValueError("unequal length") N = len(...
def extract_iface_name_from_content(content): """ Extract the interface name from the third item in the content, delimited by spaces, up to its second-last character. For example, this transmutes ``Features for bond0:`` to ``bond0``. """ return content.split(" ", 3)[-1][:-1]
def schedule(epoch, lr_init, epochs): """ piecewise learning rate schedule borrowed from https://github.com/timgaripov/swa """ t = (epoch) / (epochs) lr_ratio = 0.01 if t <= 0.5: factor = 1.0 elif t <= 0.9: factor = 1.0 - (1.0 - lr_ratio) * (t - 0.5) / 0.4 else: ...
def parse_readelf_line(x): """Return the version from a readelf line that looks like: 0x00ec: Rev: 1 Flags: none Index: 8 Cnt: 2 Name: GLIBCXX_3.4.6 """ return x.split(':')[-1].split('_')[-1].strip()
def required_args(a, b): """ Returns the values for a and b. """ return 'a=%s, b=%s' % (a, b)
def fake_bin(x): """ Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. :param x: sting of digits. :return: the resulting string. """ return "".join("0" if int(i) < 5 else "1" for i in str(x))
def pop_params_or_defaults(params, defaults): """Returns params.update(default) restricted to default keys""" merged = { key: params.pop(key, default) for key, default in defaults.items() } return merged
def normalize_weights(weights): """ normalizes criteria's weigths """ normalized_weights = [0 for j in range(len(weights))] weights_sum = sum(weights) for j in range(len(weights)): normalized_weights[j] = (weights[j] * 1.0 / weights_sum) return normalized_weights
def add_prefix_to_str(item: str, prefix: str, divider: str = '') -> str: """Adds 'prefix' to 'item' with 'divider' in between. Args: item (str): item to be modified. prefix (str): prefix to be added to 'item'. divider (str): str to add between 'item' and 'prefix'. Defaults to '', ...
def is_tls_record_magic(d): """ Returns: True, if the passed bytes start with the TLS record magic bytes. False, otherwise. """ d = d[:3] # TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2 # http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html#c...
def perfect_score(student_info): """ :param student_info: list of [<student name>, <score>] lists :return: first `[<student name>, 100]` or `[]` if no student score of 100 is found. """ for info in student_info: if info[1] == 100: return info return []
def with_without_e(s): """Return number of Es in string. input = string output = count in string form of Es """ if not s: return s count = 0 for e in s: if e == 'e' or e == 'E': count += 1 if count == 0: return 'There is no "e".' else: st_...
def join_on_pipes(tokens): """ joins all tokens, except if they are pipes. >>> join_on_pipes(['echo ', "Hello>hi" >> file.txt]) ['echo "Hello>hi"', '>>', 'file.txt'] """ cmds = [] pipes = [] at = 0 while True: try: token = tokens[at] except IndexError: ...
def centroid(points): """Return the lon,lat simple geometric centroid for features.""" # Todo: Geographic center, or simple average? x = sum(i[0] for i in points) y = sum(i[1] for i in points) return x/len(points), y/len(points)
def read_maze(file_name): """ Reads a maze stored in a text file and returns a 2d list containing the maze representation. """ try: with open(file_name) as fh: maze = [[char for char in line.strip("\n")] for line in fh] num_cols_top_row = len(maze[0]) for row ...
def get_Zb(k, l): """Return Z for k-l length suffix.""" assert 0 < k and 0 <= l <= k return pow(2, k-l) - 1*(l<k)
def is_valid_monthly_period(year: int, period: int) -> bool: """ Returns False for periods before agencies were able to make monthly submissions """ is_valid_period = True if year == 2020 and period in [2, 4, 5]: is_valid_period = False if year < 2020 and period in [2, 4, 5, 7, 8, 10, 11]: ...
def split_file_path(paths: dict) -> dict: """Convert files paths stored in a dict to nested dicts. Author: @PaigeCD / Paige Downey""" output = {} popped = {} for key, value in paths.items(): if value is not None and value != "": if "/" not in key: key = key + "/" ...
def zero_gen(n): """Returns n amount of zeros (0) in string format, eg n=3 => "000" """ zeros = "" for i in range(0, n): zeros = zeros + "0" return zeros
def get_r(t, N): """ Get the Pearson's r given the above parameters. Paramters --------- > `t`: the t-statistic for the t-test > `N`: total number of participants in the test """ return (t*t / (t*t + N -2)) ** 0.5
def none_for_empty_string(s: str): """Input csv reads empty strings as '' instead of None. We'd want to insert None in such cases""" if s: return s else: return None
def sort_format(src): """ format 1-2-3... to 0001-0002-0003... src should be convertable to int """ src_list= src.split('-') res_list= [] for elm in src_list: try: res_list.append('%04d' % int(elm)) except: res_list.append(elm) res= '-'.join(res_li...
def gamble_curve(rand): """ Reward curve for gambling. Desired properties of the curve: - Low probability of value near 0, or players will be mad and think the game is unfair (for whatever standard of fair). - Low probability of value near 1, or players will be winning too many coins (i...
def temp_ouput_file(pytest_input): """ Return the name of the temporary output file for a given test. Arguments --------- pytest_input : str The pytest input indicating for which test function to obtain the temporary output file name Returns ------- str The temp...
def cap(value : float, minimum : float, maximum : float) -> float: """Caps the value at given minimum and maximum. Arguments: value {float} -- The value being capped. minimum {float} -- Smallest value. maximum {float} -- Largest value. Returns: float -- The capped v...
def cell(i, j): """String name for a cell in the grid.""" return 'cell_%d_%d' % (i, j)
def get_closing_brace_index(string): """ Returns the index of the last closing brace `{` in a BibTeX entry. """ count = 0 for i, s in enumerate(string): if s == "{": count += 1 elif s == "}": count -= 1 if count == 0: return i ...
def bin_exp_mod(a, n, b): """ >>> bin_exp_mod(3, 4, 5) 1 >>> bin_exp_mod(7, 13, 10) 7 """ # mod b assert not (b == 0), "This cannot accept modulo that is == 0" if n == 0: return 1 if n % 2 == 1: return (bin_exp_mod(a, n - 1, b) * a) % b r = bi...
def remove_punctuations(text: str) -> str: """Remove non-space, non-alphanumeric characters from `text` Arguments: text {str} -- ex: 'It\'s 4:00am, you say?' Returns: str -- ex: 'Its 400am you say' """ unpunct = ''.join(t for t in text if t.isalnum() or t.isspace()) return unp...
def parseNeighbors(urls): """Parses a urls pair string into urls pair.""" parts = urls.split(',') return parts[0], parts[1]
def check_condition(template, context): """ Checks a condition formatted as jinja2 template. May raise Exceptions if the evaluation fails. """ if not template: return True rendered = template.render(**context) return bool(eval(str(rendered)))