content
stringlengths
42
6.51k
def to_lower(ctx, param, value): """Callback to lower case the value of a click argument""" return value.lower()
def eq_strict(a, b): """Returns True if both values have the same type and are equal.""" if type(a) is type(b): return a == b return False
def eval_branch(branch, teaching_combo): """Evaluate a branch on a teaching combo :param branch: dict containing comparators and numbers for blickets and non-blickets; used to construct a function representation of the branch :param teaching_combo: string of '*' (blickets) and "." (non-blickets) :returns: float between 0 and 1 representing the probability of the branch outputting a positive activation for teaching_combo """ # sanity check that comparators are filled in assert(branch['blicket_comparator'] is not None) assert(branch['nonblicket_comparator'] is not None) combo_blicket_num = teaching_combo.count('*') combo_nonblicket_num = teaching_combo.count('.') nonblicket_comparator = '==' if branch['nonblicket_comparator'] == '=' else branch['nonblicket_comparator'] nonblicket_num = branch['nonblicket_num'] if nonblicket_comparator == 'any': nonblicket_bool = True else: # sanity check that corresponding num is filled in assert(nonblicket_num is not None) nonblicket_bool = eval(f"{combo_nonblicket_num} {nonblicket_comparator} {nonblicket_num}") blicket_comparator = '==' if branch['blicket_comparator'] == '=' else branch['blicket_comparator'] blicket_num = nonblicket_num if branch['blicket_num'] == 'nonblicket_num' else branch['blicket_num'] if blicket_comparator == 'any': blicket_bool = True elif branch['blicket_num'] == 'nonblicket_num' and (nonblicket_num is None): # case when blicket num is supposed to be the same as nonblicket num and there can be any number of nonblickets assert(nonblicket_comparator == 'any') blicket_bool = True else: # sanity check that corresponding num is filled in assert(blicket_num is not None) blicket_bool = eval(f"{combo_blicket_num} {blicket_comparator} {blicket_num}") return branch['reliability'] * (blicket_bool and nonblicket_bool)
def make_tag(ttag, ttype): """Inverse of parse_tag.""" if ttype is None: return ttag else: return ttag+'-'+ttype
def cos(direction): """naive implementation of cos""" return int(abs(2 - direction) - 1)
def height(ep, m): """ Calculate and return the value of height using given values of the params How to Use: Give arguments for ep and m params *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: ep (int):potential energy in Joule m (int):mass in kg Returns: int: the value of height in meter """ g = 9.8 h = ep / (m * g) return h
def collate_double(batch): """ collate function for the ObjectDetectionDataSet. Only used by the dataloader. """ x = [sample['x'] for sample in batch] y = [sample['y'] for sample in batch] x_name = [sample['x_name'] for sample in batch] y_name = [sample['y_name'] for sample in batch] return x, y, x_name, y_name
def _mro(cls): """ Return the I{method resolution order} for C{cls} -- i.e., a list containing C{cls} and all its base classes, in the order in which they would be checked by C{getattr}. For new-style classes, this is just cls.__mro__. For classic classes, this can be obtained by a depth-first left-to-right traversal of C{__bases__}. """ if isinstance(cls, type): return cls.__mro__ else: mro = [cls] for base in cls.__bases__: mro.extend(_mro(base)) return mro
def sudoku2(grid): """ check if sudoku board is true by checking that the same number didn't appear more than one in its row, col, surrounding 3*3 sub matrix """ for i in range(9): for j in range(9): if i % 3 == 0 and j % 3 == 0: l = [ grid[s_i][s_j] for s_i in range(i, i + 3) for s_j in range(j, j + 3) if grid[s_i][s_j].isdigit() ] if len(set(l)) != len(l): return False if grid[i][j].isdigit(): if grid[i].count(grid[i][j]) > 1: return False if list(zip(*grid))[j].count(grid[i][j]) > 1: return False return True
def compare_values(value1, value2): """ In-depth comparison of the two values. If the two are primitives, compare them directly. If the two are collections, go recursive through the elements. """ print("Comparing " + str(value1) + " & " + str(value2) + ".") # if different types, sure not equal if type(value1) != type(value2): return False # check if they are containers or not try: n1 = len(value1) n2 = len(value2) # if length not equal, return False if n1 != n2: return False # else check for each pair for i in range(0, n1): val1 = value1[i] val2 = value2[i] if not compare_values(val1, val2): return False except: # if they are not containers, check for value equality if value1 != value2: return False # True if all comparisons are true return True
def _transform_str_numeric_read_net_per_stock(row): """Transformation fucntion from string to numeric for rows of table net_per_stock. "Month Year", "Ticker", "Available Quantity units",(int) "Average Buy Price brl_unit",(float) "Sold Quantity units",(int) "Average Sell Price brl_unit",(float) "Profit per unit brl_per_unit",(float) "Unit profit per stock including sales operations costs",(float) "Profit brl",(float) "Remain Quantity units",(int) "Remain Operation value w taxes brl",(float) Args: row (list): List of strings Returns: list: List of strings and numeric. """ row[2] = int(float(row[2])) row[3] = float(row[3]) row[4] = int(float(row[4])) row[5] = float(row[5]) row[6] = float(row[6]) row[7] = float(row[7]) row[8] = float(row[8]) row[9] = int(float(row[9])) row[10] = float(row[10]) return row
def strip(string): """ Strip a unisense identifier string of unnecessary elements such as version string {https://www.unisens.org/unisens2.0} """ if '}' in string: string = string.split('}')[-1] return string
def call_sig(args, kwargs): """Generates a function-like signature of function called with certain parameters. Args: args: *args kwargs: **kwargs Returns: A string that contains parameters in parentheses like the call to it. """ arglist = [repr(x) for x in args] arglist.extend("{}={!r}".format(k, v) for k, v in kwargs.items()) return "({args})".format(args=", ".join(arglist))
def break_s3_file_uri(fully_qualified_file): """ :param fully_qualified_file: in form s3://{0}/{1}/{2} where {0} is bucket name, {1} is timeperiod and {2} - file name :return: tuple (s3://{0}, {1}/{2}) """ tokens = fully_qualified_file.rsplit('/', 2) return tokens[0], '{0}/{1}'.format(tokens[1], tokens[2])
def listify(value): """If variable, return a list of 1 value, if already a list don't change a list. """ if value is not None: if not isinstance(value, list): value = [value] else: value = [] return value
def adjust_detector_length(requested_detector_length, requested_distance_to_tls, lane_length): """ Adjusts requested detector's length according to the lane length and requested distance to TLS. If requested detector length is negative, the resulting detector length will match the distance between requested distance to TLS and lane beginning. If the requested detector length is positive, it will be adjusted according to the end of lane ending with TLS: the resulting length will be either the requested detector length or, if it's too long to be placed in requested distance from TLS, it will be shortened to match the distance between requested distance to TLS and lane beginning. """ if requested_detector_length == -1 or requested_detector_length is None: return lane_length - requested_distance_to_tls return min(lane_length - requested_distance_to_tls, requested_detector_length)
def pretty_float(x): """Format a float to no trailing zeroes.""" return ('%f' % x).rstrip('0').rstrip('.')
def place_nulls(key, input_keyvals, output_results): """ Useful in a specific case when you want to verify that a mapped list object returns objects corresponding to input list. Hypothetical example: Customer.raw_get_all([1,2,3]) returns [C1, C3] There is no customer with id 2 in db. But this is bad for us becaause we will want to iterate like zip (input, output) if possible. So we need to place nulls wherever the list is missing an output value. This function will make the list as [C1, None, C3] """ if len(input_keyvals) != len(output_results): for index, keyval in enumerate(input_keyvals): try: if getattr(output_results[index], key) != keyval: output_results.insert(index, None) except IndexError: output_results.insert(index, None) return output_results
def color(string_name, color_name=None): """ Change text color for the Linux terminal. """ if not string_name: return '' string_name = str(string_name) attr = ['1'] # bold if color_name: if color_name.lower() == "red": attr.append('31') elif color_name.lower() == "green": attr.append('32') elif color_name.lower() == "yellow": attr.append('33') elif color_name.lower() == "blue": attr.append('34') if '\n' in string_name: str_list = string_name.split('\n') str_list_modified = [] for s in str_list: str_list_modified.append('\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)) return '\n'.join(str_list_modified) else: return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string_name) else: if string_name.strip().startswith("[!]"): attr.append('31') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string_name) elif string_name.strip().startswith("[+]"): attr.append('32') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string_name) elif string_name.strip().startswith("[*]"): attr.append('34') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string_name) elif string_name.strip().startswith("[>]"): attr.append('33') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string_name) else: return string_name
def findPoisonedDuration(timeSeries, duration): """ :type timeSeries: List[int] :type duration: int :rtype: int """ #complexity: O(n) +O(n) = O(n) poisoned = [] for t in timeSeries: #loop over all elements in timeSeries = O(n) poisoned += list(range(t, t+duration)) #O(1) b/c duration = constant poisoned_secs = set(poisoned) # O(n) return len(poisoned_secs)
def update_gd_parameters(parameters, gradients, alpha=0.01): """ subtracting the gradient from the parameters for gradient descent :param parameters: containing all the parameters for all the layers :param gradients: containing all the gradients for all the layers :param alpha: learning rate :return: parameters """ L = len(parameters) // 2 for l in range(1, L + 1): parameters['W' + str(l)] -= alpha * gradients[l - 1][0] parameters['b' + str(l)] -= alpha * gradients[l - 1][1] return parameters
def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... """ if str(value).lower() in ("yes", "y", "true", "t", "1"): return True if str(value).lower() in ("no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False raise Exception('Invalid value for boolean conversion: ' + str(value))
def cleanup_bars(bars, width): """Cleans up a set of bars in staves globally""" if len(bars) > 1: l_diffs = [] for i in range(len(bars) - 1): l_diffs.append(abs(bars[i][0] - bars[i+1][0])) if min(l_diffs) < width: lowest_index = l_diffs.index(min(l_diffs)) if lowest_index == 0: new_bars = [bars[0]] + bars[2:] elif lowest_index == len(l_diffs) - 1: new_bars = bars[0:-2] + [bars[-1]] else: if l_diffs[lowest_index - 1] < l_diffs[lowest_index+1]: new_bars = bars[0:lowest_index] + bars[lowest_index+1:] else: new_bars = bars[0:lowest_index+1] + bars[lowest_index+2:] return cleanup_bars(new_bars, width) else: return bars else: return bars
def custom_latex_processing(latex): """ Processes a :epkg:`latex` file and returned the modified version. @param latex string @return string """ if latex is None: raise ValueError("Latex is null") # this weird modification is only needed when jenkins run a unit test in # pyquickhelper (pycode) return latex
def convert(hours: int, minutes: int) -> int: """Convert hours and minutes to total seconds.""" total_seconds = (minutes * 60) + (hours * 3600) return total_seconds
def minutes_to_hours(time): """ input: time in minutes, output: same in 'HH:MM' """ return str(time // 60) + ':' + str(time % 60)
def has_shape(a): """Returns True if the input has the shape attribute, indicating that it is of a numpy array type. Note that this also applies to scalars in jax.jit decorated functions. """ try: a.shape return True except AttributeError: return False
def fuzzy_collname_match(trial, targets): """ Do a noddy fuzzy match for bits between punctuation, e.g. matthews_cool_database will search for matthews, cool and database in the known collection names. Parameters: trial (str): database search name. targets (list): list of existing database names. Returns: list: list of roughly matching collection names ordered by occurence of tokens. """ split_chars = set([char for char in trial if (not char.isalpha() and not char.isdigit())]) tokens = trial for char in split_chars: tokens = tokens.replace(char, ' ') tokens = tokens.split() options = {} for token in tokens: for option in targets: if token in option: if option not in options: options[option] = 0 else: options[option] += 1 options_list = [item[0] for item in list(sorted(options.items(), reverse=True, key=lambda item: item[1]))] return options_list
def get(l, i, d=None): """Returns the value of l[i] if possible, otherwise d.""" if type(l) in (dict, set): return l[i] if i in l else d try: return l[i] except (IndexError, KeyError, TypeError): return d
def process_latitude(cell): """Return the latitude from a cell.""" lat = cell.strip().split("/")[0].strip() return float( int( str(lat[0]) + str(lat[1]), ) + int( str(lat[2]) + str(lat[3]), ) / 60 + int( str(lat[4]) + str(lat[5]), ) / 3600 )
def dispatch(obj, replacements): """make the replacement based on type :param obj: an obj in which replacements will be made :type obj: any :param replacements: the things to replace :type replacements: tuple of tuples """ if isinstance(obj, dict): obj = {k: dispatch(v, replacements) for k, v in obj.items()} elif isinstance(obj, list): obj = [dispatch(l, replacements) for l in obj] elif isinstance(obj, str): for replacement in replacements: obj = obj.replace(replacement[0], replacement[1]) return obj
def dict_to_css(css_dict, pretty=False): """Takes a dictionary and creates CSS from it :param css_dict: python dictionary containing css rules :param pretty: if css should be generated as pretty :return: css as string """ seperator = '\n' tab = '\t' if not pretty: seperator = '' tab = '' css_rules = [] for selector, rules in css_dict.items(): tmp = selector + '{' + seperator tmp_rules = [] if isinstance(rules, dict): for rule, value in rules.items(): tmp_rules.append(tab + rule + ':' + value + ';') tmp += seperator.join(tmp_rules) tmp = tmp + '}' css_rules.append(tmp) return seperator.join(css_rules)
def calc_temp(hex_str): """ Convert 4 hex characters (e.g. "040b") to float temp (25.824175824175825) :param hex_str: hex character string :return: float temperature """ adc = int(hex_str[0:2], 16) * 256 + int(hex_str[2:4], 16) temp = (300 * adc / 4095) - 50 return temp
def filter_assigments(all_player_dict, schedule_name_counter, data_screen_names): """Keep only dataset related player assigments""" player_dict = {} for p in all_player_dict: if schedule_name_counter is None: player_dict[p] = all_player_dict[p] else: if p in schedule_name_counter: if data_screen_names is None: player_dict[p] = all_player_dict[p] else: accounts = list(set(all_player_dict[p]).intersection(set(data_screen_names))) if len(accounts) > 0: player_dict[p] = accounts print("Total number of assigments: %i" % len(all_player_dict)) print("Dataset related number of assigments: %i" % len(player_dict)) return player_dict
def eea(m, n): """ Compute numbers a, b such that a*m + b*n = gcd(m, n) using the Extended Euclidean algorithm. """ p, q, r, s = 1, 0, 0, 1 while n != 0: k = m // n m, n, p, q, r, s = n, m - k*n, q, p - k*q, s, r - k*s return (p, r)
def escape_email(email: str) -> str: """ Convert a string with escaped emails to just the email. Before:: <mailto:[email protected]|[email protected]> After:: [email protected] :param email: email to convert :return: unescaped email """ return email.split('|')[0][8:]
def part1(input_data): """ >>> part1([0,3,6]) 436 >>> part1([1,3,2]) 1 >>> part1([2,1,3]) 10 >>> part1([1,2,3]) 27 >>> part1([2,3,1]) 78 >>> part1([3,2,1]) 438 >>> part1([3,1,2]) 1836 """ memory = input_data.copy() for i in range(2020-len(input_data)): last = memory[-1] new_entry = 0 len_memory = len(memory) for x in range(1, len_memory): if memory[len_memory-x-1] == last: new_entry = x break memory.append(new_entry) return memory[-1]
def dob_fun(dob): """This function takes a date of birth and checks whether it's valid or not. Parameters: dob: The date of the birth of the person. Returns: The proper date of birth of the person. """ condition = len(dob) == 10 and (dob[:4] + dob[5:7] + dob[8:]).isdigit() \ and dob[4] == '-' and dob[7] == '-' \ and int(dob[5:7]) <= 12 and int(dob[8:]) <= 30 while not(condition): dob = input("ERROR: Must follow 1970-01-01 format, try again: ") condition = len(dob) == 10 and (dob[:4] + dob[5:7] + dob[8:]).isdigit() \ and dob[4] == '-' and dob[7] == '-' \ and int(dob[5:7]) <= 12 and int(dob[8:]) <= 30 return dob
def small(txt): """ >>> print(small('I feel tiny')) <small>I feel tiny</small> >>> print(small('In a website I would be small...', tags=False)) In a website I would be small... """ return f'<small>{txt}</small>'
def _make_validation_key(game_id: str) -> str: """Make the redis key for game validation.""" return 'ttt:{}:valid'.format(game_id)
def get_package_name_list(package_list): """Take a list of package loaders and returns a list of package names """ package_name_list = [] for package in package_list: package_name_list.append(package.__name__) return package_name_list
def intersectionOfSortedArrays(a,b): """ less than o(m+n) complexity """ ia=0 ib=0 op=[] while ia<len(a) and ib<len(b): if a[ia] < b[ib]: ia+=1 elif a[ia] > b[ib]: ib+=1 else: op.append(a[ia]) ia+=1 return op
def isprivilege(value): """Checks value for valid privilege level Args: value (str, int): Checks if value is a valid user privilege Returns: True if the value is valid, otherwise False """ try: value = int(value) return 0 <= value < 16 except ValueError: return False
def round_up(value): """Replace the built-in round function to achieve accurate rounding with 2 decimal places :param value:object :return:object """ return round(value + 1e-6 + 1000) - 1000
def marquee(txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'. :Examples: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test ' """ if not txt: return (mark*width)[:width] nmark = (width-len(txt)-2)//len(mark)//2 if nmark < 0: nmark =0 marks = mark*nmark return '%s %s %s' % (marks,txt,marks)
def join_name_with_id(stations, data): """ Performs a join on stations and pollution data :param stations: list of stations data for a specific date :param data: pollution data :return: list of joined data """ mapping = {name.lower().strip(): id_station for id_station, name in stations} data = [{'id_station': mapping[row['name'].lower().strip()], **row} for row in data if row['name'].lower().strip() in mapping] for row in data: del row['name'] return data
def _stringify_time_unit(value: int, unit: str) -> str: """ Returns a string to represent a value and time unit, ensuring that it uses the right plural form of the unit. >>> _stringify_time_unit(1, "seconds") "1 second" >>> _stringify_time_unit(24, "hours") "24 hours" >>> _stringify_time_unit(0, "minutes") "less than a minute" """ if unit == "seconds" and value == 0: return "0 seconds" elif value == 1: return f"{value} {unit[:-1]}" elif value == 0: return f"less than a {unit[:-1]}" else: return f"{value} {unit}"
def is_testharness_baseline(filename): """Checks whether a given file name appears to be a testharness baseline. Args: filename: A path (absolute or relative) or a basename. """ return filename.endswith('-expected.txt')
def swap_list_order(alist): """ Args: alist: shape=(B, num_level, ....) Returns: alist: shape=(num_level, B, ...) """ new_order0 = len(alist[0]) return [[alist[i][j] for i in range(len(alist))] for j in range(new_order0)]
def format_error(error: BaseException) -> str: """Format an error as a human-readible string.""" return f"{type(error).__name__}: {error}"
def escape_env_var(varname): """ Convert a string to a form suitable for use as an environment variable. The result will be all uppercase, and will have all invalid characters replaced by an underscore. The result will match the following regex: [a-zA-Z_][a-zA-Z0-9_]* Example: "my.private.registry/cat/image" will become "MY_PRIVATE_REGISTRY_CAT_IMAGE" """ varname = list(varname.upper()) if not varname[0].isalpha(): varname[0] = "_" for i, c in enumerate(varname): if not c.isalnum() and c != "_": varname[i] = "_" return "".join(varname)
def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): """ This prototype should be used to create an iban object from iban correct string @param {String} iban """ return ((num == 0) and numerals[0]) or \ (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
def cut_off_string_edge_spaces(string): """ :type string: str :rtype: str """ while string.startswith(" "): string = string[1:] while string.endswith(" "): string = string[:-1] return string
def bisect_left_adapt(a, x): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(x) will insert just before the leftmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ lo = 0 hi = len(a) if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid return lo
def check_reporting_status(meta, fname): """Check an individual metadata and return logical status""" status = True if("reporting_status" not in meta): print("reporting_status missing in " + fname) status = False else: valid_statuses = ['notstarted', 'inprogress', 'complete', 'notrelevant'] if(meta["reporting_status"] not in valid_statuses): err_str = "invalid reporting_status in " + fname + ": " \ + meta["reporting_status"] + " must be one of " \ + str(valid_statuses) print(err_str) status = False return status
def merge_dict(dict1, dict2, path=None): """ Merge two dictionaries such that all the keys in dict2 overwrite those in dict1 """ if path is None: path = [] for key in dict2: if key in dict1: if isinstance(dict1[key], dict) and isinstance(dict2[key], dict): merge_dict(dict1[key], dict2[key], path + [str(key)]) elif isinstance(dict1[key], list) and isinstance(dict2[key], list): dict1[key] += dict2[key] else: dict1[key] = dict2[key] else: dict1[key] = dict2[key] return dict1
def solution(power): """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ num = 2 ** power string_num = str(num) list_num = list(string_num) sum_of_num = 0 for i in list_num: sum_of_num += int(i) return sum_of_num
def get_starlark_list(values): """Convert a list of string into a string that can be passed to a rule attribute.""" if not values: return "" return "\"" + "\",\n \"".join(values) + "\""
def _is_possible_expansion(acro: str, full: str) -> bool: """ Check whether all acronym characters are present in the full form. :param acro: :param full: :return: """ # Empty acronym is presented everywhere if not acro: return True # Non-empty acronym is not presented in empty full form if not full: return False # First char must be the same if acro[0].lower() != full[0].lower(): return False j = 0 # We then skip the first char, as it has already been checked for i in range(1, len(acro)): j += 1 while j < len(full): if acro[i].lower() == full[j].lower(): break j += 1 if j < len(full): return True return False
def get_parameters(runtime, environment): """ Set up parameters dictionary for format() substitution """ parameters = {'runtime': runtime, 'environment': environment} if environment is None: tmpl = 'enable-mapping-ci-{runtime}' environment = tmpl.format(**parameters) parameters['environment'] = environment return parameters
def FlagBelongsToRequiredGroup(flag_dict, flag_groups): """Returns whether the passed flag belongs to a required flag group. Args: flag_dict: a specific flag's dictionary as found in the gcloud_tree flag_groups: a dictionary of flag groups as found in the gcloud_tree Returns: True if the flag belongs to a required group, False otherwise. """ flag_group = flag_dict.get('group', None) flag_group_properties = flag_groups.get(flag_group, {}) return flag_group_properties.get('is_required', False)
def is_small_calcification(bb_width, bb_height, min_diam): """ remove blobs with greatest dimension smaller than `min_diam` """ if max(bb_width, bb_height) < min_diam: return True return False
def get_value_of_dict(dictionary, key): """ Returns the value of the dictionary with the given key. """ value = 0 try: value = dictionary[str(key)] except KeyError: pass return value
def find_subsequence(subseq, seq): """If subsequence exists in sequence, return True. otherwise return False. can be modified to return the appropriate index (useful to test WHERE a chain is converged) """ i, n, m = -1, len(seq), len(subseq) try: while True: i = seq.index(subseq[0], i + 1, n - m + 1) if subseq == seq[i:i + m]: #return i+m-1 (could return "converged" index here) return True except ValueError: return False
def get_largest_value(li): """Returns the largest value in the given list""" m = li[0] for value in li: if value > m: m = value return m
def counting_sort(data, mod): """ :param data: The list to be sorted. :param mod: exp(index of interest) """ buckets = [[] for _ in range(10)] for d in data: buckets[d//mod % 10].append(d) return sum(buckets, [])
def _format_secs(secs: float): """Formats seconds like 123456.7 to strings like "1d10h17m".""" s = "" days = int(secs / (3600 * 24)) secs -= days * 3600 * 24 if days: s += f"{days}d" hours = int(secs / 3600) secs -= hours * 3600 if hours: s += f"{hours}h" mins = int(secs / 60) s += f"{mins}m" return s
def convert_to_tuples(examples): """ Convert a list of Example objects to tuples of the form: (source, translation, language, author, reference). """ convert1 = lambda e: e.to_simple_tuple() return list(filter(bool, map(convert1, examples)))
def replace_char_with_space(text, chars): """From StackOverflow See: https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string """ for char in chars: text = text.replace(char, ' ') return text
def convert_bytes_in_results_tuple(results_tuple): """ Convert the varbinaries to unicode strings, and return a list of lists. """ return [[x.decode() if type(x) == bytes else x for x in row] for row in results_tuple]
def remove_html_tags(text): """Remove html tags from a string""" import re clean = re.compile('<.*?>') return re.sub(clean, '', text)
def is_twin_response_topic(topic): """Topics for twin responses are of the following format: $iothub/twin/res/{status}/?$rid={rid} :param str topic: The topic string """ return topic.startswith("$iothub/twin/res/")
def simple_request_messages_to_str(messages): """ Returns a readable string from a simple request response message Arguments messages -- The simple request response message to parse """ entries = [] for message in messages: entries.append(message.get('text')) return ','.join(entries)
def formatSearchQuery(query): """ It formats the search string into a string that can be sent as a url paramenter. """ return query.replace(" ", "+")
def create_logout_url(slug): """Creates a logout url.""" # Currently we have no way to implement this on non-GAE platforms # as a stand alone app. return ''
def is_builtin_entity(oid): """Return if the OID hex number is for a built-in entity.""" # More information in get_oid oid_num = int(oid, 16) return oid_num & 0xC0 == 0xC0
def negative_loop(dists): """ Check if the distance matrix contains a negative loop - i.e. you can get from some location back to that location again in negative time. You could just follow this loop many times until you got enough time to save all bunnies and exit """ return any([dists[x][x] < 0 for x in range(len(dists))])
def modexp3(b,m): """e=3, use addition chain""" b2=(b*b)%m b3=(b*b2)%m assert(b3==pow(b,3,m)) return b3
def abv_calc(og, fg, simple=None): """Computes ABV from OG and FG. Parameters ---------- og : float Original gravity, like 1.053 fg : float Final gravity, like 1.004 simple : bool or None, defaults to None. Flag specifying whether to use the simple (linear) equation or the more complicated nonlinear equation. The simple equation is generally appropriate provided the difference in original and final gravities is less than 0.05. If None, this function will decide for itself which formula to use. Returns ------- abv : float Alcohol by volume, like 0.064. """ if (simple is None and og < fg + 0.05) or simple: return (og - fg) * 1.3125 else: return (0.7608 * (og - fg) / (1.775 - og)) * (fg / 0.794)
def make_run_list(run_csvs): """ Reads list of csvs to give performance of the different hyperparameter settings. Returns ------- data_list : list of numpy.ndarrays performance of different hyperaparameter settings for the csvs given as input. """ import csv data_list = [] for a_csv in run_csvs: with open(a_csv, 'r') as f: reader = csv.reader(f) data_as_list = list(reader) f.close() data_list.append(data_as_list) return data_list
def hamming_distance(s1, s2): """ Get Hamming distance: the number of corresponding symbols that differs in given strings. """ return sum(i != j for (i,j) in zip(s1, s2) if i != 'N' and j != 'N')
def population_attributable_fraction(a, b, c, d): """Calculates the Population Attributable Fraction from count data Returns population attribuable fraction a: -count of exposed individuals with outcome b: -count of unexposed individuals with outcome c: -count of exposed individuals without outcome d: -count of unexposed individuals without outcome """ if (a < 0) or (b < 0) or (c < 0) or (d < 0): raise ValueError('All numbers must be positive') rt = (a + c) / (a + b + c + d) r0 = c / (c + d) return (rt - r0) / rt
def get_file_size(fileobj): """ Returns the size of a file-like object. """ currpos = fileobj.tell() fileobj.seek(0, 2) total_size = fileobj.tell() fileobj.seek(currpos) return total_size
def rewrite( string: str, charmap: dict = { 'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'a': 't', 't': 'a', 'c': 'g', 'g': 'c', }, sep: str = '', ) -> str: """ Given a sequence derived from 'ATCG', this function returns the complimentary base pairs of the given dna sequence Dependencies: None Arguments: permutation from 'ATCG' Out: compliment of input """ return sep.join([charmap[string[i]] for i in range(len(string))])
def sansa_xor(arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/sansa-and-xor/problem Sansa has an array. She wants to find the value obtained by XOR-ing the contiguous subarrays, followed by XOR-ing the values thus obtained. Determine this value. Solve: By going through and XOR'ing the subarrays, you can determine that for even numbered arrays, you always end up with 0 because you XOR each value in the array with itself which always returns 0. For example, for a subarray [1, 2], you would have 1 XOR 2 XOR (1 XOR 2), so 1 and 2 both show up twice and will return 0. For arrays of odd length, you can determine that each value of an even index position shows up an odd number of times, and values in an odd index position in the array show up an even number of times. Knowing this, we can determine that the values in the odd index positions will once again 0 themselves out, so all that is left is for us to XOR each value in the array in an even index position. That value is the result and the answer. Args: arr: array of integers to test Returns: int: The result after running through sansa's XOR algorithm """ if len(arr) % 2: val = 0 for x in arr[::2]: val = val ^ x return val else: return 0
def list_to_string(in_list, conjunction): """Simple helper for formatting lists contaings strings as strings. This is intended for simple lists that contain strings. Input will not be checked. :param in_list: List to be converted to a string. :param conjunction: String - conjunction to be used (e.g. and, or). """ return ", ".join(in_list[:-1]) + ", {} {}".format(conjunction, in_list[-1])
def build_cmd(*args, **kwargs): """ >>> build_cmd('script.py', 'train', model_pickle='tmp.pkl', shuffle=True) 'script.py train --model_pickle "tmp.pkl" --shuffle' """ options = [] for key, value in kwargs.items(): if isinstance(value, bool): options.append("--%s" % key) elif isinstance(value, int) or isinstance(value, float): options.append("--%s %s" % (key, value)) else: options.append('--%s "%s"' % (key, value)) return " ".join(list(args) + options)
def isWinner(board): """Looks at `board` and returns either '1' or '2' if there is a winner or 'tie' or 'no winner' if there isn't. The game ends when a player has 24 or more seeds in their mancala or one side of the board has 0 seeds in each pocket.""" b = board # Make a shorter variable name to use in this function. # If either players has >= 24 or no seeds, the game ends. if (b['1'] >= 24) or (b['2'] >= 24) or \ (b['A'] + b['B'] + b['C'] + b['D'] + b['E'] + b['F'] == 0) or \ (b['G'] + b['H'] + b['I'] + b['J'] + b['K'] + b['L'] == 0): # Game is over, find player with largest score. if b['1'] > b['2']: return '1' elif b['2'] > b['1']: return '2' else: return 'tie' return 'no winner'
def cell_color(color): """Return the color of a cell given its container and the specified color""" return r'\cellcolor{' + color + '}' if color else ''
def add_if_not_none(a, b): """Returns a/b is one of them is None, or their sum if both are not None.""" if a is None: return b if b is None: return a return a + b
def consecutive_3_double(word): """Checks word for 3 consecutive double letters. Return Boolean""" for i in range(len(word)-5): if word[i] == word[i+1]: if word[i+2] == word[i+3]: if word[i+4] == word[i+5]: return True return False
def echo_magic(rest): """ Echo the argument, for testing. """ return "print(%r)" % rest
def get_relationship_by_type(rels, rel_type): """ Finds a relationship by a relationship type Example:: # Import from cloudify import ctx from cloudify_azure import utils # Find a specific relationship rel = utils.get_relationship_by_type( ctx.instance.relationships, 'cloudify.azure.relationships.a_custom_relationship') :param list<`cloudify.context.RelationshipContext`> rels: \ List of Cloudify instance relationships :param string rel_type: Relationship type :returns: Relationship object or None :rtype: :class:`cloudify.context.RelationshipContext` """ if not isinstance(rels, list): return None for rel in rels: if rel_type in rel.type_hierarchy: return rel return None
def get_starting_chunk(content, length=1024): """ :param content: File content to get the first little chunk of. :param length: Number of bytes to read, default 1024. :returns: Starting chunk of bytes. """ # Ensure we open the file in binary mode chunk = content[0:length] return chunk
def anchorName(symId): """HTML links are not case-sensitive, so we have to modify upper/lowercase symbols to distinguish them""" if symId[:1].isupper(): return symId else: return '__'+symId
def qs_uses_ssl(qs): """ By default, we don't use SSL. If ?ssl=true is found, we do. """ for ssl_value in qs.get('ssl', []): if ssl_value == "true": return True return False
def zmqUDS(mnt_pt): """ Set the zmq address as a Unix Domain Socket: ipc://file """ return 'ipc://{}'.format(mnt_pt)
def calc_ongrid(elec, mix, tech_lut, elec_types, emission_type): """ Calculate the emissions for a given electricity and emission type. Parameters ---------- elec : int The quantity of electricity consumption estimated for the settlement. mix : list of dicts Contains the electricity generation mix. tech_lut : dict Contains emission information for on-grid or off-grid technologies. elec_types : string The generation types of the electricity to calculate. emission_type : string The emissions type for the electricity to calculate. Returns ------- emissions : int The estimated emissions for the stated electricity consumption. """ emissions = 0 for elec_type in elec_types: emissions += elec * mix[elec_type] * tech_lut[elec_type][emission_type] return emissions
def get_small_joker_value(deck_of_cards): """ (list of int) -> int Return the second largest value in deck_of_cards as the value of small joker. >>> get_small_joker_value([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 3, 6, 9, \ 12, 15, 18, 21, 24, 27, 2, 5, 8, 11, 14, 17, 20, 23, 26]) 27 >>> get_small_joker_value([1, 4, 7, 10, 13, 16, 19, 22, 25, 3, 6, 9, \ 12, 15, 18, 21, 24, 2, 5, 8, 11, 14, 17, 20, 23, 26]) 25 """ # Make a copy of the deck_of_cards to avoid modifying the deck_of_cards. copy = deck_of_cards.copy() # Remove the largest value in the copy list to let the second # largest value become the largest one. copy.remove(max(copy)) return max(copy)
def add_subdir(config): """ Add subdir back into config """ if not config: return config if 'context' in config: config['subdir'] = config['context'] return config