content
stringlengths
42
6.51k
def recipStep(y, x): """Perform one step of reciprocal algorithm.""" return 2*x - y*(x**2);
def _get_text( row, attr ): """ Get the row from a dataframe """ return "" if type( row[ attr ] ) is float else str( row[ attr ] )
def mask_val(val, width): """mask a value to width bits""" return val & ((1 << width) - 1)
def dictRemove(dict, keys): """ Remove dict values who has a key in keys""" for key in keys: dict.pop(key) return dict
def replace_forward_slash(file_name): """ This method takes a string representing a file name and replaces forward slashes with ":" This approach is consistent with how other clients deal with attempts to upload files with forward slashes in the name. """ return file_name.replace("/", ":")
def champion_dictionary(obj): """Converts champion.json to a dictionary that is useful to us.""" champions = {} for champion in obj["data"]: name = champion.lower() champions[int(obj["data"][champion]["key"])] = name return champions
def compact_address_range(r): """ Compact address ranges Input: list of pairs of address ranges Output: (nothing) Returns: compacted list of pairs of address ranges """ x = list(r[:]) x.sort() j = 0 y = [] y.append(list(x[0])) for i in range(len(x) - 1): if (x[i][-1] == x[i + 1][0]): y[j][-1] = x[i + 1][-1] else: y.append(list(x[i + 1])) j = j + 1 return y
def get_pi0(pv, lambdas): """ Compute Storey's C{pi0} from p-values C{pv} and C{lambda}. this function is equivalent to:: m = len(pv) return [sum(p >= l for p in pv)/((1.0-l) * m) for l in lambdas] but the above is C{O(m*n)}, while it needs only be C{O(m+n) (n = len(lambdas))} @type pv: list @param pv: B{SORTED} p-values vector @type lambdas: list @param lambdas: B{SORTED} lambda values vector @rtype: list @return: estimated proportion of null hypotheses C{pi0} for each lambda """ m = len(pv) i = m - 1 pi0 = [] for l in reversed(lambdas): while i >= 0 and pv[i] >= l: i -= 1 pi0.append((m-i-1)/((1.0-l)*m)) pi0.reverse() return pi0
def get_min_temp(results): """Returns the minimum temp for the given hourly weather objects.""" min_temp = 100000 for forecast in results: min_temp = min(forecast['temp'], min_temp) return min_temp
def get_split_ind(seq, N): """seq is a list of words. Return the index into seq such that len(' '.join(seq[:ind])<=N """ sLen = 0 # todo: use Alex's xrange pattern from the cbook for efficiency for (word, ind) in zip(seq, list(range(len(seq)))): sLen += len(word) + 1 # +1 to account for the len(' ') if sLen >= N: return ind return len(seq)
def readable_list(elements, liaison='and'): """ Creates a readable sentence by joining elements of a list Args: elements (:obj:`list` of :obj:`str`): elements to join together liaison (`str`, optional, 'and'): liaison to use to join elements Returns: `str` A human readable sentence joining all elements """ if not elements: return "" if len(elements) == 1: return str(elements[0]) if len(elements) == 2: return '{} {} {}'.format(elements[0], liaison, elements[1]) # "Oxford comma innit" -Zack, France return "{}, {} {}".format( ', '.join((str(e) for e in elements[:-1])), liaison, elements[-1])
def s_(xT): # pragma: no cover """ derivative of saturation vapor pressure: kPa / C Paw U and Gao (1987) Ag For Met 43:121-145 Applicaitons of solutions to non-linear energy budget equations :param xT - temperature (C): :return: """ return (42.22 + 2 * 1.675 * xT + 3 * 0.01408 * xT ** 2 + 4 * 0.0005818 * xT ** 3) / 1000
def name_test(item): """ used for pytest verbose output """ p = item['params'] return f"{p['peer_device']} role={p['role']} via={p['peer_ip']}"
def team_distance(str): """ function to weight teams distance from tournament for use in sorting teams prior to scheduling; higher weighted numbers give a team's request priority. team = a str with city and state (ex. 'Charleston, SC') current weights are setup with Charleston, SC as the base city returns an integer state abbrevations courtesy of Jeff Paine, https://gist.github.com/JeffPaine/3083347 """ states = {"AL": 2, "AK": 10, "AZ": 6, "AR": 4, "CA": 6, "CO": 6, "CT": 5, "DC": 3, "DE": 3, "FL": 3, "GA": 1, "HI": 10, "ID": 6, "IL": 4, "IN": 4, "IA": 5, "KS": 5, "KY": 2, "LA": 4, "ME": 6, "MD": 3, "MA": 5, "MI": 5, "MN": 6, "MS": 3, "MO": 4, "MT": 6, "NE": 5, "NV": 6, "NH": 5, "NJ": 4, "NM": 6, "NY": 5, "NC": 1, "ND": 6, "OH": 4, "OK": 5, "OR": 6, "PA": 4, "RI": 5, "SC": 0, "SD": 6, "TN": 2, "TX": 5, "UT": 6, "VT": 6, "VA": 2, "WA": 6, "WV": 3, "WI": 5, "WY": 6} if str not in states: return False else: return states.get(str)
def compute_sum(n, total): """ Compute the total sum range 0 to n """ # print(n) # base case, if you reach n is 0 then you want to return it print(total[0]) if n == 0: return 0 total[0] = total[0] + compute_sum(n-1, total) # else the previous value + (n - 1) # return n + compute_sum(n-1)
def pos_to_index(mouse_col, mouse_row, labels_positions): """ convert label's position to it's index """ if 550 <= mouse_row <= 600 and 0 <= mouse_col <= 200: return 'mode_changed' if 580 <= mouse_row <= 600 and 430 <= mouse_col <= 440: return 'back_changed-' if 580 <= mouse_row <= 600 and 550 <= mouse_col <= 560: return 'back_changed+' if 560 <= mouse_row < 580 and 430 <= mouse_col <= 440: return 'life_changed-' if 560 <= mouse_row < 580 and 550 <= mouse_col <= 560: return 'life_changed+' if 198 <= mouse_col <= 388: for i in range(len(labels_positions)): if labels_positions[i] <= mouse_row <= labels_positions[i] + 13: return i return 'new_chosen'
def drop_hash_comment(line): """ Getting a line with '#' comment it drops the comment. Note that JSON does not support comments, but gyp with its JSON-like syntax (really just a Python dict) does support comments. Should this func be aware of hashes in double quotes? Atm it's not. """ hash_index = line.find('#') # drops suffix while keeping trailing \n def drop_line_suffix(line, index): trailing_whitespace = line[len(line.rstrip()):] remaining_line = line[0:index] return remaining_line + trailing_whitespace return line if hash_index == -1 else drop_line_suffix(line,hash_index)
def night_to_month(night): """ Trivial function that returns the month portion of a night. Can be given a string or int. Args: night, int or str. The night you want the month of. Returns: str. The zero-padded (length two) string representation of the month corresponding to the input month. """ return str(night)[:-2]
def create_graphics(graphics: list) -> str: """Function to transform a list of graphics dicts (with lines and fill rectangles) into a PDF stream, ready to be added to a PDF page stream. Args: graphics (list): list of graphics dicts. Returns: str: a PDF stream containing the passed graphics. """ last_fill = last_color = last_line_width = last_line_style = None stream = '' for g in graphics: if g['type'] == 'fill': if g['color'] != last_fill: last_fill = g['color'] stream += ' ' + str(last_fill) stream += ' {} {} {} {} re F'.format( round(g['x'], 3), round(g['y'], 3), round(g['width'], 3), round(g['height'], 3) ) if g['type'] == 'line': if g['color'] != last_color: last_color = g['color'] stream += ' ' + str(last_color) if g['width'] != last_line_width: last_line_width = g['width'] stream += ' {} w'.format(round(g['width'], 3)) if g['style'] == 'dashed': line_style = ' 0 J [{} {}] 0 d'.format(round(g['width']*3, 3), round(g['width']*1.5, 3)) elif g['style'] == 'dotted': line_style = ' 1 J [0 {}] {} d'.format(round(g['width']*2, 3), round(g['width'], 3)*0.5) elif g['style'] == 'solid': line_style = ' 0 J [] 0 d' else: raise Exception( 'line style should be dotted, dashed or solid: {}' .format(g['style']) ) if line_style != last_line_style: last_line_style = line_style stream += line_style stream += ' {} {} m {} {} l S'.format( round(g['x1'], 3), round(g['y1'], 3), round(g['x2'], 3), round(g['y2'], 3), ) if stream != '': stream = ' q' + stream + ' Q' return stream
def TransformEventData(event_data): """Takes Event object to new specification.""" new_event_data = {} new_event_data['summary'] = event_data['summary'] new_event_data['description'] = event_data['description'] # Where new_event_data['location'] = event_data['location'] # When start = event_data['when:from'] if start.endswith('Z'): new_event_data['start'] = {'dateTime': start} else: new_event_data['start'] = {'date': start} end = event_data['when:to'] if end.endswith('Z'): new_event_data['end'] = {'dateTime': end} else: new_event_data['end'] = {'date': end} return new_event_data
def parse_vertex(text): """Parse text chunk specifying single vertex. Possible formats: vertex index vertex index / texture index vertex index / texture index / normal index vertex index / / normal index """ v = 0 t = 0 n = 0 chunks = text.split("/") v = int(chunks[0]) if len(chunks) > 1: if chunks[1]: t = int(chunks[1]) if len(chunks) > 2: if chunks[2]: n = int(chunks[2]) return { 'v': v, 't': t, 'n': n }
def tokenize_line(line): """ Tokenize a line: * split tokens on whitespace * treat quoted strings as a single token * drop comments * handle escaped spaces and comment delimiters """ ret = [] escape = False quote = False tokbuf = "" ll = list(line) while len(ll) > 0: c = ll.pop(0) if c.isspace(): if not quote and not escape: # end of token if len(tokbuf) > 0: ret.append(tokbuf) tokbuf = "" elif quote: # in quotes tokbuf += c elif escape: # escaped space tokbuf += c escape = False else: tokbuf = "" continue if c == '\\': escape = True continue elif c == '"': if not escape: if quote: # end of quote ret.append(tokbuf) tokbuf = "" quote = False continue else: # beginning of quote quote = True continue elif c == ';': # if there is a ";" in a quoted string it should be treated as valid. # DMARC records as an example. if not escape and quote is False: # comment ret.append(tokbuf) tokbuf = "" break # normal character tokbuf += c escape = False if len(tokbuf.strip(" ").strip("\n")) > 0: ret.append(tokbuf) return ret
def _tuples_native(S, k): """ Return a list of all `k`-tuples of elements of a given set ``S``. This is a helper method used in :meth:`tuples`. It returns the same as ``tuples(S, k, algorithm="native")``. EXAMPLES:: sage: S = [1,2,2] sage: from sage.combinat.combinat import _tuples_native sage: _tuples_native(S,2) [(1, 1), (2, 1), (2, 1), (1, 2), (2, 2), (2, 2), (1, 2), (2, 2), (2, 2)] """ if k <= 0: return [()] if k == 1: return [(x,) for x in S] ans = [] for s in S: for x in _tuples_native(S, k-1): y = list(x) y.append(s) ans.append(tuple(y)) return ans
def remove_whitespace(s): """Remove excess whitespace including newlines from string """ words = s.split() # Split on whitespace return ' '.join(words)
def colorCalculator(hex): """ Converts an RGB hex string into a tuple of (R, G, B) values from 0 to 1. Args: hex (str): hex value of color. Returns: tuple: tuple (R, G, B) of values from 0 to 1. """ # check for pound-sign if hex[0] == "#": hex = hex[1:] # first, convert hex to decimal r = hex[0:2] g = hex[2:4] b = hex[4:6] colors = [] for color in (r, g, b): dec = int(color, 16) colors.append(dec) print("converted " + hex + " to RGB:") print(colors) colors.append(255) for i in range(4): colors[i] /= 255 print(tuple(colors)) return tuple(colors)
def get_taxonomies_by_meta(data): """ Reads from the dict via meta -> taxonomies """ return data["meta"]["taxonomies"]
def convert_gdml_unit(unit): """Convert a GDML unit to MCNP system""" units = {"m": 1E+02, "cm": 1., "mm": 1E-01, "g/cm3": 1.} return units[unit]
def add_text_col(example: dict) -> dict: """constructs text column to news article""" example["text"] = "" if example["Heading"].strip(" "): example["text"] = example["Heading"] if example["SubHeading"].strip(" "): example["text"] += f'\n {example["SubHeading"]}' # if example["PublishDate"]: # example["text"] += f'\n {example["PublishDate"]}' # if example["Paragraph"].strip(" "): # example["text"] += f'\n\n {example["Paragraph"]}' if example["BodyText"].strip(" "): example["text"] += f'\n\n {example["BodyText"]}' return example
def is_sorted(arr): """ assert array is sorted """ return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
def is_none_or_empty(arg): """ purpose: check if the arg is either None or an empty string arguments: arg: varies return value: Boolean """ try: return arg is None or arg == "" except Exception: return False
def NDD_eval(xi, dd, xd): """Evaluar el polinomio interpolante. Args: dd : array Diferencias divididas xi : list or array Valores donde quiero evaluar al polinomio xd : list or array Valores X interpolados Returns: y : list or array Valores del polinomio en x """ #N = len(dd) #print(f"P = a[{N-1}]") #for i in range(N-2, -1, -1): #print(f"P = a[{i}] + p*(x-x[{i}])") N = len(dd) y = [] for xx in xi: p = dd[N-1] for i in range(N-2, -1, -1): p = dd[i] + p*(xx-xd[i]) y.append(p) return y
def count_padding_bases(seq1, seq2): """Count the number of bases padded to report indels in .vcf Args: seq1 (str): REF in .vcf seq2 (str): ALT in .vcf Returns: n (int): Examples: REF ALT GCG GCGCG By 'left-alignment', REF and ATL are alignmed: GCG ||| GCGCG The first 3 bases are left-aligned. In this case, 3 will be returned """ if len(seq1) <= len(seq2): shorter, longer = seq1, seq2 else: shorter, longer = seq2, seq1 n = 0 for base1, base2 in zip(shorter, longer[: len(shorter)]): if base1 == base2: n += 1 else: break return n
def check_redirect_uris(uris, client_type=None): """ This function checks all return uris provided and tries to deduce as what type of client we should register. :param uris: The redirect URIs to check. :type uris: list :param client_type: An indicator of which client type you are expecting to be used. If this does not match the deduced type, an error will be raised. :type client_type: str :returns: The deduced client type. :rtype: str :raises ValueError: An error occured while checking the redirect uris. .. versionadded:: 1.0 """ if client_type not in [None, 'native', 'web']: raise ValueError('Invalid client type indicator used') if not isinstance(uris, list): raise ValueError('uris needs to be a list of strings') if len(uris) < 1: raise ValueError('At least one return URI needs to be provided') for uri in uris: if uri.startswith('https://'): if client_type == 'native': raise ValueError('https url with native client') client_type = 'web' elif uri.startswith('http://localhost'): if client_type == 'web': raise ValueError('http://localhost url with web client') client_type = 'native' else: if (uri.startswith('http://') and not uri.startswith('http://localhost')): raise ValueError('http:// url with non-localhost is illegal') else: raise ValueError('Invalid uri provided: %s' % uri) return client_type
def string_to_env(string: str): """ Overview: Turn string ``KEY=VALUE`` to key-value tuple. Arguments: - string (:obj:`str`): Original key-value string. Returns: - (key, value): key and value Examples:: >>> from pyspj.utils import string_to_env >>> string_to_env('THIS=1') ('THIS', '1') >>> string_to_env('THIS=1=2') ('THIS', '1=2') """ _name, _value = string.split('=', maxsplit=1) return _name, _value
def recursive_merge(source, destination): """ Recursively merge dictionary in source with dictionary in desination. Return the merged dictionaries. Stolen from: https://stackoverflow.com/questions/20656135/python-deep-merge-dictionary-data """ for key, value in source.items(): if isinstance(value, dict): # get node or create one node = destination.setdefault(key, {}) recursive_merge(value, node) else: destination[key] = value return destination
def RemoveBadCarac(mot): """ remove a list of bad carac in a word """ bad_carac = [",", "*", "'", "]", "[", "-", "!", "?", " ", '', "(", ")", "//", ".", '-'] mot_propre = list() for carac in mot: if carac not in bad_carac and not carac.isnumeric(): mot_propre.append(carac) else: mot_propre.append("") #return mot return("".join(mot_propre))
def render_build_args(options, ns): """Get docker build args dict, rendering any templated args. Args: options (dict): The dictionary for a given image from chartpress.yaml. Fields in `options['buildArgs']` will be rendered and returned, if defined. ns (dict): the namespace used when rendering templated arguments """ build_args = options.get('buildArgs', {}) for key, value in build_args.items(): build_args[key] = value.format(**ns) return build_args
def store(value=None, addr=None, heap=None): """Symbolic accessor for the store command""" return '!', value, addr, heap
def split_docker_domain(name): """Split Docker image name to domain and remainder part. Ported from https://github.com/distribution/distribution/blob/v2.7.1/reference/normalize.go#L62-L76. Args: name (str): Docker image name. Returns: str: Docker registry domain. str: Remainder part. """ legacy_default_domain = 'index.docker.io' default_domain = 'docker.io' i = name.find('/') domain, remainder = '', '' if i == -1 or ('.' not in name[:i] and ':' not in name[:i] and name[:i] != 'localhost'): domain, remainder = default_domain, name else: domain, remainder = name[:i], name[i + 1:] if domain == legacy_default_domain: domain = default_domain if domain == default_domain and '/' not in remainder: remainder = 'library/{}'.format(remainder) return domain, remainder
def cpp_escape_name(name): """Escape package name to be CPP macro safe.""" return name.replace("-", "_")
def is_local(path: str) -> str: """Return valid URL path for file Args: path (str): normal path or URL Returns: str: Modified file path if local file Returns path as it is if URL """ import os URL = path if os.path.exists(path) or path.startswith("file"): if not URL.startswith("file"): URL = f"file://{URL}" return URL
def get_iterable(x): """Helper function to ensure iterability.""" if isinstance(x, str): return (x,) else: try: iter(x) except TypeError: return (x,) return x
def is_fragment(href): """Return True if href is a fragment else False""" is_fragment = False try: if href[0] == '#': is_fragment = True except IndexError: is_fragment = False return is_fragment
def merge_sorted_lists( l1, l2): """ :param l1: ListNode 1 head :param l2: ListNode 2 head :return: merged L head """ if not l1 or not l2: return l1 or l2 if l1.val <= l2.val: main = l1 sub = l2 else: main = l2 sub = l1 last = main while sub and last.next: if last.next.val <= sub.val: pass else: temp = last.next last.next = sub sub = temp last = last.next last.next = sub return main
def _quick_sort_in(input_data): """ Intern method for quicksort """ if input_data == []: return [] else: pivot = input_data[0] first = _quick_sort_in([x for x in input_data[1:] if x < pivot]) second = _quick_sort_in([x for x in input_data[1:] if x > pivot]) return first + [pivot] + second
def table_log_format(name, timestamp, data): """ Return a formatted string for use in the log""" return str(str(name) + '&' + str(timestamp) + '->[' + str(data) + ']')
def _str_date(time): """ Transfer date to str. Args: time(datetime.datetime): time input. """ return str(time.date()) if time else None
def md(pArray1, pArray2, pFunc, axis=0): """ Map _by dot product_ """ if bool(axis): pArray1, pArray2 = pArray1.T, pArray2.T iRow1 = len(pArray1) iRow2 = len(pArray2) assert(iRow1 == iRow2) aOut = [] for i, item in enumerate(pArray1): aOut.append(pFunc(item, pArray2[i])) return aOut
def _get_quote_state(token, quote_char): """ the goal of this block is to determine if the quoted string is unterminated in which case it needs to be put back together """ # the char before the current one, used to see if # the current character is escaped prev_char = None for idx, cur_char in enumerate(token): if idx > 0: prev_char = token[idx - 1] if cur_char in "\"'" and prev_char != "\\": if quote_char: if cur_char == quote_char: quote_char = None else: quote_char = cur_char return quote_char
def sum_2_cpdicts(cpdict_a,cpdict_b): """ Sum 2 dicts of cpdict and store the result in the second parameter """ for item in cpdict_a.keys(): if item not in cpdict_b.keys(): cpdict_b[item] = dict(cpdict_a[item]) else: for chords in cpdict_a[item].keys(): if chords not in cpdict_b[item].keys(): cpdict_b[item][chords] = cpdict_a[item][chords] else: cpdict_b[item][chords] += cpdict_a[item][chords] return cpdict_b
def solution(S): # O(N) """ Given a string S of upper case characters, from which you have to retrieve the 7 letters: "B", "A", "L", "L" "O", "O", "N" Return how many times you can retrieve these characters from string S. >>> solution('AGEASEBESLOLOBN') 1 >>> solution('AGEASEBESLOLOBNDSOENOLBOLVA') 2 >>> solution('XEBEALPLOWQOA') 0 """ characters = { 'B': 0, 'A': 0, 'L': 0, 'O': 0, 'N': 0 } # O(1) occurences = { 'B': 1, 'A': 1, 'L': 2, 'O': 2, 'N': 1 } # O(1) keys = characters.keys() # O(1) for letter in S: # O(N) if letter in keys: # O(1) characters[letter] += 1 # O(1) num_moves = float('inf') # O(1) for key in keys: # O(1) move = characters[key] // occurences[key] # O(1) num_moves = min(num_moves, move) # O(1) return num_moves # O(1)
def toansi(text): """ Encode special characters """ trans = {'{': r'\{', '}': r'\}', '\\': r'\\', '|': r'\|', } out = '' for char in text: if char in trans: out += trans[char] elif ord(char) < 127: out += char else: out += r"\'%x" % ord(char) return out
def start_new_game(player1, player2): """ Creates and returns a new game configuration. """ board = [['-']*3 for _ in range(3)] game = { 'player1': player1, 'player2': player2, 'board': board, 'next_turn': player1, 'winner': None } return game
def name_score(name: str) -> int: """Get the score of the input name.""" return sum(ord(char) - 64 for char in name)
def _PortValue(value): """Returns True if port value is an int within range or 'default'.""" try: return value == 'default' or (1 <= int(value) <= 65535) except ValueError: return False
def get_alias_from_index(index_name): """ The indexes are named as `alias_suffix` """ return index_name.split("_",1)[0]
def pick_all(keys, dict): """Similar to pick except that this one includes a key: undefined pair for properties that don't exist""" picked_dict = {} for k in keys: picked_dict[k] = None if k in dict: picked_dict[k] = dict[k] return picked_dict
def update_dictionary(dictionary, key, value): """ Add the key-value pair to the dictionary and return the dictionary. :dictionary: dict object :key: String (e.g. module name) :value: Integer (e.g. line number) :returns: dict object """ if key not in dictionary: dictionary[key] = [value] else: # The same key can appear on multiple lines if value not in dictionary[key]: dictionary[key].append(value) return dictionary
def split_virtual_offset(virtual_offset): """Divides a 64-bit BGZF virtual offset into block start & within block offsets. >>> (100000, 0) == split_virtual_offset(6553600000) True >>> (100000, 10) == split_virtual_offset(6553600010) True """ start = virtual_offset >> 16 return start, virtual_offset ^ (start << 16)
def calculateAccuracy(tn, fp, fn, tp): """ return the accuracy based on the confusion matrix values :param tn: Quantity of True negative :param fp: Quantity of False positive :param fn: Quantity of False negative :param tp: Quantity of True positive :type tn: int - required :type fp: int - required :type fn: int - required :type tp: int - required :return: The accuracy value :rtype: Float """ acc = (tp + tn) / (tp + tn + fp + fn) return acc
def basic_open(file): """Open and read a file.""" with open(file, 'r', encoding="utf=8") as f: f = f.readlines() return f
def from_sql(row): """Translates an SQLAlchemy model instance into a dictionary.""" if not row: return None data = row.__dict__.copy() data['id'] = row.id data.pop('_sa_instance_state') return data
def escapeDoubleQuoteInSQLString(string, forceDoubleQuote=True): """ Accept true database name, schema name, table name, escape the double quote inside the name, add enclosing double quote by default. """ string = string.replace('"', '""') if forceDoubleQuote: string = '"' + string + '"' return string
def _get_edges(value, last_value, mask): """ Given two integer values representing a current and a past value, and a bit mask, this function will return two integer values representing the bits with rising (re) and falling (fe) edges. """ changed = value ^ last_value re = changed & value & mask fe = changed & ~value & mask return re, fe
def decode_punycode(thebytes: bytes): """Decodes the bytes string using Punycode. Example: >>> encode_punycode('hello')\n b'hello-' >>> decode_punycode(b'hello-')\n 'hello' """ import codecs if isinstance(thebytes, bytes): temp_obj = thebytes return codecs.decode(temp_obj, "punycode")
def check_input(s): """ This function checks the input is in correct format or not :param s: The input string of each row :return: (bool) If the input format is correct """ for i in range(len(s)): if i % 2 == 1 and s[i] != ' ': return True elif len(s) != 7: return True elif i % 2 == 0 and s[i].isalpha() is False: return True
def hard_threshold(x): """ Returns an hard threshold which returns 0 if sign = -1 and 1 otherwise. This let the combination of multiple perceptron with uniform input :param x: + or - 1 :return: 1 for positive, 0 for negative """ return 0 if x <= 0.5 else 1
def is_criticality_balanced(temperature: int, neutrons_emitted: int) -> bool: """ :param temperature: int - Temperatur of the reactor core :param neutrons_emitted: int - Neutrons emitted per second :return: boolean True if conditions met, False if not A reactor is said to be critical if it satisfies the following conditions: - The temperature is less than 800. - The number of neutrons emitted per second is greater than 500. - The product of temperature and neutrons emitted per second is less than 500000. """ return all((temperature < 800, neutrons_emitted > 500, temperature * neutrons_emitted < 500_000))
def get_headers(token): """Return HTTP Token Auth header.""" return {"x-rh-identity": token}
def get_simulation_length_info( units, prop_freq, coord_freq, run_length, steps_per_sweep=None, block_avg_freq=None, ): """Get the Simulation_Length_Info section of the input file Parameters ---------- units : string 'minutes', 'steps', or 'sweeps' prop_freq : int frequency of writing property info coord_freq : int frequency of writing coordinates to file run_length : int number of (units) to run the simulation steps_per_sweep : int, optional number of steps in a MC sweep block_avg_freq : int, optional write properties as block averages, averaged over block_avg_freq (units) """ valid_units = ["minutes", "steps", "sweeps"] if units not in valid_units: raise ValueError( "Invalid units specified {} Allowable options " "include {}".format(units, valid_units) ) if not isinstance(prop_freq, int): raise ValueError("prop_freq must be an integer") if not isinstance(coord_freq, int): raise ValueError("coord_freq must be an integer") if not isinstance(run_length, int): raise ValueError("run_length must be an integer") if steps_per_sweep is not None: if not isinstance(steps_per_sweep, int): raise ValueError("steps_per_sweep must be an integer") if block_avg_freq is not None: if not isinstance(block_avg_freq, int): raise ValueError("block_avg_freq must be an integer") inp_data = """ # Simulation_Length_Info units {units} prop_freq {prop_freq} coord_freq {coord_freq} run {run_length}""".format( units=units, prop_freq=prop_freq, coord_freq=coord_freq, run_length=run_length, ) if steps_per_sweep is not None: inp_data += """ steps_per_sweep {steps_per_sweep} """.format( steps_per_sweep=steps_per_sweep ) if block_avg_freq is not None: inp_data += """ block_averages {block_avg_freq} """.format( block_avg_freq=block_avg_freq ) inp_data += """ !------------------------------------------------------------------------------ """ return inp_data
def to_currency(cents: int) -> str: """Convert a given number of cent into a string formated dollar format Parameters ---------- cents : int Number of cents that needs to be converted Returns ------- str Formated dollar amount """ return f"${cents / 100:.2f}"
def contrasting_hex_color(hex_str): """ Pass string with hash sign of RGB hex digits. Returns white or black hex code contrasting color passed. """ (r, g, b) = (hex_str[1:3], hex_str[3:5], hex_str[5:]) return '#000000' if 1 - (int(r, 16) * 0.299 + int(g, 16) * 0.587 + int(b, 16) * 0.114) / 255 < 0.5 else '#ffffff'
def create_rules(lines): """ Given the list of line rules, create the rules dictionary. """ rules = dict() for line in lines: sline = line.split() rules[sline[0]] = sline[-1] return rules
def convertFloat(s): """Tells if a string can be converted to float and converts it Args: s : str Returns: s : str Standardized token 'FLOAT' if s can be turned to an float, s otherwise""" try: float(s) return "FLOAT" except: return s
def format_sizeof(num, suffix='bytes'): """ Readable size format, courtesy of Sridhar Ratnakumar """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1000.0: return '{0:3.1f}{1}{2}'.format(num, unit, suffix) num /= 1000.0 return '{0:.1f}Y{1}'.format(num, suffix)
def count_val_size_in_dict(result): """ expects a dict with keys which map to lists sums the size of all lists in the dict @param result: a dict where each key maps to a list @return: the summed size of all lists """ amount = 0 for k, values in result.items(): amount += len(values) return amount
def check_placement(ship_placement, ship_number): """Returns true if ship placed inside the board""" ships_position_check = [0,10,20,30,40,50,60,70,80,90] if ship_placement > 99 or ship_placement < 0: return False if ship_number in [2,3,4]: if ship_placement in ships_position_check: return False return True
def shorten_str(text: str, width: int = 30, suffix: str = "[...]") -> str: """Custom string shortening (`textwrap.shorten` collapses whitespace).""" if len(text) <= width: return text else: return text[: width - len(suffix)] + suffix
def validate_http_request(request): """ Check if request is a valid HTTP request and returns TRUE / FALSE and the requested URL """ request = request.decode() if request[0:3] == "GET": if request[0:14] == "GET / HTTP/1.1": return "GET", True, " " else: return "GET", True, request[4:request.find("HTTP/1.1")] if request[0:4] == "POST": if request[0:14] == "POST / HTTP/1.1": return "POST", True, " " else: return "POST", True, request else: return None, False, ""
def ID2ccc(ID, device_number=0): """ Turns a control ID into a combination of channel + cc. >>> ID2ccc(0) 1, 0 >>> ID2ccc(1) 1, 1 >>> ID2ccc(127) 1, 127 >>> ID2ccc(128) 2, 0 >>> ID2ccc(2047) 16, 127 """ ID -= device_number * 128 * 16 ID %= 128 * 16 return (ID // 128) + 1, ID % 128
def addNums(a, b): """ Adds two numbers and returns the result. """ c = a + b return c
def process_line(line): """ Split a Line in key, value pairs """ key, value = line.partition("=")[::2] return key, value.rstrip()
def divide(x: float, y: float) -> float: """Divide :math:`x` by :math:`y` Arguments --------- x : float First number y : float Second number. Raises ------ ZeroDivisionError: If the denominator is zero Returns ------- float x / y """ if abs(y) < 1e-12: raise ZeroDivisionError("Cannot divede by zero") return x / y
def markdown_image(url): """Markdown image markup for `url`.""" return '![]({})'.format(url)
def k_to_c(tempk): """ Parameters Temp (K) Returns Temp(C) """ tempc = tempk - 273.15 return tempc
def divide_range(total_size: int, chunk_size: int = 1000): """ Break down the range into chunks of specific size. Args: total_size: The total size of the range chunk_size: The size of each chunk return: list_ranges: A list of chunked range objects """ num_thousand, remainder = divmod(total_size, chunk_size) list_ranges = [] # Create a list of ranges for i in range(num_thousand): list_ranges.append(range(i*chunk_size, (i+1)*chunk_size)) if remainder > 0: final_range = range(num_thousand*chunk_size, num_thousand*chunk_size+remainder) list_ranges.append(final_range) return list_ranges
def split_16bit(_16bit): """ Split a 16-bit value into a list of 8-bit values in little endian format. """ return [_16bit & 0xFF, (_16bit >> 7) & 0xFF]
def sliding_windows(periods): """ Split into training and test sets, augment the data. """ x = [] y = [] for period in periods[:-3]: p_index = periods.index(period) x.append([]) x[-1].append([period[-2], period[-1]]) x[-1].append([periods[p_index + 1][-2], periods[p_index + 1][-1]]) x[-1].append([periods[p_index + 2][-2], periods[p_index + 2][-1]]) y.append([periods[p_index + 3][-2], periods[p_index + 3][-1]]) assert len(x) == len(y) return x, y
def minimum(a, b, *others): """The minimum value of all arguments""" return min(a, b, *others)
def eat_blank(Q): """Discards a sequence of blank chars at the top of Q""" n = len(Q) while Q: if Q[0] in ' \t\n': Q.popleft() else: break return n - len(Q)
def get_parents_iterative(child, child_2_parent_dict): """ par = {"C22":{"C1"}, "C21":{"C1"}, "C1":{"P1"}} get_parents_iterative("C22", par) """ if child not in child_2_parent_dict: return [] # important to set() otherwise parent is updated in orig object all_parents = set(child_2_parent_dict[child]) current_parents = set(all_parents) while len(current_parents) > 0: new_parents = set() for parent in current_parents: if parent in child_2_parent_dict: temp_parents = child_2_parent_dict[parent].difference(all_parents) all_parents.update(temp_parents) new_parents.update(temp_parents) current_parents = new_parents return all_parents
def mm(mm): """Convert from millimeter values to rounded points >>> mm(210) 595 >>> mm(297) 842 """ return int(round(mm * 72 * 0.039370))
def _tester(func, *args): """ Tests function ``func`` on arguments and returns first positive. >>> _tester(lambda x: x%3 == 0, 1, 2, 3, 4, 5, 6) 3 >>> _tester(lambda x: x%3 == 0, 1, 2) None :param func: function(arg)->boolean :param args: other arguments :return: something or none """ for arg in args: if arg is not None and func(arg): return arg return None
def updated_dict(dic1, dic2): """Return dic1 updated with dic2 if dic2 is not None. Example ------- >>> my_dict = updated_dict({"size": 7, "color": "r"}, some_defaults_dict) """ if dic2 is not None: dic1.update(dic2) return dic1
def perm_to_pattern(P,index=0): """ Convert the permutation P into a permutation """ if index not in (0,1): raise Exception("index must be 0 or 1") S = sorted(set(P)) D = {v:rank for rank,v in enumerate(S,index)} return tuple([D[p] for p in P])
def convert_time_format(date_format): """ helper function to convert the data format that is used by the Cisco EoX API :param date_format: :return: """ if date_format == "YYYY-MM-DD": return "%Y-%m-%d" return "%Y-%m-%d"
def UC_V(V_mm, A_catch, outUnits): """ Convert volume from mm to m^3 or litres Args: V_mm: Float. Depth in mm outUnits: Str. 'm3' or 'l' A_catch: Float. Catchment area in km2 Returns: Float. Volume in specified units. """ factorDict = {'m3':10**3, 'l':10**6} V = V_mm * factorDict[outUnits] * A_catch return V
def find_payment(loan: float, rate: float, m: int): """ Returns the monthly payment for a mortgage of size loan at a monthly rate of r for m months""" return loan * ((rate * (1 + rate) ** m) / ((1 + rate) ** m - 1))
def _build_message(input_table, output_table, current_date): """Returns a JSON object containing the values of the input parameters. Args: input_table: A string containing the BQ table to read from output_table: A string containing the BQ table to write to current_date: The processing date to suffix the table names Returns: JSON oject containing the input data """ msg = { 'bq_input_to_predict_table': input_table, 'bq_output_table': output_table, 'date': current_date } return msg
def LoadPins(mapping,inp): """Organizes an input into a pin mapping dict mapping <list>, ['IA','IB'] inp <dict>, <list>, <int> {'IA':1,'IB':2}, [1,2] """ if type(inp) is int and len(mapping) == 1: return {mapping[0]:inp} elif type(inp) is list and len(mapping) == len(inp): o = {} for i in range(len(inp)): o[mapping[i]] = inp[i] return o elif type(inp) is dict: return inp else: print('Invalid input for pins:',inp,type(inp)) print('Expected:',mapping) return {}