content
stringlengths
42
6.51k
def flatten(lst): """Flat list out of list of lists.""" return [item for sublist in lst for item in sublist]
def col(dict_2d, col_key): """ returns a dict of the contents of column **col_key** of dict_2d """ column = {} row_keys = dict_2d.keys() for r in row_keys: column[r] = dict_2d[r][col_key] return column
def jaccard(a, b): """ Calculate the jaccard coefficient of two sets. """ (a, b) = (set(a), set(b)) n = len(a & b) # intersection d = len(a | b) # union if d == 0: return 1 return n / d
def normalize_dataset(performance: list, variance: float, median: float): """Normalizes the performance obtain in a given dataset""" return [(p - median) / variance for p in performance]
def trunc(s, length): """Truncate a string to a given length. The string is truncated by cutting off the last (length-4) characters and replacing them with ' ...' """ if s and len(s) > length: return s[:length - 4] + ' ...' return s or ''
def run_maze(maze, i, j, solutions): """ This method is recursive method which starts from i and j and goes with 4 direction option up, down, left, right if path found to destination it breaks and return True otherwise False Parameters: maze(2D matrix) : maze i, j : coordinates of matrix solutions(2D matrix) : solutions Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == j == (size - 1): solutions[i][j] = 1 return True lower_flag = (not (i < 0)) and (not (j < 0)) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (not (solutions[i][j])) and (not (maze[i][j])) if block_flag: # check visited solutions[i][j] = 1 # check for directions if ( run_maze(maze, i + 1, j, solutions) or run_maze(maze, i, j + 1, solutions) or run_maze(maze, i - 1, j, solutions) or run_maze(maze, i, j - 1, solutions) ): return True solutions[i][j] = 0 return False
def _tags_arg(string): """Pulls out primary tag (first tag) from the others""" tags = string.split(',') return (tags[0], set(tags[1:]))
def _any_none(*args): """Returns a boolean indicating if any argument is None""" for arg in args: if arg is None: return True return False
def clean_sequence(seq): """Clean up provided sequence by removing whitespace.""" return seq.replace(' ', '')
def convert_column_to_stat_var(column, features): """Converts input CSV column name to Statistical Variable DCID.""" s = column.split('!!') sv = [] base = False for p in s: # Set base SV for special cases if not base and 'base' in features: if p in features['base']: sv = [features['base'][p]] + sv base = True # Skip implied properties if 'implied_properties' in features and p in features[ 'implied_properties']: dependent = False for feature in features['implied_properties'][p]: if feature in s: dependent = True break if dependent: continue if 'properties' in features and p in features['properties']: # Add inferred properties if 'inferred_properties' in features and p in features[ 'inferred_properties'] and features['inferred_properties'][ p] not in s: sv.append( features['properties'][features['inferred_properties'][p]]) # Add current property sv.append(features['properties'][p]) # Set default base SV if not base and 'base' in features and '_DEFAULT' in features['base']: sv = [features['base']['_DEFAULT']] + sv # Prefix MOE SVs if 'Margin of Error' in s: sv = ['MarginOfError'] + sv return '_'.join(sv)
def one_hot_encoding(x, allowable_set, encode_unknown=False): """One-hot encoding. Parameters ---------- x Value to encode. allowable_set : list The elements of the allowable_set should be of the same type as x. encode_unknown : bool If True, map inputs not in the allowable set to the additional last element. Returns ------- list List of boolean values where at most one value is True. The list is of length ``len(allowable_set)`` if ``encode_unknown=False`` and ``len(allowable_set) + 1`` otherwise. """ if encode_unknown and (allowable_set[-1] is not None): allowable_set.append(None) if encode_unknown and (x not in allowable_set): x = None return list(map(lambda s: x == s, allowable_set))
def convertOnOffStatement(v): """ Receive the value about average on/off and return "ON" or "OFF" Args: v: returned integer 0 or 1 """ if int(v)==0: return "OFF" elif int(v)==1: return "ON"
def check_keys_in_dict(keys, map): """ Check if all keys are present in a dictionary. """ return all([key in map for key in keys])
def cmd_with_properties(commandline): """Add extra arguments that use `trial` and `exp` properties""" cmd_args = commandline cmd_args.extend(["--trial-name", "{trial.hash_name}", "--exp-name", "{exp.name}"]) return cmd_args
def time_format(num, digits=1, align_unit=False): # type: (float, int, bool) -> str """Format and scale output according to standard time units. Example ------- >>> time_format(0) '0.0 s' >>> time_format(0, align_unit=True) '0.0 s ' >>> time_format(0.002) '2.0 ms' >>> time_format(2001) '33.4 m' >>> time_format(2001, digits=3) '33.350 m' """ if num is None: return "<unknown>" unit = "s" if (num >= 1.0) or (num == 0.0): if num >= 60.0: num /= 60.0 unit = "m" if num >= 60.0: num /= 60.0 unit = "h" if num >= 24.0: num /= 24.0 unit = "d" else: num *= 1000.0 for p in ["ms", "us", "ns", "ps", "fs"]: unit = p if abs(round(num, digits + 3)) >= 1: break num *= 1000.0 if (len(unit) == 1) and align_unit: return ("%." + str(digits) + "f %s ") % (num, unit) else: return ("%." + str(digits) + "f %s") % (num, unit)
def indent(code, level): """ indent code to the given level """ return code.replace("\n", "\n" + (" "*level))
def is_eresource_callno(callno: str) -> bool: """ Checks if call number is for electronic resource Args: callno: call number string Returns: bool """ try: norm_callno = callno.lower() except AttributeError: return False if norm_callno.startswith("enypl"): # NYPL pattern return True elif norm_callno in ("ebook", "eaudio", "evideo"): # BPL pattern return True else: return False
def float_from_str(string): """ Extract a float from a given String. Decimal is ',' and Thousand seperator is ".". :returns: float -- The extracted number >>> extract_float("The number is 12.567,57.") 12567.57 """ import re pattern = re.compile(r"\b[0-9]{1,3}(\.[0-9]{3})*(,[0-9]+)?\b|,[0-9]+\b") res = pattern.search(string) if res is None: return 0.0 res = res.group() res = res.replace(".", "") res = res.replace(",", ".") return float(res)
def connect_the_dots(pts): """given a list of tag pts, convert the point observations to poly-lines. If there is only one pt, return None, otherwise connect the dots by copying the points and offseting by 1, producing N-1 line segments. Arguments: - `pts`: a list of point observations of the form [[lat1,lon1],[lat2, lon2], ... ] """ if len(pts) > 1: # pts = [(x[1], x[0]) for x in pts] pts = [x[1] for x in pts] A = pts[:-1] B = pts[1:] coords = list(zip(A, B)) return coords else: return None
def _is_dunder(name): """ A copy of enum._is_dunder from Python 3.6. Returns True if a __dunder__ (double underscore) name, False otherwise. """ return (len(name) > 4 and name[:2] == name[-2:] == '__' and name[2] != '_' and name[-3] != '_')
def pretty_time(dt): """ Returns a human readable string for a time duration in seconds. :param dt: duration in seconds """ if dt > 3600: hours = dt / 3600. if hours > 9: return '%dh' % (int(hours)) minutes = 60 * (hours - int(hours)) return '%dh%2dm' % (int(hours), int(minutes)) elif dt > 60: minutes = dt / 60. if minutes > 9.5: return '%dm' % (int(minutes)) seconds = 60 * (minutes - int(minutes)) return '%dm%2ds' % (int(minutes), int(seconds)) elif dt > 10: return '%ds' % (int(dt)) elif dt > 0.05: return '%4.1fs' % dt else: return '-'
def encased(message, marker): """Return string 'message' encased in specified marker at both ends. >>> encased("hello", "**") '**hello**' :message: the string to be encased :marker: the string to encase with :returns: 'message' encased in markers """ return marker + message + marker
def extractFolders(folders): """ convert a string of folders to a list of tuples (db , schema, node) :param folders: a string containing folders db-schema-node seperated by , :return: a list of tuples (db , schema, node) """ output = [] folderList = folders.split('-') for folder in folderList: folderComponents = folder.split(',') output.append( (folderComponents[0], folderComponents[1], folderComponents[2])) return output
def adjust_size(back_height): """ adjust scale(version) for QR code to 1-40. Parameters ------ back_height: int height of background wallpaper """ ver = int(back_height/300+0.5) if ver == 0: ver += 1 elif ver > 39: ver = 39 return ver
def fcur(input): """ Format CURrency """ if int(input) == input: value = str(int(input)) else: value = r"{:20,.2f}".format(input) return rf"${value.strip()}"
def hexbyte_2integer_normalizer(first_int_byte, second_int_btye): """Function to normalize integer bytes to a single byte Transform two integer bytes to their hex byte values and normalize their values to a single integer Parameters __________ first_int_byte, second_int_byte : int integer values to normalize (0 to 255) Returns _______ integer: int Single normalized integer """ first_hex = f'{hex(first_int_byte)}'.lstrip('0x') second_hex = f'{hex(second_int_btye)}'.lstrip('0x') first_hex = first_hex if len(f'{first_hex}') == 2 else f'0{first_hex}' second_hex = second_hex if len(f'{second_hex}') == 2 else f'0{second_hex}' hex_string = f'{first_hex}{second_hex}' integer = int(hex_string, 16) return integer
def remove_empty_arrays(movies_names_wl): """ This function takes movies_names_wl and removes empty arrays. """ for movie in movies_names_wl: if(movie == []): movies_names_wl.remove(movie) return movies_names_wl
def _get_gcs_path(base_path, content_type, root_id, timestamp): """Generate a GCS object path for CAI dump. Args: base_path (str): The GCS bucket, starting with 'gs://'. content_type (str): The Cloud Asset content type for this export. root_id (str): The root resource ID for this export. timestamp (int): The timestamp for this export. Returns: str: The full path to a GCS object to store export the data to. """ return '{}/{}-{}-{}.dump'.format(base_path, root_id.replace('/', '-'), content_type.lower(), timestamp)
def compute_frequencies(words): """ Args: words: list of words (or n-grams), all are made of lowercase characters Returns: dictionary that maps string:int where each string is a word (or n-gram) in words and the corresponding int is the frequency of the word (or n-gram) in words """ Bdict = {} #Bdict is a dictionary that maps each string with its frequency for i in words: if i in Bdict.keys(): Bdict[i] += 1 else: Bdict[i] = 1 return Bdict
def _mode(basemode, label): """Return the trace mode given a base mode and label bool. """ if label: return basemode + "+text" else: return basemode
def is_cjk(character): """" Checks whether character is CJK. >>> is_cjk(u'\u33fe') True >>> is_cjk(u'\uFE5F') False :param character: The character that needs to be checked. :type character: char :return: bool """ return any([start <= ord(character) <= end for start, end in [(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215), (63744, 64255), (65072, 65103), (65381, 65500), (131072, 196607)] ])
def query_tw_field_exists(field): """ES query within documents pulled from Twitter API v2 Args: field (str) Returns: ES query (JSON) """ return { "query": { "bool": { "filter": [ {"term": {"doctype": "tweets2"}}, {"exists": {"field": field}}, ] } } }
def named_capture(pattern, name): """ generate a named capturing pattern :param pattern: an `re` pattern :type pattern: str :param name: a group name for the capture :type name: str :rtype: str """ return r'(?P<{:s}>{:s})'.format(name, pattern)
def valid_model_name(name, opt, step=0): """ chcek if a sting is valid checkpoint name. naming pattern: $NAME_acc_XX.YY_ppl_XX.YY_eZZ.pt :param name: name of the checkpoint :param opt: parser :return: return True if the name if valid else False. """ parts = name.strip().split('_') if len(parts) != (6+step): return False tmp = parts[0:0+step+1] _name = '' for i in tmp: _name += i + '_' _name = _name[0:-1] if _name != opt.name: return False if parts[1+step] != 'acc': return False try: if type(float(parts[2+step])) is not float: return False except ValueError as e: if opt.verbose: print("{0} is not a valid model address.\nException details: {1}". format(name, e)) return False if parts[3+step] != 'ppl': return False try: if type(float(parts[4+step])) is not float: return False except Exception as e: if opt.verbose: print("{0} is not a valid model address.\nException details: {1}". format(name, e)) return False if parts[5+step][-3:] != '.pt': return False if parts[5+step][0:1] != 'e': return False try: if type(int(parts[5+step][1:-3])) is not int: return False except Exception as e: if opt.verbose: print("{0} is not a valid model address.\nException details: {1}". format(name, e)) return False return True
def num_shifts_in_stack(params): """Calculate how many time points (shifts) will be used in loss functions. Arguments: params -- dictionary of parameters for experiment Returns: max_shifts_to_stack -- max number of shifts to use in loss functions Side effects: None """ max_shifts_to_stack = 1 if params['num_shifts']: max_shifts_to_stack = max(max_shifts_to_stack, max(params['shifts'])) if params['num_shifts_middle']: max_shifts_to_stack = max(max_shifts_to_stack, max(params['shifts_middle'])) return max_shifts_to_stack
def escape_split(sep, argstr): """ Allows for escaping of the separator: e.g. task:arg='foo\, bar' It should be noted that the way bash et. al. do command line parsing, those single quotes are required. Copy from fabric 1.14 """ escaped_sep = r"\%s" % sep if escaped_sep not in argstr: return argstr.split(sep) before, _, after = argstr.partition(escaped_sep) startlist = before.split(sep) # a regular split is fine here unfinished = startlist[-1] startlist = startlist[:-1] # recurse because there may be more escaped separators endlist = escape_split(sep, after) # finish building the escaped value. we use endlist[0] becaue the first # part of the string sent in recursion is the rest of the escaped value. unfinished += sep + endlist[0] return startlist + [unfinished] + endlist[1:]
def _schema_to_keys(s): """Return the entry keys for schema of dict type.""" def _get_d(s): d = s while hasattr(d, 'schema'): d = s.schema return d d = _get_d(s) if not isinstance(d, dict): return None return (_get_d(ss) for ss in d.keys())
def quotestr(v): """Quote a string value to be output.""" if not v: v = '""' elif " " in v or "\t" in v or '"' in v or "=" in v: v = '"%s"' % v.replace(r'"', r"\"") return v
def _convert_y(latitude): """ convert latitude to y """ return -68.75659401 * latitude + 2782.239846283
def compute_avg_over_multiple_runs(number_episodes, number_runs, y_all_reward, y_all_cum_reward, y_all_timesteps): """ Compute average of reward and timesteps over multiple runs (different dates) """ y_final_reward = [] y_final_cum_reward = [] y_final_timesteps = [] for array_index in range(0, number_episodes): sum_r = 0 sum_cr = 0 sum_t = 0 count = 0 for date_index in range(0, number_runs): # compute average sum_r += y_all_reward[date_index][array_index] sum_cr += y_all_cum_reward[date_index][array_index] sum_t += y_all_timesteps[date_index][array_index] count += 1 y_final_reward.append(sum_r / float(count)) y_final_cum_reward.append(sum_cr / float(count)) y_final_timesteps.append(sum_t / float(count)) return y_final_reward, y_final_cum_reward, y_final_timesteps
def is_blank_or_comment(x): """Checks if x is blank or a FASTA comment line.""" return (not x) or x.startswith("#") or x.isspace()
def find_empty(board): """Function to find empty cells in game board. Args: board (list): the current game board. Returns: (i, j) (tuple): empty position (row, column) if found, otherwise None. """ for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) # row, col return None
def format_message( text: str, *args, no_arg_phrase: str = "None", enclosing_char: str = "`") -> str: """Construct message from given text with inserting given args to it and return resulting message. Args: text: Main message text with formatting brackets `{}`. args: Positional args ordered for according formatting brackets. Given lists will be also unpacked. no_arg_phrase: Text to insert to position of arg with `None` value instead it. Defaults to `"None"`. enclosing_char: Char to enclose every given argument in text from both sides for differentiation. If set to `None`, don't perform enclosing. Defaults to single backtick. Raise: ValueError: If given text has different number of braces than amount of given arguments. """ vars_to_format = [] for arg in args: if isinstance(arg, list): if not bool(arg): # Empty mapping, no need to unpack. vars_to_format.append(no_arg_phrase) for _arg in arg: if ( _arg is None or ( not bool(_arg) and not isinstance(_arg, int))): vars_to_format.append(no_arg_phrase) else: vars_to_format.append(_arg) elif arg is None or (not bool(arg) and not isinstance(arg, int)): vars_to_format.append(no_arg_phrase) else: vars_to_format.append(arg) # Check if text with correct number of braces given. if text.count("{}") != len(vars_to_format): raise ValueError( f"Text `{text}` has different number of braces than amount of" f" given arguments: `{vars_to_format}`.") # Apply enclosing char to every var. if enclosing_char is not None: enclosed_vars_to_format = [] for var in vars_to_format: enclosed_vars_to_format.append( str(enclosing_char) + str(var) + str(enclosing_char)) message = text.format(*enclosed_vars_to_format) return message
def format_subpattern(subpattern: dict) -> list: """Sort layers of each subpattern and convert to tuple""" formatted = list() for _, color_layers in subpattern.items(): formatted.append(tuple(sorted(color_layers))) return formatted
def gff3_attributes(att): """ Process the attributes column into a dict of key - list(values) pairs :param att: str :return attribute_dict: dict """ att_arr = att.split(";") # Break K=V;K=V;K=V into key-value pairs if len(att_arr) == 0: return None attribute_dict = dict() for a in att_arr: k, v = a.split("=") # Break Key = Value pair attribute_dict[k] = list() for sub_v in v.split(","): if ":" in sub_v: sub_sub_v = sub_v.split(":") attribute_dict[k].append((sub_sub_v[0], sub_sub_v[1])) else: attribute_dict[k].append(sub_v) return attribute_dict
def parse(tokens): """ Parses a list of tokens, constructing a representation where: * symbols are represented as Python strings * numbers are represented as Python ints or floats * S-expressions are represented as Python lists Arguments: tokens (list): a list of strings representing tokens """ # Check if all the parentheses are matched def check_parenthese(tokens): paren = 0 for token in tokens: if token == '(': paren += 1 elif token == ')': paren -= 1 if paren < 0: raise SyntaxError("Parentheses are mismatched!") if paren != 0: raise SyntaxError("Parentheses are mismatched!") # Convert each token into a Python data type def convert(token): try: sym = int(token) except: try: sym = float(token) except: sym = str(token) return sym # Recursivly convert the tokens into a nested Python list def add_token(tokens): i = 0 result = [] while i < len(tokens): sym = convert(tokens[i]) if sym == '(': i += 1 parsed, num = add_token(tokens[i::]) result.append(parsed) i += num elif sym == ')': i += 1 return result, i else: result.append(sym) i += 1 return result, i check_parenthese(tokens) return convert(tokens[0]) if len(tokens) == 1 else add_token(tokens[1:len(tokens)-1])[0]
def isSubListInListWithIndex(sublist, alist): """ Predicates that checks if a list is included in another one Args: sublist (list): a (sub)-list of elements. alist (list): a list in which to look if the sublist is included in. Result: (True, Index) if the sublist is included in the list. False otherwise. """ for i in range(len(alist) - len(sublist) + 1): if sublist == alist[i: i + len(sublist)]: return True, i return False, -1
def concatenate(*args, **kwargs): """ Concatenates the given strings. Usage:: {% load libs_tags %} {% concatenate "foo" "bar" as new_string %} {% concatenate "foo" "bar" divider="_" as another_string %} The above would result in the strings "foobar" and "foo_bar". """ divider = kwargs.get('divider', '') result = '' for arg in args: if result == '': result += arg else: result += '{0}{1}'.format(divider, arg) return result
def path(keys, dict): """Retrieve the value at a given path""" if not keys: raise ValueError("Expected at least one key, got {0}".format(keys)) current_value = dict for key in keys: current_value = current_value[key] return current_value
def recursive_binary_search(l:list, item): """Use binary search with recursion.""" if len(l) < 2: return 0 if len(l) == 1 and item == l[0] else None else: mid = len(l) // 2 if item == l[mid]: return mid elif item > l[mid]: return recursive_binary_search(l[mid:], item) else: return recursive_binary_search(l[:mid], item)
def encode(number, base): """ Encode given number in base 10 to digits in given base. number: int -- integer representation of number (in base 10) base: int -- base to convert to return: str -- string representation of number (in given base) NOTE: For the purpose of this function we keep remainders as number we didnt convert them into hex value """ # Handle up to base 36 [0-9a-z] assert 3 <= base <= 16, 'base is out of range: {}'.format(base) # Handle unsigned numbers only for now assert number >= 0, 'number is negative: {}'.format(number) dividend = number divisor = base quotient = 1 result = [] while quotient != 0: # check if dividend(number) is less than divisor(base) # if true no need to devide. then divedend = remainder if dividend < divisor: remainder = dividend quotient = 0 else: remainder = dividend % divisor # updating the dividend until it is less than devisor dividend = (dividend - remainder) // divisor # if remainder > 9: # remainder = chr(remainder + hex_letter_offset) # remainder = str(remainder) # result += str(remainder) result.append(str(remainder)) return result
def addFloat2String(value, val_len, decimal_len, front): """ Function for parsing a float into a correct string format. Front works as the parser character which tells the program how the string has to be formatted. **Examples**:: >> addFloat2String(0.71, 6, 3, '>') " 0.710" :param float value: integer that will be formatted :param int val_len: value that tells how long the string needs to be :param int decimal_len: value that tells how many of the letters will be allocated for the fraction :param str front: formatting character :return: formatted string """ if value is None: return val_len * " " if len(str(value)) > val_len: value = float(("{:."+ str(decimal_len) +"f}").format(value)) if value < 1.0 and value > -1.0 and val_len == len(str(value)) - 1: pass elif len(str(value)) > val_len: raise ValueError string = "" parser = "{:" + front + str(val_len) + "." + str(decimal_len) + "f}" string += parser.format(value) if float(value) < 0 and val_len == len(string) - 1: string = string[0] + string[2:] return string
def convert_to_base(num, base): """ Converts integer num into base b format ie number to configuration Args: num - intger to be converted base - base to be converted into Returns: base b representation of num """ convStr = "0123" if num < base: return str(num) else: return convert_to_base(num // base, base) + convStr[num % base]
def _merge_dicts(a, b, path=None, overwrite=True): """ like _join_dicts, but works for any nested levels copied from: https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): _merge_dicts(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: pass # same leaf value else: if not overwrite: raise Exception('Conflict at %s' % '.'.join(path + [str(key)])) else: a[key] = b[key] else: a[key] = b[key] return a
def get_xp(lvl): """ Returns total XP according to gain level """ total_xp = int((lvl * 10) ** 1.1) return total_xp * lvl
def selfDescriptiveNumber(num): """ -- Self-Descriptive Number -- See: http://en.wikipedia.org/wiki/Self-descriptive_number -- Checks if the given number is self-descriptive -- num : a number, in base 10 -- returns : true if the number is self-descriptive, false otherwise """ sdNum=0 #create self-descriptive number base=1000000000 digitCount=[0,0,0,0,0,0,0,0,0,0] for digit in str(num): digitCount[int(digit)]+=1 for number in digitCount: sdNum+=number*base base/=10 #check the given number with the created one return (sdNum==num)
def master_func(x, m, p): """ master function to be fit refer to the Supplementary Note for a justification """ return m * (1 - ((m - p) / m) ** x)
def normalize_memory_value(mem_string): """ Returns memory value in Gigabyte """ if mem_string[-1] == 'G': return float(mem_string[:-1]) elif mem_string[-1] == 'M': return float(mem_string[:-1])/1024.0 elif mem_string[-1] == 'K': return float(mem_string[:-1])/(1024*1024.0)
def float_input(input_str): """ Parse passed text string input to float Return None if input contains characters apart from digits """ try: input_val = float(input_str) except ValueError: input_val = None return input_val
def isfloat(instr): """ Reports whether a string is floatable """ try: _ = float(instr) return(True) except: return(False)
def where2(value1, value2, ls, interval): """Find where the value1 and value2 are located in ls, where the interval between neighboring elements are given. This function may be faster than where, but might be slower in case that the interval is irregular. This function returns the slice of ls between value1 and value2. Suppose that where returns (s1, s2) given value1, value2, and ls, and value1 <= value2 The use can get the slice between value1 and value2 by ls[s1:s2]. """ length = len(ls) start = 0 end = 0 # if empty array, just return 0, 0 if length ==0: return start, end diff1 = int(value1 - ls[0]) if diff1 >= 0: start = min(diff1/interval, length-1) # adjust 'start' while start > 0 and value1 < ls[start]: start-=1 while start < length and value1 > ls[start]: start+=1 diff2 = int(value2 - value1) if diff2 >= 0: try: end = min(start + diff2/interval, length-1) except ZeroDivisionError: interval = 1 end = min(start + diff2/interval, length-1) else: # if value1 > value2, just return start, start return start, start # adjust 'end' while end > 0 and value2 < ls[end]: end-=1 while end < length and value2 >= ls[end]: end+=1 end = min(length, end) return start, end
def mirror_distance_object(focal_point,distance_image): """Usage: Find distance of object with focal point and distance of image""" numerator = focal_point * distance_image denominator = distance_image - focal_point return numerator / denominator
def transpose(matrix): """Takes a 2D matrix (as nested list) and returns the transposed version. Parameters ---------- matrix : Returns ------- """ return [list(val) for val in zip(*matrix)]
def build_trigram(words): """ build up the trigrams dict from the list of words :param words: a list of individual words in order :returns: a dict with: keys: word pairs in tuples values: list of the words that follow the pain in the key """ # Dictionary for trigram results: # The keys will be all the word pairs # The values will be a list of the words that follow each pair word_pairs = {} # loop through the words # (rare case where using the index to loop is easiest) for i in range(len(words) - 2): # minus 2, 'cause you need a pair pair = tuple(words[i:i + 2]) # a tuple so it can be a key in the dict follower = words[i + 2] word_pairs.setdefault(pair, []).append(follower) # setdefault() returns the value if pair is already in the dict # if it's not, it adds it, setting the value to a an empty list # then it returns the list, which we then append the following # word to -- cleaner than: # if pair in word_pairs: # word_pairs[pair].append(follower) # else: # word_pairs[pair] = [follower] return word_pairs
def bound_between(min_val, val, max_val): """Bound value between min and max.""" return min(max(val, min_val), max_val)
def getCall(row): """ Return a call dictionary representing the call. Assuming that row is an array having 4 elements """ return (row[0], row[1], row[2], row[3])
def results_basename(search_id): """ Generate the base name for the download file """ basename = 'results-{}.csv'.format(search_id) return basename
def make_polymer(starting_dict, reference_dict_, n): """Creates the polymer by doing n steps""" if n == 0: return starting_dict else: #print(starting_dict) n_dict = starting_dict.copy() for key in starting_dict.keys(): val = starting_dict[key] n_dict[key] -= val for j in reference_dict_[key]: n_dict[j] += val n -= 1 return make_polymer(n_dict, reference_dict_, n)
def one_hand_hash(x, y): """ Use hash; more space; Bad solution since hashing is order invariant 'pale' and 'elap' will returned the same :param x: string :param y: string :return: """ if x == y: return True # Fill dict of chars from the first string cnt = {} for ch in x: if ch not in cnt: cnt[ch] = 1 else: cnt[ch] += 1 # Remove existing chars from the second string for ch in y: if ch in cnt: cnt[ch] -= 1 # Check everything is 0 except one key tmp = 0 for k, v in cnt.items(): if v != 0: tmp += 1 if tmp > 1: return False return True
def as_float(value): """ Converts a value to a float if possible On success, it returns (converted_value, True) On failure, it returns (None, False) """ try: return float(value), True except Exception as exception: # Catch all exception including ValueError return None, False
def is_numeric(s): """Returns true if a value can be converted to a floating point number""" try: float(s) return True except ValueError: return False except TypeError: print('ERROR: Must have null value in working dictionary') return False
def _LeftMostFace(holes, points): """Return (hole,index of hole in holes) where hole has the leftmost first vertex. To be able to handle empty holes gracefully, call an empty hole 'leftmost'. Assumes holes are sorted by softface.""" assert(len(holes) > 0) lefti = 0 lefthole = holes[0] if len(lefthole) == 0: return (lefthole, lefti) leftv = lefthole[0] for i in range(1, len(holes)): ihole = holes[i] if len(ihole) == 0: return (ihole, i) iv = ihole[0] if points.pos[iv] < points.pos[leftv]: (lefti, lefthole, leftv) = (i, ihole, iv) return (lefthole, lefti)
def _ExtractPatternsFromFiletypeTriggerDict( triggerDict ): """Returns a copy of the dictionary with the _sre.SRE_Pattern instances in each set value replaced with the pattern strings. Needed for equality test of two filetype trigger dictionaries.""" copy = triggerDict.copy() for key, values in triggerDict.items(): copy[ key ] = set( [ sre_pattern.pattern for sre_pattern in values ] ) return copy
def b2h(num, suffix='B'): """Format file sizes as human readable. https://stackoverflow.com/a/1094933 Parameters ---------- num : int The number of bytes. suffix : str, optional (default: 'B') Returns ------- str The human readable file size string. Examples -------- >>> b2h(2048) '2.0kB' """ try: for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1024.0: return '{0:3.1f}{1}{2}'.format(num, unit, suffix) num /= 1024.0 return '{0:.1f}{1}{2}'.format(num, 'Y', suffix) except: return '-'
def verif_checksum(line_str, checksum): """Check data checksum.""" data_unicode = 0 data = line_str[0:-2] #chaine sans checksum de fin for caractere in data: data_unicode += ord(caractere) sum_unicode = (data_unicode & 63) + 32 sum_chain = chr(sum_unicode) return bool(checksum == sum_chain)
def split_basename(basename): """ Splits a base name into schema and table names. """ parts = basename.split(".") db_name = parts[0] python_path_name = parts[1] schema_name = parts[2] table_name = parts[3] return db_name, python_path_name, schema_name, table_name
def GetRegionFromZone(gce_zone): """Parses and returns the region string from the gce_zone string.""" zone_components = gce_zone.split('-') # The region is the first two components of the zone. return '-'.join(zone_components[:2])
def algP(m,s,b,n): """ based on Algorithm P in Donald Knuth's 'Art of Computer Programming' v.2 pg. 395 """ result = 0 y = pow(b,m,n) for j in range(s): if (y==1 and j==0) or (y==n-1): result = 1 break y = pow(y,2,n) return result
def reverse(head): # Write your code here """ head Node return Node """ node = head evens = [] while node is not None: isEven = node.data % 2 == 0 # push node to evens if isEven: # print(" push:",node.data) evens.append(node) # not even, reverse nodes in evens if not isEven or node.link is None: # print(" len(evens):", len(evens)) while len(evens) > 1: # swap data for matched pair in evens # print(" swap:",evens[0].data,evens[-1].data) evens[0].data, evens[-1].data = evens[-1].data, evens[0].data evens.pop(0) evens.pop(-1) evens.clear() node = node.link return head
def findFirstRepeater(data: list) -> int: """ Loops over puzzleArray adding each value to frequency as with part 1, but loops over entire array until it adds the same number twice. Once found, returns that integer to submission. Args: data: puzzleArray from AOC Returns: first instance of repeated integer as per puzzle """ frequencyDict = {} frequency = 0 while True: for eachFrequency in data: frequency = frequency + eachFrequency if frequency not in frequencyDict.keys(): frequencyDict[frequency] = 'Yes' else: return frequency return frequency
def parse_to_sacred_experiment_args(arguments: list, _seed: int, log_dir: str) -> list: """Add seed to sys args if not already defined. This brings arguments into the expected structure of the sacred framework. Remind: arguments is a list, so this is a call by reference Parameters ---------- arguments An object holding information of the parsed console arguments. This is a call by reference! _seed The seed for the random generator. log_dir Over-write the default BASEDIR by setting a sacred flag. Returns ------- list The parsed arguments with the expected structure. """ seed_in_args = None with_in_args = False custom_log_dir = None if log_dir == '' else log_dir _args = arguments.copy() # copy argument list, since this is a call by reference # sacred expects the first element of list to be a command if len(_args) > 0 and _args[0] == 'with': _args = ['run', ] + _args if len(_args) == 0: _args.append('run') for pos, elem in enumerate(_args): # look if there exists seed=X in _args, if len(elem) > 5 and elem[:5] == 'seed=': seed_in_args = pos value = elem[5:] print( 'WARNING: Seed==={} was found in args, change seed to: {}'.format( value, _seed)) if len(elem) == 4 and elem == 'with': with_in_args = True string_argument = 'seed=' + str(_seed) if seed_in_args: _args[seed_in_args] = string_argument else: if not with_in_args: _args.append('with') _args.append(string_argument) # over-write the default BASEDIR with custom log dir if provided if custom_log_dir: _args.append(f'base_dir={custom_log_dir}') return _args
def build_isolation_parameters( technique, threshold_type, threshold_const, threshold_min=0, window_size=1.0, chunk_size=2.0): """ Wrapper function for all of the audio isolation techniques (Steinberg, Simple, Stack, Chunk). Will call the respective function of each technique based on isolation_parameters "technique" key. Args: technique (string) - Chooses which of the four isolation techniques to deploy - options: "steinberg", "chunk", "stack", "simple" threshold_type (string) - Chooses how to derive a threshold from local score arrays - options: "mean", "median", "standard deviation", "pure" threshold_const (float) - Multiplier for "mean", "median", and "standard deviation". Acts as threshold for "pure" threshold_min (float) - Serves as a minimum barrier of entry for a local score to be considered a positive ID of a class. - default: 0 window_size (float) - determines how many seconds around a positive ID local score to build an annotation. chunk_size (float) - determines the length of annotation when using "chunk" isolation technique Returns: isolation_parameters (dict) - Python dictionary that controls how to go about isolating automated labels from audio. """ isolation_parameters = { "technique": technique, "treshold_type": threshold_type, "threshold_const": threshold_const, "threshold_min": threshold_min, "window_size": window_size, "chunk_size": chunk_size } if window_size != 1.0 and technique != "steinberg": print('''Warning: window_size is dedicated to the steinberg isolation technique. Won't affect current technique.''') if chunk_size != 2.0 and technique != "chunk": print('''Warning: chunk_size is dedicated to the chunk technique. Won't affect current technique.''') return isolation_parameters
def wait_timer(index: int, time: int): """Wait for timer.""" return f'B;WaitTimer("{index}","{time}");'.encode()
def as_flag(b): """Return bool b as a shell script flag '1' or '0'""" if b: return '1' return '0'
def convert_chrome_cookie(cookie): """Convert a cookie from Chrome to a CookieJar format type""" return { 'name': cookie['name'], 'value': cookie['value'], 'domain': cookie['domain'], 'path': cookie['path'], 'secure': cookie['secure'], 'expires': int(cookie['expires']) if cookie['expires'] != -1 else None, 'rest': {'HttpOnly': True if cookie['httpOnly'] else None} }
def compute_returns(rewards, gamma=1.0): """ Compute returns for each time step, given the rewards @param rewards: list of floats, where rewards[t] is the reward obtained at time step t @param gamma: the discount factor @returns list of floats representing the episode's returns G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + ... >>> compute_returns([0,0,0,1], 1.0) [1.0, 1.0, 1.0, 1.0] >>> compute_returns([0,0,0,1], 0.9) [0.7290000000000001, 0.81, 0.9, 1.0] >>> compute_returns([0,-0.5,5,0.5,-10], 0.9) [-2.5965000000000003, -2.8850000000000002, -2.6500000000000004, -8.5, -10.0] """ returns = [rewards[-1]] for i, reward in enumerate(rewards[-2::-1]): return_ = gamma * returns[i] + reward returns.append(return_) return returns[::-1]
def elematypecolor2string(elem, atype, color): """ return formatted string from element, atomtype, and color """ return "%s_%s/%s" % (elem, atype, color)
def format(time): """ Converts time in tenths of seconds to formatted string A:BC.D """ A = time // 600 B = ((time // 10) % 60) // 10 C = ((time // 10) % 60) % 10 D = time % 10 return str(A) + ":" + str(B) + str(C) + "." + str(D)
def split_obj_identifier(obj_identifier): """ Break down the identifier representing the instance. Converts 'notes.note.23' into ('notes.note', 23). """ bits = obj_identifier.split('.') if len(bits) < 2: return (None, None) pk = '.'.join(bits[2:]) # In case Django ever handles full paths... object_path = '.'.join(bits[0:2]) return (object_path, pk)
def ProcCSV(lst): """ Processes lst for delimiters and sorts them into a multi-dimensional array """ OutList = [] MegaList = [] for element in lst: for item in element.split(",,"): OutList.append(item.strip("\n")) for item in OutList: MegaList.append(item.split(",")) return MegaList
def count_column_freqs(columns_list): """return the frequency of columns""" col_freq_dict = {} for column in columns_list: column = ' '.join(column) col_freq_dict[column] = col_freq_dict.get(column, 0) + 1 return col_freq_dict
def iterative_len(x): """Return the len of an iterator without using len Example: >>> a = "hola" >>> iterative_len(a) >>> 4 """ return sum(1 for i in x)
def _qualified_type_name(class_): """ Compute a descriptive string representing a class, including a module name where relevant. Example outputs are "RuntimeError" for the built-in RuntimeError exception, or "struct.error" for the struct module exception class. Parameters ---------- class_ : type Returns ------- class_name : str """ # We're being extra conservative here and allowing for the possibility that # the class doesn't have __module__ and/or __qualname__ attributes. This # function is called during exception handling, so we want to minimise the # possibility that it raises a new exception. class_module = getattr(class_, "__module__", "<unknown>") class_qualname = getattr(class_, "__qualname__", "<unknown>") if class_module == "builtins": return f"{class_qualname}" else: return f"{class_module}.{class_qualname}"
def getDataNodeUrls(app): """ Return list of all urls to the set of datanodes """ dn_url_map = app["dn_urls"] dn_urls = [] for id in dn_url_map: dn_urls.append(dn_url_map[id]) return dn_urls
def has_duplicates(array): """Write a function called has_duplicates that takes a list and returns True if there is any element that appears more than once. It should not modify the original list.""" copy_array = array[:] copy_array.sort() val = copy_array[0] for i in range (1, len(array)): if val == copy_array[i]: return True return False
def aggregation_count(list_, primary_key, count_key): """ params list_ : [{},{}] """ return list( map( lambda x: { primary_key: x[primary_key], 'count': len(x[count_key]) }, list_))
def convert_phred(letter): """Converts a single character into a phred score""" QScore = ord(letter) - 33 return QScore
def strip_package_from_class(base_package: str, class_name: str) -> str: """ Strips base package name from the class (if it starts with the package name). """ if class_name.startswith(base_package): return class_name[len(base_package) + 1 :] else: return class_name
def get_text(*args, sep=' '): """ Use this function for join some data with a separator Args: *args: all arguments sep (str): text separator Returns: (str) : result text """ text = "" for i in range(len(args)): text += str(args[i]) if i != len(args) - 1: text += sep return text
def use_mem(numbers): """Different ways to use up memory. """ a = sum([x * x for x in numbers]) b = sum(x * x for x in numbers) c = sum(x * x for x in numbers) squares = [x * x for x in numbers] d = sum(squares) del squares x = 'a' * int(1e6) del x return 42