content
stringlengths
42
6.51k
def factorial(letter_qty): """ :param letter_qty: how many letters are key in :return: total arrangement qty """ if letter_qty == 0: return 1 else: temp = letter_qty * factorial(letter_qty - 1) return temp
def bann(code): """ If banned return True else False """ ban_list = ['First Ride', 'New Customers', 'From SMU', 'From NTU', 'From NUS', 'From SUTD', 'From SIM', 'First GrabHitch', 'New GrabPay', 'First 2 Rides', 'First 4 Rides'] for word in ban_list: if code.find(word) > 0: return True return False
def convert_to_ents_dict(tokens, tags): """ Handle the BIO-formatted data :param tokens: list of tokens :param tags: list of corresponding BIO tags :return: json-formatted result """ ent_type = None entities = [] start_char_offset = 0 end_char_offset = 0 start_char_entity = 0 entity_tokens = [] tokens_length = len(tokens) for position, (token, token_tag) in enumerate(zip(tokens, tags)): if token_tag == "O": if ent_type: entity = { "type": ent_type, "entity": " ".join(entity_tokens), "start_offset": start_char_entity + 1, "end_offset": end_char_offset + 1 } entities.append(entity) entity_tokens = [] ent_type = None elif ent_type and token_tag.startswith('B-'): entity = { "type": ent_type, "entity": " ".join(entity_tokens), "start_offset": start_char_entity + 1, "end_offset": end_char_offset + 1 } entities.append(entity) entity_tokens = [] ent_type = token_tag[2:] entity_tokens.append(token) start_char_entity = len(" ".join(tokens[:position])) elif token_tag.startswith('B-'): ent_type = token_tag[2:] entity_tokens.append(token) start_char_entity = len(" ".join(tokens[:position])) elif not ent_type and token_tag.startswith('I-'): ent_type = token_tag[2:] entity_tokens.append(token) start_char_entity = len(" ".join(tokens[:position])) elif ent_type and token_tag.startswith('I-') and token_tag[2:] == ent_type: entity_tokens.append(token) elif ent_type and token_tag.startswith('I-') and token_tag[2:] != ent_type: entity = { "type": ent_type, "entity": " ".join(entity_tokens), "start_offset": start_char_entity + 1, "end_offset": end_char_offset + 1 } entities.append(entity) entity_tokens = [] ent_type = token_tag[2:] entity_tokens.append(token) start_char_entity = len(" ".join(tokens[:position])) if position: start_char_offset = len(" ".join(tokens[:position])) + 1 end_char_offset = start_char_offset + len(token) - 1 # catches an entity that foes up until the last token if ent_type and position == tokens_length - 1: entity = { "type": ent_type, "entity": " ".join(entity_tokens), "start_offset": start_char_entity + 1, "end_offset": end_char_offset + 1 } entities.append(entity) return [" ".join(tokens), entities]
def nsf(num, n=1): #from StackOverflow: https://stackoverflow.com/questions/9415939/how-can-i-print-many-significant-figures-in-python """n-Significant Figures""" while n-1 < 0: n+=1 numstr = ("{0:.%ie}" % (n-1)).format(num) return float(numstr)
def get_outputs(job: dict, configuration: dict, data: dict) -> list: """ Get list of output Datareference """ outputs = [] if "outputs" in job: for data_name in job["outputs"]: data_object = data[data_name] outputs.append(data_object["pipelinedata_object"]) return outputs
def weigher(r, method='hyperbolic'): """ The weigher function. Must map nonnegative integers (zero representing the most important element) to a nonnegative weight. The default method, 'hyperbolic', provides hyperbolic weighing, that is, rank r is mapped to weight 1/(r+1) Args: r: Integer value (supposedly a rank) to weight method: Weighing method. 'hyperbolic' """ if method == 'hyperbolic': return 1 / (r + 1) else: raise Exception('Unknown method: {}'.format(method))
def integer(value, numberbase=10): """OpenEmbedded 'integer' type Defaults to base 10, but this can be specified using the optional 'numberbase' flag.""" return int(value, int(numberbase))
def getPlayerID(playerOrID): """Returns the Player ID for the given player.""" if playerOrID is None or playerOrID == -1: return -1 if isinstance(playerOrID, int): return playerOrID return playerOrID.getID()
def elliptical_u(b, k, upsilon, l_tilde, n): """ Disutility of labor supply from the elliptical utility function Args: b (scalar): scale parameter of elliptical utility function k (scalar): shift parametr of elliptical utility function upsilon (scalar): curvature parameter of elliptical utility function l_tilde (scalar): maximum amount of labor supply n (array_like): labor supply amount Returns: u (array_like): disutility of labor supply """ u = b * ((1 - ((n / l_tilde) ** upsilon)) ** (1 / upsilon)) + k return u
def get_value_with_field(model, field, null=None): """ Get value from a model or dict or list with field Field must be a string or number value usage: >>> model_value_with_field({"key1": "value1", "key2": "value2"}, "key1", "default") "value1" >>> model_value_with_field({"key1": "value1", "key2": "value2"}, "key3", "default") "default" >>> model_value_with_field(["1", "2", "3"], 2, "default") "3" >>> model_value_with_field(["1", "2", "3"], 4, "default") "default" :param model: origin model or dict or list :param field: which value want to get :param null: default value if field not in model """ # check input value if not model: return null # get value from dict if isinstance(model, dict): return model.get(field, null) # get value from list if isinstance(model, list): # if model is a list, field must be a number try: index = int(field) # check index is in the list if len(model) <= index: return null return list(model)[index] except TypeError: return null # get value from an object if hasattr(model, field): return getattr(model, field) return null
def _apply_correction(tokens, correction, offset): """Apply a single correction to a list of tokens""" start_token_offset, end_token_offset, _, insertion = correction to_insert = insertion[0].split(" ") end_token_offset += (len(to_insert) - 1) to_insert_filtered = [t for t in to_insert if t != ""] head = tokens[:start_token_offset + offset] tail = tokens[end_token_offset + offset:] new_tokens = head + to_insert_filtered + tail new_offset = len(to_insert_filtered) - (end_token_offset - start_token_offset) + offset return new_tokens, new_offset
def get_last_n_features(feature, current_words, idx, n=3): """For the purposes of timing info, get the timing, word or pos values of the last n words (default = 3). """ if feature == "words": position = 0 elif feature == "POS": position = 1 elif feature == "timings": position = 2 else: raise Exception("Unknown feature {}".format(feature)) start = max(0, (idx - n) + 1) # print start, idx + 1 return [triple[position] for triple in current_words[start: idx + 1]]
def traffic_gen(flows: dict, flow_rates, num_bytes, K, skewness): """Generate the traffic configurations. Args: flows (dict): Dictionary of flows information (key, value) = (flowID, (flowID, (src, dst))). flow_rates (dict): Dictionary of flow rate information (key, value) = (flowID, flow rate). num_bytes (int): Number of bytes to send for all the flows. K (int): number of pods. skewness (float): num_bytes skewness between intrapod and interpod traffic, inter = intra*skewness Returns: str: Generated traffic configurations. Examples: The return can be " # Format: int job id, source host, destination host, number of bytes to transfer, time in seconds to start the transfer, expected fair share of the flow in Mbits/sec 1, h1, h2, 80000000, 0, 1.4583333333333346, h1 s1 s17 s2 h2 2, h1, h3, 80000000, 0, 1.4583333333333346, h1 s1 s17 s3 h3 3, h1, h4, 80000000, 0, 1.4583333333333346, h1 s1 s17 s4 h4 ... " """ traffic_conf = "# Format: int job id, source host, destination host, number of bytes to transfer, " \ "time in seconds to start the transfer, expected fair share of the flow in Mbits/sec, specified path\n" for flow_id, (src,dst) in flows.items(): if (int(src[1:])-1) // K != (int(dst[1:])-1) // K: traffic_conf += "{}, {}, {}, {}, 0, {}, N/A\n".format(flow_id, src, dst, int(num_bytes*skewness), flow_rates[flow_id]) else: traffic_conf += "{}, {}, {}, {}, 0, {}, N/A\n".format(flow_id, src, dst, num_bytes, flow_rates[flow_id]) return traffic_conf
def parsePort(port): """ Converts port in string format to an int :param port: a string or integer value :returns: an integer port number :rtype: int """ result = None try: result = int(port) except ValueError: import socket result = socket.getservbyname(port) return result
def _CreateAssetsList(path_tuples): """Returns a newline-separated list of asset paths for the given paths.""" dests = sorted(t[1] for t in path_tuples) return '\n'.join(dests) + '\n'
def checksum(data): """ Calculates the checksum, given a message without the STX and ETX. Returns a list with the ordered checksum bytes""" calc_sum = 0 for i in data: calc_sum += i low_sum = calc_sum >> 8 & 0xFF high_sum = calc_sum & 0xFF return bytearray([high_sum, low_sum])
def get_duplicates(iterable): """ Returns set of duplicated items from iterable. Item is duplicated if it appears at least two times. """ seen = set() seen2 = set() for item in iterable: if item in seen: seen2.add(item) else: seen.add(item) return seen2
def find_workflow_uuid(galaxy_workflows,uuid): """ Finds a particular workflow with the given uuid. :param galaxy_workflows: The list of workflows to search through. :param uuid: The workflow uuid to search for. :return: The matching workflow. :throws: Exception if no such matching workflow. """ workflow = None for w in galaxy_workflows: if w['latest_workflow_uuid'] == uuid: if workflow != None: raise Exception("Error: multiple workflows with uuid="+uuid+", please use --workflow-id to specify") else: workflow=w return workflow
def fill_point(x, y, z, _): """ Returns a string defining a set of minecraft fill coordinates relative to the actor. In minecraft, the y axis denotes the vertical (non-intuitively). """ return f'~{int(x)} ~{int(z)} ~{int(y)}'
def rbits_to_int(rbits): """Convert a list of bits (MSB first) to an int. l[0] == MSB l[-1] == LSB 0b10000 | | | \\--- LSB | \\------ MSB >>> rbits_to_int([1]) 1 >>> rbits_to_int([0]) 0 >>> bin(rbits_to_int([1, 0, 0])) '0b100' >>> bin(rbits_to_int([1, 0, 1, 0])) '0b1010' >>> bin(rbits_to_int([1, 0, 1, 0, 0, 0, 0, 0])) '0b10100000' """ v = 0 for i in range(0, len(rbits)): v |= rbits[i] << len(rbits)-i-1 return v
def stick_to_bounds(box, bounds=(0,0,1,1)): """ Sticks the given `box`, which is a `(l, t, w, h)`-tuple to the given bounds which are also expressed as `(l, t, w, h)`-tuple. """ if bounds is None: return box l, t, w, h = box bl, bt, bw, bh = bounds l += max(bl - l, 0) l -= max((l+w) - (bl+bw), 0) t += max(bt - t, 0) t -= max((t+h) - (bt+bh), 0) return l, t, w, h
def setup_path(project, test_data): """ Setting up project URL :param project: from pytest_addoption :return: project URL """ url = project if project == 'market': url = test_data[0]['url'] elif project == 'bank': url = test_data[0]['url'] elif project == 'intranet': url = test_data[0]['url'] return url
def get_project_host_names_local(): """" In tests and local projectnames are hardcoded """ return ['wiki', 'dewiki', 'enwiki']
def map_route_to_route_locations(vehicle_location, route, jobs): """ Maps route list, which includes job ids to route location list. :param vehicle_location: Vehicle location index. :param route: Job ids in route. :param jobs: Jobs information, which includes job ids, location indexes and delivery. :return: Route location list including job location indexes. """ route_locations = [vehicle_location] for job in route: job_location = jobs[job][0] route_locations.append(job_location) return route_locations
def post_data(data): """ Take a dictionary of test data (suitable for comparison to an instance) and return a dict suitable for POSTing. """ ret = {} for key, value in data.items(): if value is None: ret[key] = '' elif type(value) in (list, tuple): if value and hasattr(value[0], 'pk'): # Value is a list of instances ret[key] = [v.pk for v in value] else: ret[key] = value elif hasattr(value, 'pk'): # Value is an instance ret[key] = value.pk else: ret[key] = str(value) return ret
def flatten(x): """flatten flatten 2d array to 1d array :param x: initial array :return: array after flatten """ x_flatten = [] for i in range(len(x)): for j in range(len(x[0])): x_flatten.append(x[i][j]) return x_flatten
def sanitize_plugin_class_name(plugin_name: str, config: bool = False) -> str: """ Converts a non-standard plugin package name into its respective class name. :param: plugin_name: String a plugins name :param: config: Boolean true if it should convert into a config name instead of a class name. For given package: philips_hue_lights when config is false it will produce PhilipsHueLightsPlugin and when its true it will produce PhilipsHueLightsConfig :return: The name of the class enclosed within the plugin package. """ if plugin_name is None: return "" parts = plugin_name.split("_") sanitized = [] for part in parts: part = part.capitalize() sanitized.append(part) sanitized.append("Plugin" if not config else "Config") return "".join(sanitized)
def variance(x): """ Return the standard variance If ``x`` is an uncertain real number, return the standard variance. If ``x`` is an uncertain complex number, return a 4-element sequence containing elements of the variance-covariance matrix. Otherwise, return 0. **Examples**:: >>> ur = ureal(2.5,0.5,3,label='x') >>> variance(ur) 0.25 >>> ur.v 0.25 >>> uc = ucomplex(1+2j,(.5,.5),3,label='x') >>> variance(uc) VarianceCovariance(rr=0.25, ri=0.0, ir=0.0, ii=0.25) """ try: return x.v except AttributeError: return 0.0
def int_to_roman(number: int) -> str: """ Given a integer, convert it to an roman numeral. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(int_to_roman(value) == key for key, value in tests.items()) True """ ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] result = [] for (arabic, roman) in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result)
def dice_coefficient(a, b): """dice coefficient 2nt / (na + nb).""" if not len(a) or not len(b): return 0.0 if len(a) == 1: a = a + u'.' if len(b) == 1: b = b + u'.' a_bigram_list = [] for i in range(len(a) - 1): a_bigram_list.append(a[i:i + 2]) b_bigram_list = [] for i in range(len(b) - 1): b_bigram_list.append(b[i:i + 2]) a_bigrams = set(a_bigram_list) b_bigrams = set(b_bigram_list) overlap = len(a_bigrams & b_bigrams) dice_coeff = overlap * 2.0 / (len(a_bigrams) + len(b_bigrams)) return dice_coeff
def int_to_bytes(number: int) -> bytes: """Convert integer to byte array in big endian format""" return number.to_bytes((number.bit_length() + 7) // 8, byteorder='big')
def annotate_counts(node): """Recursive function to annotate each node with the count of all of it's descendants, as well as the count of all sibling comments plus their children, made after each node. """ # If no replies, this is a leaf node. Stop and return 1. node['reply_count'] = 0 if not node['replies']: return 1 else: # Annotate descendants and sum counts. for r in node['replies']: node['reply_count'] += annotate_counts(r) # Once descendants are annotated with descendant counts, # annotate with the count of siblings and their children coming after # this node. after_count = 0 for r in reversed(node['replies']): r['after_count'] = after_count after_count += r['reply_count'] + 1 return node['reply_count'] + 1
def format_data(account): """Format account into printable format: name, description and country""" name = account["name"] description = account["description"] country = account["country"] return f"{name}, a {description}, from {country}"
def caption_from_metadata(metadata): """ converts metadata list-of-lists to caption string which is one antinode per line """ caption = "" for an in range(len(metadata)): [cx, cy, a, b, angle, rings] = metadata[an] #this_caption = "[{0}, {1}, {2}, {3}, {4}, {5}]".format(cx, cy, a, b, angle, rings) this_caption = "{0},{1},{2},{3},{4},{5}".format(cx, cy, a, b, angle, rings) if (an > 0): caption +="\n" caption += this_caption return caption
def smoothstep(x): """Polynomial transition from 0 to 1 with continuous first derivative""" return -2*x**3 + 3*x**2
def format_ctor_arguments(arguments, parent, id, size): """Format constructor arguments; returns a list arguments: Constructor arguments (list) parent: Parent widget (string or unicode) id: Widget ID e.g. wxID_ANY size: Widget size 'width, height'""" vSize = size.split(',') for i in range(len(arguments)): if arguments[i] == '$parent': arguments[i] = parent elif arguments[i] == '$id': arguments[i] = id elif arguments[i] == '$width': arguments[i] = vSize[0] elif arguments[i] == '$height': arguments[i] = vSize[1] return arguments
def reverse_reps(replacements): """Map from replacement to source and reverse each string also The string reverse is needed because the steps_to_molecule reverses the molecule string itself. """ return {b[::-1]: a[::-1] for a, b in replacements}
def obtenerBinario(numero): """ bin(numero) obtiene el valor binario de numero [2:] obtiene los elementos de del binario anterior excepto los primeros 2, por ejemplo 11000000[2:] regresa 000000 zfill(8) rellena con ceros a la izquiera el valor anterior hasta que este tenga longitud 8, por ejemplo 111111 regresa 00111111 """ return bin(numero)[2:].zfill(8)
def _format_datetime_for_js(stamp): """Formats time stamp for Javascript.""" if not stamp: return None return stamp.strftime("%Y-%m-%d %H:%M:%S %Z")
def yaml_list_to_dict(yaml_list): """Converts a yaml list (volumes, configs etc) into a python dict :yaml_list: list of a yaml containing colon separated entries :return: python dict """ return {i.split(":")[0]: i.split(":")[1] for i in yaml_list}
def _linux_kernel_dso_name(kernel_build_target): """Given a build target, construct the dso name for linux.""" parts = kernel_build_target.split(":") return "%s:libtfkernel_%s.so" % (parts[0], parts[1])
def _set_name_and_type(param, infer_type, word_wrap): """ Sanitise the name and set the type (iff default and no existing type) for the param :param param: Name, dict with keys: 'typ', 'doc', 'default' :type param: ```Tuple[str, dict]``` :param infer_type: Whether to try inferring the typ (from the default) :type infer_type: ```bool``` :param word_wrap: Whether to word-wrap. Set `DOCTRANS_LINE_LENGTH` to configure length. :type word_wrap: ```bool``` :returns: Name, dict with keys: 'typ', 'doc', 'default' :rtype: ```Tuple[str, dict]``` """ name, _param = param del param if name is not None and (name.endswith("kwargs") or name.startswith("**")): name = name.lstrip("*") if _param.get("typ", "dict") == "dict": _param["typ"] = "Optional[dict]" if "default" not in _param: _param["default"] = NoneStr elif "default" in _param: _infer_default(_param, infer_type) google_opt = ", optional" if (_param.get("typ") or "").endswith(google_opt): _param["typ"] = "Optional[{}]".format(_param["typ"][: -len(google_opt)]) if "doc" in _param and not _param["doc"]: del _param["doc"] # if "doc" in _param and isinstance(_param["doc"], list): # _param["doc"] = "".join(_param["doc"]) if "doc" in _param: if not isinstance(_param["doc"], str): _param["doc"] = "".join(_param["doc"]).rstrip() else: _param["doc"] = ( " ".join(map(str.strip, _param["doc"].split("\n"))) if word_wrap else _param["doc"] ).rstrip() if ( ( _param["doc"].startswith("(Optional)") or _param["doc"].startswith("Optional") ) and "typ" in _param and not _param["typ"].startswith("Optional[") ): _param["typ"] = "Optional[{}]".format(_param["typ"]) return name, _param
def _gen_alt_forms(term): """ Generate a list of alternate forms for a given term. """ if not isinstance(term, str) or len(term) == 0: return [None] alt_forms = [] # For one alternate form, put contents of parentheses at beginning of term if "(" in term: prefix = term[term.find("(") + 1 : term.find(")")] temp_term = term.replace("({0})".format(prefix), "").replace(" ", " ") alt_forms.append(temp_term) alt_forms.append("{0} {1}".format(prefix, temp_term)) else: prefix = "" # Remove extra spaces alt_forms = [s.strip() for s in alt_forms] # Allow plurals # temp = [s+'s' for s in alt_forms] # temp += [s+'es' for s in alt_forms] # alt_forms += temp # Remove words "task" and/or "paradigm" alt_forms += [term.replace(" task", "") for term in alt_forms] alt_forms += [term.replace(" paradigm", "") for term in alt_forms] # Remove duplicates alt_forms = list(set(alt_forms)) return alt_forms
def factorial(digit: int) -> int: """ >>> factorial(3) 6 >>> factorial(0) 1 >>> factorial(5) 120 """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1))
def nearest_neighbors_targets(x_train, y_train, x_new, k, distance): """Get the targets for the k nearest neighbors of a new sample, according to a distance metric. """ # Associate training data and targets in a list of tuples training_samples = list(zip(x_train, y_train)) # Sort samples by their distance to new sample neighbors = sorted( ((x, y) for (x, y) in training_samples), key=lambda sample: distance(x_new, sample[0]), ) # Keep only targets of the k nearest neighbors return [target for (_, target) in neighbors[:k]]
def hierarchical_label(*names): """ Returns the XNAT label for the given hierarchical name, qualified by a prefix if necessary. Example: >>> from qixnat.helpers import hierarchical_label >>> hierarchical_label('Breast003', 'Session01') 'Breast003_Session01' >>> hierarchical_label('Breast003', 'Breast003_Session01') 'Breast003_Session01' >>> hierarchical_label(3) # for scan number 3 3 :param names: the object names :return: the corresponding XNAT label """ names = list(names) if not all(names): raise ValueError("The XNAT label name hierarchy is invalid: %s" % names) last = names.pop() if names: prefix = hierarchical_label(*names) if last.startswith(prefix): return last else: return "%s_%s" % (prefix, last) else: return last
def get_word_from_derewo_line(line): """Processor for individual line from DeReWo textfile. Args: line: Single line from DeReWo text file Returns: Lowercase word, None if invalid """ line = line.split() # skip words with whitespace if len(line) > 2: return None # disregard DeReWo integer for frequency, only word is needed word = line[0] # lowercase passwords are good enough with sufficient word list length return word.lower()
def date_facet_interval(facet_name): """Return the date histogram interval for the given facet name The default is "year". """ parts = facet_name.rpartition('.') interval = parts[2] if interval in ['month', 'year', 'decade', 'century']: return interval else: return 'year'
def is_palindrome(word): """Check if input is a palindrome.""" if len(word) <= 1: return True return word[0] == word[-1] and is_palindrome(word[1:-1])
def onek_encoding_unk(x, allowable_set): """One-hot embedding""" if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: int(x == s), allowable_set))
def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/n
def build_links_package_index(packages_by_package_name, base_url): """ Return an HTML document as string which is a links index of all packages """ document = [] header = f"""<!DOCTYPE html> <html> <head> <title>Links for all packages</title> </head> <body>""" document.append(header) for _name, packages in packages_by_package_name.items(): for package in packages: document.append(package.simple_index_entry(base_url)) footer = """ </body> </html> """ document.append(footer) return "\n".join(document)
def get_eqn(p0, p1): """ Returns the equation of a line in the form mx+b as a tuple of (m, b) for two points. Does not check for vertical lines. """ m = (p0[1] - p1[1]) / (p0[0] - p1[0]) return (m, p0[1] - m * p0[0])
def find_min_cand(counts): """ return list of candidates who need to be eliminated this round WARNING: doesn't deal properly with ties in support for min candidates.... """ ans = [] if len(counts.keys()) == 0: return None curmin = min(list(counts.values())) for k in counts.keys(): if counts[k] == curmin: return k
def last(xs): """ last :: [a] -> a Extract the last element of a list, which must be finite and non-empty. """ return xs[-1]
def find_peak(A): """find pick element""" if A == []: return None def recursive(A, left=0, right=len(A) - 1): """helper recursive function""" mid = (left + right) // 2 # check if the middle element is greater than its neighbors if ((mid == 0 or A[mid - 1] <= A[mid]) and (mid == len(A) - 1 or A[mid + 1] <= A[mid])): return A[mid] # If the left neighbor of `mid` is greater than the middle element, # find the peak recursively in the left sublist if mid - 1 >= 0 and A[mid - 1] > A[mid]: return recursive(A, left, mid - 1) # If the right neighbor of `mid` is greater than the middle element, # find the peak recursively in the right sublist return recursive(A, mid + 1, right) return recursive(A)
def Pad(ids, pad_id, length): """Pad or trim list to len length. Args: ids: list of ints to pad pad_id: what to pad with length: length to pad or trim to Returns: ids trimmed or padded with pad_id """ assert pad_id is not None assert length is not None if len(ids) < length: a = [pad_id] * (length - len(ids)) return ids + a else: return ids[:length]
def get_network_name_from_url(network_url): """Given a network URL, return the name of the network. Args: network_url: str - the fully qualified network url, such as (https://www.googleapis.com/compute/v1/projects/' 'my-proj/global/networks/my-network') Returns: str - the network name, my-network in the previous example """ return network_url.split('/')[-1]
def in_bisect(word_list, target): """ Takes a sorted word list and checks for presence of target word using bisection search""" split_point = (len(word_list) // 2) if target == word_list[split_point]: return True if len(word_list) <= 1: return False if target < word_list[split_point]: # print ('Calling in_bisect on 0', split_point) return in_bisect(word_list[0:split_point], target) else: # print ('Calling in_bisect on', split_point, len(word_list)) return in_bisect(word_list[split_point:], target)
def dotProduct(listA, listB): """ listA: a list of numbers listB: a list of numbers of the same length as listB Returns the dot product of all the numbers in the lists. """ dotProd = 0 for num in range(len(listA)): prod = listA[num] * listB[num] dotProd = dotProd + prod return dotProd
def word_overlap(left_words, right_words): """Returns the Jaccard similarity between two sets. Note ---- The topics are considered sets of words, and not distributions. Parameters ---------- left_words : set The set of words for first topic right_words : set The set of words for the other topic Returns ------- jaccard_similarity : float """ intersection = len(left_words.intersection(right_words)) union = len(left_words.union(right_words)) jaccard = intersection / union return jaccard
def func(arg): """ :param arg: taking args :return: returning square """ x = arg*arg return x
def is_triangle_possible(triangle): """Check if triangle is possible.""" return sum(sorted(triangle)[:2]) > max(triangle)
def get_nr_dic1_keys_in_dic2(dic1, dic2): """ Return number of dic1 keys found in dic2. >>> d1 = {'hallo': 1, 'hello' : 1} >>> d2 = {'hallo': 1, 'hello' : 1, "bonjour" : 1} >>> get_nr_dic1_keys_in_dic2(d1, d2) 2 >>> d1 = {'hollo': 1, 'ciao' : 1} >>> get_nr_dic1_keys_in_dic2(d1, d2) 0 """ assert dic1, "dic1 empty" assert dic2, "dic2 empty" dic1_keys_found = 0 for key in dic1: if key in dic2: dic1_keys_found += 1 return dic1_keys_found
def find_largest_digit_helper(n, lar): """ This is the help function to find the largest digit :param n :(int) the number to find the largest digit :param lar:(int) found the largest digit :return :(int) the largest digit """ if n < lar: return lar else: if n % 10 > lar: lar = n % 10 return find_largest_digit_helper(int(n/10), lar)
def format_coord(x, y): """coordinate formatter replacement""" return 'x={x}, y={y:.2f}'.format(x=x, y=y)
def isolate_rightmost_0_bit(n: int) -> int: """ Isolate the rightmost 0-bit. >>> bin(isolate_rightmost_0_bit(0b10000111)) '0b1000' """ return ~n & (n + 1)
def convert(client, denomination, amount): """ Convert the amount from it's original precision to 18 decimals """ if denomination == 'nct': return client.to_wei(amount, 'ether') elif denomination == 'nct-gwei': return client.to_wei(amount, 'gwei') elif denomination == 'nct-wei': return amount else: raise ValueError()
def repeat_val (num:int, val): """ repeat a value several k times. """ return [val for _ in range(num - 1)]
def to_dependencies_of(g): """ Compute the dependencies of each path var. :param d: an adjacency list of dependency => [depends on, ...] :return: an adjacency list of the given data structure such that the k => [depends on, ...]. The vertices in the values are presorted to ensure reproducible results """ deps = {} for k, vertices in g.items(): for v in vertices: if v not in deps: deps[v] = set() deps[v].add(k) # I do this for deterministic ordering. return {k: sorted(v) for k, v in deps.items()}
def _user_to_simple_dict(user: dict) -> dict: """Convert Notion User objects to a "simple" dictionary suitable for Pandas. This is suitable for objects that have `"object": "user"` """ record = { "notion_id": user["id"], "type": user["type"], "name": user["name"], "avatar_url": user["avatar_url"], } if user["type"] == "person": record["email"] = user["person"]["email"] return record
def duration(s): """Turn a duration in seconds into a human readable string""" m, s = divmod(s, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) parts = [] if d: parts.append('%dd' % d) if h: parts.append('%dh' % h) if m: parts.append('%dm' % m) if s: parts.append('%ds' % s) return ' '.join(parts)
def is_discrete(num_records: int, cardinality: int, p=0.15): """ Estimate whether a feature is discrete given the number of records observed and the cardinality (number of unique values) The default assumption is that features are not discrete. Parameters ---------- num_records : int The number of observed records cardinality : int Number of unique observed values Returns ------- discrete : bool Whether the feature is discrete """ if cardinality >= num_records: return False if num_records < 1: return False if cardinality < 1: raise ValueError("Cardinality must be >= 1 for num records >= 1") discrete = False density = num_records/(cardinality + 1) if 1/density <= p: discrete = True return discrete
def average(nums,n): """Find mean of a list of numbers.""" return sum(nums) / n
def find_str(string: str, pattern: str) -> list: """ Find all indices of patterns in a string Parameters ---------- string : str input string pattern : str string pattern to search Returns ------- ind : list list of starting indices """ import re if not pattern.isalpha(): # if the pattern contains non-alphabetic chars such as * pattern = "\\" + pattern ind = [m.start() for m in re.finditer(pattern, string)] return ind
def _cons8_99(m8, L88, L89, d_gap, k, Cp, h_gap): """dz constrant for edge gap sc touching 2 corner gap sc""" term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts term2 = 2 * k * d_gap / m8 / Cp / L89 # cond to adj bypass corner return 1 / (term1 + term2)
def expand_brackets(text): """ Change a text with TEXT[ABC..] into a list with [TEXTA, TEXTB, TEXC, ... if no bracket is used it just return the a list with the single text It uses recursivity to allow several [] in the text :param text: :return: """ if text is None: return (None, ) start = text.find("[") end = text.find("]") if start < 0 or end < 0: return [text] text_list = [] for char in text[start+1:end]: text_list += expand_brackets(text[:start] + char + text[end+1:]) return text_list
def tokenize(separators, seq): """tokenize(separators, seq) : Transforms any type of sequence into a list of words and a list of gap lengths seq : the sequence (any sequence type, e.g. a list, tuple, string, ...) [will not be modified] separators : a sequence of values to be used as separators between words. adjoining separators will be merged. Returns: words, gaps where len(gaps) = len(words) + 1 The first and last gaps are at the beginning and end of the sequence and may have length 0. If seq is a string, words are also returned as strings. Otherwise every word is a list. Gap lengths are integers >= 0. """ words = [] gaps = [0] if len(seq)<1: return words, gaps gapIsOpen=True # current gap size for i,v in enumerate(seq): if v not in separators: if gapIsOpen: words.append([]) gapIsOpen=False words[-1].append(v) else: if not gapIsOpen: gaps.append(0) gapIsOpen=True gaps[-1] += 1 if not gapIsOpen: gaps.append(0) assert len(gaps) == len(words) + 1 if isinstance(seq, str): for i in range(len(words)): words[i] = "".join(words[i]) return words, gaps
def string_to_integer(word): """ Converts a string into the integer format expected by the neural network """ integer_list = list() for character in word: integer_list.append(character) for index in range(integer_list.__len__()): current_character = integer_list[index] integer_list[index] = ord(current_character) for index in range(integer_list.__len__()): current_character = integer_list[index] integer_list[index] = current_character - ord('`') while integer_list.__len__() < 16: integer_list.append(0) return integer_list
def shorten(x, length): """ Shorten string x to length, adding '..' if shortened """ if len(x) > (length): return x[:length - 2] + '..' return x
def Right(text, number): """Return the right most characters in the text""" return text[-number:]
def walk_line(strings, max_x, max_y, coordinates, direction, path_char): """ Given some starting points and a direction, find any connected corners in said direction. :param strings string - the text that may contain rectangles. :param max_x int - the boundary/width of the text. :param max_y int - the boundary/height of the text. :param coordinates list[(tuple),...] - List containing starting locations (y, x). :param direction string - "+" or "-" for incrementing/decrmenting x or y depending on path_char. :param path_char string - "|" or "-" the connecting char to look for. :return list[(tuple),...] - List containing any valid corners in the direction specified. """ corner_coords = [] for coords in coordinates: y = coords[0] x = coords[1] in_bounds = True while (in_bounds): # move 'forward' if path_char == "-" and direction == "+": x += 1 elif path_char == "-" and direction == "-": x -= 1 elif path_char == "|" and direction == "+": y += 1 elif path_char == "|" and direction == "-": y -= 1 if x < 0 or x > max_x or y < 0 or y > max_y: in_bounds = False break if strings[y][x] == path_char: continue elif strings[y][x] == "+": corner_coords.append((y, x)) else: break return corner_coords
def _GetStepsAndTests(failed_steps): """Extracts failed steps and tests from failed_steps data structure. Args: failed_steps(TestFailedSteps): Failed steps and test information. Example of a serialized TestFailedSteps: { 'step_a': { 'last_pass': 4, 'tests': { 'test1': { 'last_pass': 4, 'current_failure': 6, 'first_failure': 5 }, 'test2': { 'last_pass': 4, 'current_failure': 6, 'first_failure': 5 } }, 'current_failure': 6, 'first_failure': 5, 'list_isolated_data': [ { 'isolatedserver': 'https://isolateserver.appspot.com', 'namespace': 'default-gzip', 'digest': 'abcd' } ] }, 'step_b': { 'current_failure': 3, 'first_failure': 2, 'last_pass': 1 } } Returns: failed_steps_and_tests: Sorted list of lists of step and test names. Example: [ ['step_a', 'test1'], ['step_a', 'test2'], ['step_b', None] ] """ failed_steps_and_tests = [] if not failed_steps: return failed_steps_and_tests for step_name, step in failed_steps.iteritems(): for test_name in (step.tests or [None]): failed_steps_and_tests.append([step_name, test_name]) return sorted(failed_steps_and_tests)
def listize(obj): """ If obj is iterable and not a string, returns a new list with the same contents. Otherwise, returns a new list with obj as its only element. """ if not isinstance(obj, str): try: return list(obj) except: pass return [obj]
def get_version(data): """ Parse version from changelog written in RST format. """ def all_same(s): return not any(filter(lambda x: x != s[0], s)) def has_digit(s): return any(char.isdigit() for char in s) data = data.splitlines() return next(( v for v, u in zip(data, data[1:]) # v = version, u = underline if len(v) == len(u) and all_same(u) and has_digit(v) and "." in v ))
def string_distance(a: str, b: str): """ Returns the levenshtein distance between two strings, which can be used to compare their similarity [Code source](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py) """ if len(a) < len(b): return string_distance(b, a) if len(b) == 0: return len(a) prow = range(len(b) + 1) for i, c1 in enumerate(a): crow = [i + 1] for j, c2 in enumerate(b): ins = prow[j + 1] + 1 dl = crow[j] + 1 sub = prow[j] + (c1 != c2) crow.append(min(ins, dl, sub)) prow = crow return prow[-1]
def strip_whitespace_from_data(data): """Recursively strips whitespace and removes empty items from lists""" if isinstance(data, str): return data.strip() elif isinstance(data, dict): return {key: strip_whitespace_from_data(value) for key, value in data.items()} elif isinstance(data, list): return list(filter(lambda x: x != '', map(strip_whitespace_from_data, data))) else: return data
def how_many_namefellows(queue: list, person_name: str) -> int: """ :param queue: list - names in the queue. :param person_name: str - name you wish to count or track. :return: int - the number of times the name appears in the queue. """ cnt = 0 for name in queue: if name == person_name: cnt += 1 return cnt
def year_list_to_cite_years(year_list,p_year): """convert year_list into cite_years :param year_list,p_year: :return: cite_years """ year_list_int = [] for s in year_list: try: year_list_int.append(int(s)) except: pass y = [p_year+i for i in range(2021 - p_year + 1)] cite_years = [0 for _ in range(2021 - p_year + 1)] for year in year_list_int: if year >= p_year and year <= 2021: cite_years[year - p_year] += 1 list_return = [y, cite_years] # cite_years = pd.DataFrame(cite_years, # index=y, # columns=['total']) # cite_years = cite_years.T return list_return
def clean_string(string): """Clean a string. Trims whitespace. Parameters ---------- str : str String to be cleaned. Returns ------- string Cleaned string. """ assert isinstance(string, str) clean_str = string.strip() clean_str = clean_str.replace(" ", " ") assert isinstance(clean_str, str) return clean_str
def good_fibonacci(n): """Return pair of Fibonacci numbers, F(n) and F(n-1)""" if n <= 1: return n, 0 a, b = good_fibonacci(n - 1) return a + b, a
def step_forward(position, panel_r, panel_l, connection_map): """ When each character is read from the input, this function is sounded until it reaches the reflect board. This function specifies that at each step I have to go through the index of each page Of the routers to reach the reflect board. :param position: Position of the char in the list. :param panel_r: The list that represents the right side of the router :param panel_l: The list that represents the left side of the router :param connection_map: A dictionary showing which characters are attached to each character on the screen :return: Index of the char in left side of router """ holder1 = panel_r[position] holder2 = connection_map[holder1] holder3 = panel_l.index(holder2) return holder3
def datetime_to_float(datetime): """ SOPC_DateTime* (the number of 100 nanosecond intervals since January 1, 1601) to Python time (the floating point number of seconds since 01/01/1970, see help(time)). """ nsec = datetime[0] # (datetime.date(1970,1,1) - datetime.date(1601,1,1)).total_seconds() * 1000 * 1000 * 10 return (nsec - 116444736000000000)/1e7
def readline_setup(exports): """setup readline completion, if available. :param exports: the namespace to be used for completion :return: True on success """ try: import readline except ImportError: # no completion for you. readline = None return False else: import rlcompleter readline.set_completer( rlcompleter.Completer(namespace=exports).complete) return True
def is_bad_port(port): """ Bad port as per https://fetch.spec.whatwg.org/#port-blocking """ return port in [ 1, # tcpmux 7, # echo 9, # discard 11, # systat 13, # daytime 15, # netstat 17, # qotd 19, # chargen 20, # ftp-data 21, # ftp 22, # ssh 23, # telnet 25, # smtp 37, # time 42, # name 43, # nicname 53, # domain 69, # tftp 77, # priv-rjs 79, # finger 87, # ttylink 95, # supdup 101, # hostriame 102, # iso-tsap 103, # gppitnp 104, # acr-nema 109, # pop2 110, # pop3 111, # sunrpc 113, # auth 115, # sftp 117, # uucp-path 119, # nntp 123, # ntp 135, # loc-srv / epmap 137, # netbios-ns 139, # netbios-ssn 143, # imap2 161, # snmp 179, # bgp 389, # ldap 427, # afp (alternate) 465, # smtp (alternate) 512, # print / exec 513, # login 514, # shell 515, # printer 526, # tempo 530, # courier 531, # chat 532, # netnews 540, # uucp 548, # afp 554, # rtsp 556, # remotefs 563, # nntp+ssl 587, # smtp (outgoing) 601, # syslog-conn 636, # ldap+ssl 993, # ldap+ssl 995, # pop3+ssl 1719, # h323gatestat 1720, # h323hostcall 1723, # pptp 2049, # nfs 3659, # apple-sasl 4045, # lockd 5060, # sip 5061, # sips 6000, # x11 6566, # sane-port 6665, # irc (alternate) 6666, # irc (alternate) 6667, # irc (default) 6668, # irc (alternate) 6669, # irc (alternate) 6697, # irc+tls ]
def e_vect(n, i): """ get a vector of zeros with a one in the i-th position Parameters ---------- n: vector length i: position Returns ------- an array with zeros and 1 in the i-th position """ zeros = [0 for n_i in range(n)] zeros[i] = 1 return zeros
def zoo_om_re_ratio(carbon, d_carbon, ratio, d_ratio): """carbon and d_carbon im moles carbon, ratio - to be changed d_carbon, d_ratio - what changes the ratio""" return (carbon+d_carbon)/(carbon/ratio+d_carbon/d_ratio)
def sumNumber(num): """ Gives the sum of all the positive numbers before input number """ # Used for rank based selection sum_num = 0 for i in range(num+1): sum_num += i return sum_num
def filter_nodes(nodes, env='', roles=None, virt_roles=''): """Returns nodes which fulfill env, roles and virt_roles criteria""" retval = [] if not roles: roles = [] if virt_roles: virt_roles = virt_roles.split(',') for node in nodes: append = True if env and node.get('chef_environment', 'none') != env: append = False if roles: if not set.intersection( set(roles), set([role.split("_")[0] for role in node['roles']])): append = False if virt_roles: # Exclude node in two cases: # * the virtualization role is not in the desired virt_roles # * the virtualization role is not defined for the node AND # 'guest' is a desired virt_role virt_role = node.get('virtualization', {}).get('role') if not virt_role in virt_roles and \ not ('guest' in virt_roles and not virt_role): append = False if append: retval.append(node) return retval
def lower(low, temp): """ :param low: int, the lowest temperature data before :param temp: int, the new temperature data :return: int, the lower one between high and temp, which becomes the lowest temperature """ if temp < low: return temp return low