content
stringlengths
42
6.51k
def emoji_usage(emoji_list, output_dict): """ Collect emoji usage """ for emo in emoji_list: if emo not in output_dict: output_dict[emo] = 1 else: output_dict[emo] += 1 return output_dict
def split_paragraphs(text, min_length=30): """Extract a list of paragraphs from text Return a list of strings. Paragraphs are separated by double "new-line" characters. Any paragraph shorter than min_length is dropped. Any whitespaces at the beginning or ending of paragraphs are trimmed. """ paragraphs = [p.strip() for p in text.split("\n\n")] return [p for p in paragraphs if len(p) >= min_length]
def get_spec_assets(balances, assets): """ Select only coins which user wants to calculate for final asset. """ your_balances = {} choosed_assets = [a.upper() for a in assets] for balance in balances: asset = balance["asset"] if asset in choosed_assets: your_balances[asset] = float(balance.get( "free", 0)) + float(balance.get("locked", 0)) if not your_balances: print("Your codes of coins did not found.") return your_balances
def parse_ip(ip_str): """ Parse an IP address Parse an IP address '.' separated string of decimal digits to an host ordered integer. '172.24.74.77' => @param ip_str The string to convert @return Integer value """ array = map(lambda val: int(val), ip_str.split(".")) val = 0 for a in array: val <<= 8 val += a return val
def analyseWords(mywords, additionals=''): """Analyse mywords and return all used characters. The characters are sorted by occurence (descending). """ mydict = {} moreletters = [] for word in mywords: # create dict with occurence of letters in all words for letter in word.lower(): if additionals and (letter in additionals): moreletters = additionals[letter] for letter in moreletters: if letter in mydict: mydict[letter] += 1 else: mydict[letter] = 1 if letter in mydict: mydict[letter] += 1 else: mydict[letter] = 1 # pairs in mydict dictionary sorted by occurence (descending) # http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value # pairlist looks like this: [('e', 167410), ('n', 100164),...] pairlist = sorted(mydict.items(), key=lambda x: x[1], reverse=True) occurencestring = '' for pair in pairlist: occurencestring += pair[0] # use 1st element of each pair return list(occurencestring.lower())
def clean_context(context): """ This function take a dictionary and remove each entry with its key starting with 'default_' """ return {k: v for k, v in context.items() if not k.startswith('default_')}
def bits(s, e, byte): """ Extract bits start, end, byte Ex. bits(4,2,27) == 0b110 (extracting bits 4, 3 and 2) """ byte = byte>>e return byte & [1, 3, 7, 15, 31, 63, 127, 255][s-e]
def make_path(wname, wdate, sname, sdate): """Create the api path base string to append on livetiming.formula1.com for api requests. The api path base string changes for every session only. Args: wname: Weekend name (e.g. 'Italian Grand Prix') wdate: Weekend date (e.g. '2019-09-08') sname: Session name 'Qualifying' or 'Race' sdate: Session date (formatted as wdate) Returns: relative url path """ smooth_operator = f'{wdate[:4]}/{wdate} {wname}/{sdate} {sname}/' return '/static/' + smooth_operator.replace(' ', '_')
def transform_feature_on_popularity(feature: str, feature_popularity: dict) -> str: """ INPUT feature - any categorical feauture (e.g., Developer, full-stack; Developer, back-end) feature_popularity - a dictionary mapping the feature to popularity OUTPUT transformed feature - the more popular feature value (e.g., Developer, full-stack) """ feature_types = feature.split(';') max_pop = -1 popular_feature_type = 'None' for r in feature_types: pop = feature_popularity.get(r, -1) if pop > max_pop: popular_feature_type = r max_pop = pop return popular_feature_type
def elf_hash(name): """ ELF hashing function. See figure 2-15 in the ELF format PDF document. """ h = 0 for c in name: h = (h << 4) + ord(c) g = h & 0xF0000000 if g: h ^= g >> 24 h &= ~g assert h >= 0 return h
def convert_list2str(list_data, space_mark = ''): """ :param list_data: One-dimensional list data :param space_mark: The spacing symbol between string :return: List of converted strings """ s = "" list_len = len(list_data) for i in range(list_len): data = list_data[i] s += str(data) if i < list_len - 1: s += space_mark return s
def force_list_to_length(list, length): """ Force a list to be a certain list in order that it can be stacked with other lists to make an array when working out epidemiological outputs. No longer used because was for use in model_runner to make all the new data outputs the same length as the first. However, now the approach is to make all the data outputs the same length as the longest one, by sticking zeros on at the start where necessary. Args: list: The list that needs its length adapted length: The desired length as an integer Returns: The list in its adapted form, either unchanged, truncated to desired length or with zeroes added to the start """ if len(list) == length: return list elif len(list) > length: return list[-length:] elif len(list) < length: return [0.] * (length - len(list)) + list
def allindex(value, inlist): """ Mathematica Positions -equivalent :param value: :param inlist: list from which to find value :return: all indices """ # indices = [] # idx = -1 # while True: # try: # idx = qlist.index(value, idx+1) # indices.append(idx) # except ValueError: # break # return indices return [i for i, x in enumerate(inlist) if x == value]
def _nuke_newlines(p_string): """ Strip newlines and any trailing/following whitespace; rejoin with a single space where the newlines were. Trailing newlines are converted to spaces. Bug: This routine will completely butcher any whitespace-formatted text. @param p_string: A string with embedded newline chars. """ if not p_string: return '' l_lines = p_string.splitlines() return ' '.join([l_line.strip() for l_line in l_lines])
def suppressMultipleSpaces(x): """ Returns the string X, but with multiple spaces (as found in Metro Transit return values) with single spaces. """ while x.find(" ") >= 0: x = x.replace(" "," ") return x
def html_decode(s): """ Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like <p>. """ htmlCodes = (("'", '&#39;'), ('"', '&quot;'), ('>', '&gt;'), ('<', '&lt;'), ('&', '&amp;'),(' ','&nbsp;'),('"','&#34;')) for code in htmlCodes: s = s.replace(code[1], code[0]) return s
def output_clock_freq(session, Type='Real64', RepCap='', AttrID=1150004, buffsize=0, action=['Get', '']): """[Output Clock Frequency <real64>] This READ-ONLY attribute is used to ascertain the current clock frequency. Changes to the clock frequency must be accomplished with the OutputConfigureSampleClock function. """ return session, Type, RepCap, AttrID, buffsize, action
def join_(str_, iterable): """functional version of method join of class str """ return str_.join(map(str,iterable))
def dict_list_search(l, keys, value): """ Search a list of dictionaries of a common schema for a specific key/value pair. For example: l = [{'a': foo, 'b': 1, 'c': 2}, {'a': 'bar', 'b': 3, 'c': 4}] If `keys='a'` and `value='foo'` then the first dict in the list would be returned. """ values_list = [d[keys] for d in l] try: idx = values_list.index(value) except ValueError: raise ValueError(f"A pair matching {{{keys}: {value}}} could not be found.") else: return l[idx]
def transpose_list(list_of_dicts): """Transpose a list of dicts to a dict of lists. :param list_of_dicts: to transpose, as in the output from a parse call :return: Dict of lists """ res = {} for d in list_of_dicts: for k, v in d.items(): if k in res: res[k].append(v) else: res[k] = [v] return res
def _translate_time(time): """ Translate time from format: Feb 8 01:44:59 EST 2013 to format: 2013/03/06-00:17:54 """ # get all parts time_parts = time.split() # do we have the correct number of parts? if len(time_parts) != 5: raise Exception("Unexpected number of parts in time: " + time) # validate month months = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr": "04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"} if time_parts[0] in months: time_parts[0] = months.get(time_parts[0]) else: raise Exception("Unexpected format when translating month " + time_parts[0] + " of time: " + time) # time_parts[1] should be a number representing the day. try: int(time_parts[1]) except ValueError: raise Exception("Unexpected format when translating day " + time_parts[1] + " of time: " + time) else: # if day is less than 10 prepend a 0. if int(time_parts[1]) < 10: time_parts[1] = "0" + time_parts[1] # validate hour:minute:second hour_minute_second = time_parts[2].split(":") if (len(hour_minute_second) != 3 or not hour_minute_second[0].isdigit() or not hour_minute_second[1].isdigit() or not hour_minute_second[2].isdigit()): raise Exception("Unexpected format when translating " "hour:minute:second " + time_parts[2] + " of time: " + time) # time_parts[4] should be a number representing the year. try: int(time_parts[4]) except ValueError: raise Exception("Unexpected format when translating year " + time_parts[4] + " of time: " + time) return (time_parts[4] + "/" + time_parts[0] + "/" + time_parts[1] + "-" + time_parts[2])
def highlight_pos(cell): """ helper function for pd.DataFrame display options. It changes color of text in cell to green, red, orange depending on value Parameters ---------- cell: value in pd.DataFrame cell Returns ------- str : color of text in cell """ # If cell is number and negative then red if type(cell) != str and cell < 0: return 'color: red' # If cell is number and equall 0 then orange elif type(cell) != str and cell == 0: return 'color: orange' # If cell is number and positive then green else: return 'color: green'
def removeprefix(prefix: str, string: str) -> str: """Remove the prefix from the string""" return string[len(prefix) :] if string.startswith(prefix) else string
def bucket_bin(item, ndivs, low, width): """ Return the bin for an item """ assert item >= low, Exception("negative bucket index") return min(int((item - low) / width), ndivs-1)
def binary_range(bits): """Return a list of all possible binary numbers in order with width=bits. It would be nice to extend it to match the functionality of python's range() built-in function. """ l = [] v = ['0'] * bits toggle = [1] + [0] * bits while toggle[bits] != 1: v_copy = v[:] v_copy.reverse() l.append(''.join(v_copy)) toggle = [1] + [0]*bits i = 0 while i < bits and toggle[i] == 1: if toggle[i]: if v[i] == '0': v[i] = '1' toggle[i+1] = 0 else: v[i] = '0' toggle[i+1] = 1 i += 1 return l
def print_summary(targets): """ Return 0 if all test passed Return 1 if all test completed but one or more failed Return 2 if one or more tests did not complete or was not detected """ passed = 0 failed = 0 tested = 0 expected = 0 return_code = 3 print("-----------------------------------------------------------------------------------------------------------") # Find all passed and failed for target in targets: for test in target["tests"]: expected += 1 if target[test]["tested"]: tested += 1 else: print("ERROR: Test {} for target {} not found".format(test, target["name"])) if target[test]["pass"]: passed += 1 else: failed += 1 if tested != expected: print("ERROR: Not all tests found!") print("Expected: {} Actual: {}".format(expected, tested)) return_code = 2 elif tested == passed: return_code = 0 else: return_code = 1 print("Summary: {} tests in total passed on {} targets ({})". format(passed, len(targets), ', '.join([t['name'] for t in targets]))) # Print those that failed if failed > 0: print() for target in targets: for test in target["tests"]: if not target[test]["pass"]: print("{}: {} failed".format(target["name"], test)) if (passed > 0): print("{:.0f}% tests passed, {} tests failed out of {}".format(passed/expected*100, failed, expected)) else: print("0% tests passed, {} tests failed out of {}".format(failed, tested)) return return_code
def group_consecutives(vals, step=1): """ Return list of consecutive lists of numbers from vals (number list). References: Modified from the following https://stackoverflow.com/questions/7352684/ how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy """ run = list() result = [run] expect = None for v in vals: if (v == expect) or (expect is None): run.append(v) else: run = [v] result.append(run) expect = v + step return result
def evapor_channel(Vc0, ETo, W, X): """Compute the evaporation from a channel store. Calculate the evaporation loss from a channel store. The function attempts to remove the demand from the open water potential evaporation from the channel store, if there isn't sufficient water in the store then the total volume in the channel is removed. Parameters ---------- Vc0 : scalar Volume in the channel store before evaporation removal (:math:`m^3`) ETo : scalar The potential evaporation from an open water surface (:math:`mm`) W : scalar Width of the channel (:math:`m`) X : scalar The length of the channel cell, this can be different from the cell dimension if the channel runs along the cell diagonal (:math:`m`) Returns ------- ET_channel : scalar The actual depth of water removed from the channel store (:math:`mm`) Vc1 : scalar Volume in the channel store after evaporation removal (:math:`m^3`) """ ETo = ETo*1e-3 if Vc0-ETo*W*X > 0: Vc1 = Vc0-ETo*W*X Vevap_c = ETo*W*X else: Vc1 = 0 Vevap_c = Vc0 ET_channel = Vevap_c*1e3/(W*X) return ET_channel, Vc1
def shout_echo(word1,echo=1,intense=False): """Concatenate echo copies of word1 and three exclamation marks at the end of the string.""" # Concatenate echo copies of word1 using *: echo_word echo_word = word1 * echo # Capitalize echo_word if intense is True if intense is True: # Capitalize and concatenate '!!!': echo_word_new echo_word_new = echo_word.upper() + '!!!' else: # Concatenate '!!!' to echo_word: echo_word_new echo_word_new = echo_word + '!!!' # Return echo_word_new return echo_word_new
def _dict_diff(old: dict, new: dict) -> dict: """ Recursive find differences between two dictionaries. :param old: Original dictionary. :param new: New dictionary to find differences in. :return: Dictionary containing values present in :py:attr:`new` that are not in :py:attr:`old`. """ out = {} for key, value in new.items(): if key in old: if type(value) is dict: diff = _dict_diff(old[key], value) if diff == {}: continue else: out[key] = diff elif old[key] == value: continue else: out[key] = value else: out[key] = value return out
def generate_resource_url( url: str, resource_type: str = "", resource_id: str = "", version: str = "v1" ) -> str: """ Generate a resource's URL using a base url, the resource type and a version. """ return f"{url}/{resource_type}/{resource_id}"
def get_igmp_status(cli_output): """ takes str output from 'show ip igmp snooping | include "IGMP Snooping" n 1' command and returns a dictionary containing enabled/disabled state of each vlan """ search_prefix = "IGMP Snooping information for vlan " vlan_status={} counter = 0 line_list = cli_output.splitlines() for line in line_list: if line.startswith(search_prefix): vlan_status.update({line.strip(search_prefix):line_list[counter+1].strip('IGMP snooping ')}) counter += 1 return vlan_status
def get_RB_data_attribute(xmldict, attr): """Get Attribute `attr` from dict `xmldict` Parameters ---------- xmldict : dict Blob Description Dictionary attr : string Attribute key Returns ------- sattr : int Attribute Values """ try: sattr = int(xmldict['@' + attr]) except KeyError: if attr == 'bins': sattr = None else: raise KeyError('Attribute @' + attr + ' is missing from Blob Description' 'There may be some problems with your file') return sattr
def euler_tour_dfs(G, source=None): """adaptation of networkx dfs""" if source is None: # produce edges for all components nodes = G else: # produce edges for components with source nodes = [source] yielder = [] visited = set() for start in nodes: if start in visited: continue visited.add(start) stack = [(start, iter(G[start]))] while stack: parent, children = stack[-1] try: child = next(children) if child not in visited: # yielder += [[parent, child]] yielder += [parent] visited.add(child) stack.append((child, iter(G[child]))) except StopIteration: if stack: last = stack[-1] yielder += [last[0]] stack.pop() return yielder
def _is_str(text): """Checks whether `text` is a non-empty str""" return isinstance(text, str) and text != ""
def mergeHalves(leftHalf, rightHalf): """ Merge two halves and return the merged data list """ sortedData = list() while leftHalf and rightHalf: smallerDataHolder = leftHalf if leftHalf[0] < rightHalf[0] else rightHalf minData = smallerDataHolder.pop(0) sortedData.append(minData) remaininData = leftHalf if leftHalf else rightHalf while remaininData: sortedData.append(remaininData.pop(0)) return sortedData
def FilterKeptAttachments( is_description, kept_attachments, comments, approval_id): """Filter kept attachments to be a subset of last description's attachments. Args: is_description: bool, if the comment is a change to the issue description. kept_attachments: list of ints with the attachment ids for attachments kept from previous descriptions, if the comment is a change to the issue description. comments: list of IssueComment PBs for the issue we want to edit. approval_id: int id of the APPROVAL_TYPE fielddef, if we're editing an approval description, or None otherwise. Returns: A list of kept_attachment ids that are a subset of the last description. """ if not is_description: return None attachment_ids = set() for comment in reversed(comments): if comment.is_description and comment.approval_id == approval_id: attachment_ids = set([a.attachment_id for a in comment.attachments]) break kept_attachments = [ aid for aid in kept_attachments if aid in attachment_ids] return kept_attachments
def node_para(args): """ Node parameters. :param args: args :return: node config or test node config list """ node_list = [] i = 0 if args.find("//") >= 0: for node in args.split("//"): node_list.append([]) ip, name, passwd = node.split(",") node_list[i].append(ip) node_list[i].append(name) node_list[i].append(passwd) i += 1 else: node_list.append([]) ip, name, passwd = args.split(",") node_list[i].append(ip) node_list[i].append(name) node_list[i].append(passwd) return node_list
def new_value(seat: str, neighbors: str): """ Returns the new state of one seat. """ occupied_count = neighbors.count("#") if seat == "L" and occupied_count == 0: return "#" elif seat == "#" and 4 <= occupied_count: return "L" else: return seat
def find_digits(n): """Hackerrank Problem: https://www.hackerrank.com/challenges/find-digits/problem An integer d is a divisor of an integer n if the remainder of n / d = 0. Given an integer, for each digit that makes up the integer determine whether it is a divisor. Count the number of divisors occurring within the integer. Args: n (int): integer to check Returns: int: the number of digits that divide evenly into the integer """ digits = 0 for i in str(n): if int(i) != 0 and n % int(i) == 0: digits += 1 return digits
def _GetExceptionName(cls): """Returns the exception name used as index into _KNOWN_ERRORS from type.""" return cls.__module__ + '.' + cls.__name__
def fib(n): """ Calculate a fibonacci number """ a, b = 0, 1 for _ in range(n): a, b = b, a + b return a
def relative_target_price_difference(side: str, target_price: float, current_price: float) -> float: """ Returns the relative difference of current_price from target price. Negative vallue could be considered as "bad" difference, positive as "good". For "sell" order: relative_target_price_difference = (target_price / current_price) - 1 For "buy" orders: relative_target_price_difference = (current_price / target_price) - 1 Means that for "buy" order if the price is greater that the target price - the relative difference will be negative. For "sell" orders: if the price will be less than target price - the rel. difference will be negative. :param side: side of the order to compare :param target_price: the price to compare with :param current_price: the price which is being compared to target price :return: relative difference between the current_price and target_price regarding the order's side or None """ result = None if side.lower() == "sell": result = (current_price / target_price) - 1 return result if side.lower() == "buy": result = 1 - (current_price / target_price) return result raise (ValueError("Wrong side of the order {}".format(side)))
def iou(box1, box2): """ From Yicheng Chen's "Mean Average Precision Metric" https://www.kaggle.com/chenyc15/mean-average-precision-metric helper function to calculate IoU """ x11, y11, x12, y12 = box1 x21, y21, x22, y22 = box2 w1, h1 = x12-x11, y12-y11 w2, h2 = x22-x21, y22-y21 area1, area2 = w1 * h1, w2 * h2 xi1, yi1, xi2, yi2 = max([x11, x21]), max( [y11, y21]), min([x12, x22]), min([y12, y22]) if xi2 <= xi1 or yi2 <= yi1: return 0 else: intersect = (xi2-xi1) * (yi2-yi1) union = area1 + area2 - intersect return intersect / union
def padded_slice_filter(value, page_number): """ Templatetag which takes a value and returns a padded slice """ try: bits = [] padding = 5 page_number = int(page_number) if page_number - padding < 1: bits.append(None) else: bits.append(page_number - padding) if page_number + padding > len(value): bits.append(len(value)) else: bits.append(page_number + padding) return value[slice(*bits)] except (ValueError, TypeError): # Fail silently. return value
def merge(left: list, right: list) -> list: """Merges 2 sorted lists (left and right) in 1 single list, which is returned at the end. Time complexity: O(m), where m = len(left) + len(right).""" mid = [] i = 0 # Used to index the left list. j = 0 # Used to index the right list. while i < len(left) and j < len(right): if left[i] < right[j]: mid.append(left[i]) i += 1 else: mid.append(right[j]) j += 1 while i < len(left): mid.append(left[i]) i += 1 while j < len(right): mid.append(right[j]) j += 1 return mid
def resolve_name_obj(name_tree_kids): """Resolve 'Names' objects recursively. If key 'Kids' exists in 'Names', the name destination is nested in a hierarchical structure. In this case, this recursion is used to resolve all the 'Kids' :param name_tree_kids: Name tree hierarchy containing kid needed to be solved :return: Resolved name tree list """ temp_list = [] for kid in name_tree_kids: if 'Kids' in kid and kid['Kids']: temp_list.extend([kid_kid.resolve() for kid_kid in kid['Kids']]) elif 'Names' in kid: return name_tree_kids return resolve_name_obj(temp_list)
def array_check(lst): """ Function to check whether 1,2,3 exists in given array """ for i in range(len(lst)-2): if lst[i] == 1 and lst[i+1] == 2 and lst[i+2] == 3: return True return False
def num(mensurationString): """Transform the characters 'p' and 'i' to the values '3' and '2', respectively, and return the appropriate numeric value. Arguments: mensurationString -- one-character string with two possible values: 'i' or 'p' """ strings_for_mensuration = ['p', 'i'] numbers_for_mensuration = ['3', '2'] mensurationNumber = numbers_for_mensuration[strings_for_mensuration.index(mensurationString)] return mensurationNumber
def b2s(b): """ Binary to string. """ ret = [] for pos in range(0, len(b), 8): ret.append(chr(int(b[pos:pos + 8], 2))) return "".join(ret)
def interval_to_milliseconds(interval): """Convert a Bitrue interval string to milliseconds :param interval: Bitrue interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: None if unit not one of m, h, d or w None if string not in correct format int value of interval in milliseconds """ ms = None seconds_per_unit = { "m": 60, "h": 60 * 60, "d": 24 * 60 * 60, "w": 7 * 24 * 60 * 60 } unit = interval[-1] if unit in seconds_per_unit: try: ms = int(interval[:-1]) * seconds_per_unit[unit] * 1000 except ValueError: pass return ms
def cubeSum(num): """assumes num is an int returns an int, the sum of cubes of the ints 1 to n""" cube_sum = 0 for i in range(1, num+1): cube_sum += i**2 return cube_sum
def find_cnc_loc(code): """get CNC's location""" if code in [1, 2]: cnc_loc = 0 elif code in [3, 4]: cnc_loc = 1 elif code in [5, 6]: cnc_loc = 2 else: cnc_loc = 3 return cnc_loc
def reverseNumberv3(num): """assumes num is a int returns an int, the reverse of num""" holding_num = num return_num = 0 while holding_num > 0: return_num += (holding_num % 10) * (10 ** (len(str(holding_num)) - 1)) holding_num //= 10 return return_num
def check_valid_relname(schema, relname, tables_in_table_file, schemas_in_schema_file=None): """ check if relation is valid (can be from schema level restore) """ if ((schemas_in_schema_file and schema in schemas_in_schema_file) or (tables_in_table_file and (schema, relname) in tables_in_table_file)): return True return False
def add_strings(a, b): """Add two floats that are stored as strings""" return sum(map(float, (a, b)))
def iswinner(board, piece: str) -> int: """ piece - string - Either an "X" or "O" Checks if win conditions are met. Could check only relevant squares but not as readable. """ # Checks each row, then each col, and then the diagonals for line in [[x + 3 * y for x in range(3)] for y in range(3)] + \ [[3 * x + y for x in range(3)] for y in range(3)] + \ [[3 * x + x for x in range(3)]] + \ [[3 * x + 2 - x for x in range(3)]]: if all(board[sq] == piece for sq in line): return True return False
def compare_lists(la, lb): """Compare two lists.""" if len(la) != len(lb): return 1 for i in range(0, len(la)): sa = la[i] sb = lb[i] if sa != sb: return 1 return 0
def SanitizeJs(s): """Sanitizes JS input""" return s.lower().replace('script', 'span')
def combine_exif(exif_data, lut, d): """ Add extracted exif information to master list of HP data :param exif_data: dictionary of data extracted from an image :param lut: LUT to translate exiftool output to fields :param fields: master dictionary of HP data :return: fields - a dictionary with updated exif information """ for k in lut: if k in exif_data and exif_data[k] != '-': d[lut[k]] = exif_data[k] return d
def quaternary_spherical(rho, phi): """Zernike quaternary spherical.""" return 252 * rho**10 \ - 630 * rho**8 \ + 560 * rho**6 \ - 210 * rho**4 \ + 30 * rho**2 \ - 1
def clamp_str(string, **kwargs): """Returns 'foo...' for clamped strings. Args: maxlen: limits of the string length eat_lf: if True, replaces \n with their textual representation <Ignores other arguments> """ maxlen = kwargs.get('maxlen', 50) if maxlen > 3 and len(string) >= (maxlen - 2): string = string[0:maxlen-3] + '...' if kwargs.get('eat_lf', False): string = string.replace('\n', r'\n').replace('\r', r'\r') return string
def _are_all_ints(arr): """Check whether all elements in arr are ints.""" for a in arr: if not isinstance(a, int): return False return True
def index_of(lst, search_item) -> int: """ Returns the index of the item in the list or -1. Args: lst: The list. search_item: The item to search for. Returns: The index in the list of the item or -1. """ for idx, item in enumerate(lst): if item == search_item: return idx return -1
def roll(x, n): """ The roll function Lifted from https://www.johndcook.com/blog/2019/03/03/do-the-chacha/ """ return ((x << n) & 0xffffffff) + (x >> (32 - n))
def prepare_update_sql(list_columns, list_values, data_code=100): """ Creates a string for the update query :param list_columns: columns that are in need of an update :param list_values: values where the columns should be updated with :param data_code: data code to add to the columns :return: string with the columns and update values """ string = '' for i in enumerate(list_columns): if list_values[i[0]] is not None: if len(i[1]) >= 50: new_label = i[1][:50] + '_' + str(data_code) string = string + '`' + new_label + '`' + '= ' + '\'' + str(list_values[i[0]]) + '\'' + ', ' else: string = string + '`' + i[1] \ + '_' + str(data_code) + '`' + '= ' + '\'' + str(list_values[i[0]]) + '\'' + ', ' string = string.replace("None", "Null") return string[:-2]
def is_hidden(method_name): """Return `True` if not an interface method.""" return method_name.startswith('_')
def IsSubclass(candidate, parent_class): """Calls issubclass without raising an exception. Args: candidate: A candidate to check if a subclass. parent_class: A class or tuple of classes representing a potential parent. Returns: A boolean indicating whether or not candidate is a subclass of parent_class. """ try: return issubclass(candidate, parent_class) except TypeError: return False
def make_scored_lexicon_dict(read_data): """ Convert lexicon file to a dictionary """ lex_dict = dict() for line in read_data.split('\n'): if not(line.startswith('#')): (word, measure) = line.strip().split('\t')[0:2] lex_dict[word] = float(measure) return lex_dict
def get_comp_optional_depends_r(comp_info, comps, mandatory_comps): """ Get comp optional depends recursively from comp index """ depends = [] """ comps are optional dependency list from last layer """ for comp in comps: # print("comp name is:", comp["comp_name"]) if comp["comp_name"] not in comp_info: continue """ get mandatory dependency list for this optional component """ for dep_info in comp_info[comp["comp_name"]]["dependencies"]: if dep_info not in mandatory_comps: """ add to the list with the inherrited dependency""" tmp = {} tmp["comp_name"] = dep_info tmp["condition"] = comp["condition"] depends.append(tmp) # print("add mandatory depend r:", tmp, "for", comp["comp_name"]) """ get optional dependency list for this optional component """ for dep_info in comp_info[comp["comp_name"]]["optional_dependencies"]: if dep_info["comp_name"] not in mandatory_comps: """ add to the list with (the inherrited dependency && this condition) """ tmp = {} tmp["comp_name"] = dep_info["comp_name"] tmp["condition"] = comp["condition"] + ["and"] + dep_info["condition"] depends.append(tmp) # print("add optional depend r:", tmp, "for", comp["comp_name"]) if depends: depends += get_comp_optional_depends_r(comp_info, depends, mandatory_comps) return depends
def relative_roughness(roughness, diameter): """Returns relative roughness. :param roughness: roughness of pipe [mm] or [m] (but the same as diameter) :param diameter: diameter of duct or pipe [mm] or [m] """ return round(roughness / diameter, 8)
def convert(item, cls, default=None): """ Convert an argument to a new type unless it is `None`. """ return default if item is None else cls(item)
def make_layer_list(arch, network_type=None, reg=None, dropout=0): """ Generates the list of layers specified by arch, to be stacked by stack_layers (defined in src/core/layer.py) arch: list of dicts, where each dict contains the arguments to the corresponding layer function in stack_layers network_type: siamese or spectral net. used only to name layers reg: L2 regularization (if any) dropout: dropout (if any) returns: appropriately formatted stack_layers dictionary """ layers = [] for i, a in enumerate(arch): layer = {"l2_reg": reg} layer.update(a) if network_type: layer["name"] = "{}_{}".format(network_type, i) layers.append(layer) if a["type"] != "Flatten" and dropout != 0: dropout_layer = { "type": "Dropout", "rate": dropout, } if network_type: dropout_layer["name"] = "{}_dropout_{}".format(network_type, i) layers.append(dropout_layer) return layers
def stub_all(cls): """Stub all methods of a class.""" class StubbedClass(cls): pass method_list = [ attribute for attribute in dir(StubbedClass) if callable(getattr(StubbedClass, attribute)) and (attribute.startswith("__") is False) ] for method in method_list: setattr(StubbedClass, method, lambda *args, **kwargs: None) return cls
def desi_target_from_survey(survey): """ Return the survey of DESI_TARGET as a function of survey used (cmx, sv1, sv2, sv3, main).""" if survey == 'special': # to avoid error, return one of the column, SV2_DESI_TARGET should be full of 0. return 'SV2_DESI_TARGET' if survey == 'cmx': return 'CMX_TARGET' elif survey == 'sv1': return 'SV1_DESI_TARGET' elif survey == 'sv2': return 'SV2_DESI_TARGET' elif survey == 'sv3': return 'SV3_DESI_TARGET' elif survey == 'main': return 'DESI_TARGET'
def stripcounty(s): """ Removes " County" from county name :param s: a string ending with " County" :return: """ if s.__class__ == str: if s.endswith(" County"): s = s[0:len(s)-7] return s
def as_list(obj): """Wrap non-lists in lists. If `obj` is a list, return it unchanged. Otherwise, return a single-element list containing it. """ if isinstance(obj, list): return obj else: return [obj]
def _is_bright(rgb): """Return whether a RGB color is bright or not. see https://stackoverflow.com/a/3943023/1595060 """ L = 0 for c, coeff in zip(rgb, (0.2126, 0.7152, 0.0722)): if c <= 0.03928: c = c / 12.92 else: c = ((c + 0.055) / 1.055) ** 2.4 L += c * coeff if (L + 0.05) / (0.0 + 0.05) > (1.0 + 0.05) / (L + 0.05): return True
def create_tag_body(tag, trigger_mapping): """Given a tag, remove all keys that are specific to that tag and return keys + values that can be used to clone another tag https://googleapis.github.io/google-api-python-client/docs/dyn/tagmanager_v2.accounts.containers.workspaces.tags.html#create :param tag: The tag to convert into a request body :type tag: dict :param trigger_mapping: A mapping of the triggers that exist on the target workspace to the destination workspace :type trigger_mapping: dict :return: A request body to be used in the create tag method :rtype: dict """ body = {} non_mutable_keys = [ "accountId", "containerId", "fingerprint", "parentFolderId", "path", "tagManagerUrl", "tagId", "workspaceId", ] for k, v in tag.items(): if k not in non_mutable_keys: if "TriggerId" not in k: body[k] = v else: mapped_triggers = [] for i in v: mapped_triggers = trigger_mapping[i] body[k] = mapped_triggers return body
def triarea(x, y, dir=0): """RETURNS THE AREA OF A TRIANGLE GIVEN THE COORDINATES OF ITS VERTICES A = 0.5 * | u X v | where u & v are vectors pointing from one vertex to the other two and X is the cross-product The dir flag lets you retain the sign (can tell if triangle is flipped)""" ux = x[1] - x[0] vx = x[2] - x[0] uy = y[1] - y[0] vy = y[2] - y[0] A = 0.5 * (ux * vy - uy * vx) if not dir: A = abs(A) return A
def approx_derivative(f, x, delta=1e-6): """ Return an approximation to the derivative of f at x. :param f: function that is differentiable near x :param x: input to f :param delta: step size in x :return: df/dx """ df = (f(x + delta) - f(x - delta))/2 #order 2 approximation return df/delta
def ben_graham(eps, next_eps, bond_yield=4.24): """ Gets, or tries to get, the intrinsic value of a stock based on it's ttm EPS and the corporate bond yield. """ # growth_rate = (next_eps - eps) / eps # growth_rate *= 100 growth_rate = next_eps # The top part of the fraction: EPS x (8.5 + 2g) x 4.4 numerator = eps * (8.5 + (2 * growth_rate)) * 4.4 iv = numerator / bond_yield return round(iv, 3)
def funny_string(S): """A string is funny if S[i]-S[i-1] == R[i]-R[i-1] for all i > 0 where R is the reverse of S """ S = S.lower() R = "".join(reversed(S)) for i, s in enumerate(S[1:], 1): d1 = abs(ord(S[i - 1]) - ord(s)) d2 = abs(ord(R[i - 1]) - ord(R[i])) if d2 != d1: return False return True
def _broadcast_shapes(s1, s2): """Given array shapes `s1` and `s2`, compute the shape of the array that would result from broadcasting them together.""" n1 = len(s1) n2 = len(s2) n = max(n1, n2) res = [1] * n for i in range(n): if i >= n1: c1 = 1 else: c1 = s1[n1-1-i] if i >= n2: c2 = 1 else: c2 = s2[n2-1-i] if c1 == 1: rc = c2 elif c2 == 1 or c1 == c2: rc = c1 else: raise ValueError('array shapes %r and %r are not compatible' % (s1, s2)) res[n-1-i] = rc return tuple(res)
def longestSubsequence(list1, list2): """ NxM array len list1 by len list2 matches[i][j] shows num matches between first i+1 elements of list1 and first j+1 elements of list2 Initialize by locating where the first matches between first elements occur """ matches = [] for i in range(0, len(list1)): matches.append([]) for j in range(0, len(list2)): matches[i].append(0) if list1[i] == list2[0]: matches[i][0] += 1 for j in range(0, len(list2)): if list1[0] == list2[j]: matches[0][j] += 1 """ solve in a series of check-mark shapes 1 1 1 1 1 2 2 2 1 2 3 3 1 2 3 4 1 2 3 4 in this order could just use a standard for i in range(1, len(list1)): for j in range(1, len(list2)): ... since that order still means each solution has access to its subsolutions """ for offset in range(1, min(len(list1), len(list2))): for i in range(offset, len(list1)): # Theta(N) # professor records which subproblem was used in another array matches[i][offset] = max( matches[i - 1][offset - 1], matches[i - 1][offset], matches[i][offset - 1] ) if list1[i] == list2[offset]: matches[i][offset] += 1 # matches[offset][offset] has already been computed for j in range(offset + 1, len(list2)): # Theta(M) matches[offset][j] = max( matches[offset - 1][j - 1], matches[offset - 1][j], matches[offset][j - 1] ) if list1[offset] == list2[j]: matches[offset][j] += 1 for line in matches: print(line) return matches[len(list1) - 1][len(list2) - 1]
def close(x, y, rtol, atol): """Returns True if x and y are sufficiently close. Parameters ---------- rtol The relative tolerance. atol The absolute tolerance. """ # assumes finite weights return abs(x-y) <= atol + rtol * abs(y)
def doc_modifier(doc): """ """ return doc.replace( 'delay_shift (bool, optional): flag to simulate spike propagation ' 'delay from one layer to next. Defaults to True.', 'delay_shift (bool, optional): flag to simulate spike propagation ' 'delay from one layer to next. Defaults to False.' )
def hex_to_bin(txt: str) -> str: """Convert hexadecimal string to binary string.Useful for preprocessing the key and plaintext in different settings.""" return bin(int(txt,16))[2:]
def batch_size(batch): """ Calculates the size of a batch. Args: batch: A list of dictionaries representing mutations. Returns: An integer specifying the size in bytes of the batch. """ size = 0 for mutation in batch: size += len(mutation['key']) if 'values' in mutation: for value in mutation['values'].values(): size += len(value) return size
def is_plain_lambda(mod): """check for the presence of the LambdReduce block used by the torch -> pytorch converter """ return 'Lambda ' in mod.__repr__().split('\n')[0]
def plane_inersection(equation, plane): """ finds the point where a line intersects with a plane :param equation: tuple of two tuples, a point tuple and a direction tuple => (x, y, z) + t*(x_diff, y_diff, z_diff) :param plane: a tuple representing a plane equation (l, m, n, A) => xl + my + nz = A :return: a tuple (x, y, z) represents a point of intersection """ t_num = (plane[3] - ((plane[0] * equation[0][0]) + (plane[1] * equation[0][1]) + (plane[2] * equation[0][2]))) t_den = ((plane[0] * equation[1][0]) + (plane[1] * equation[1][1]) + (plane[2] * equation[1][2])) t = t_num / t_den return (equation[0][0] + (equation[1][0] * t)), (equation[0][1] + (equation[1][1] * t)), \ (equation[0][2] + (equation[1][2] * t))
def casefolding(token): """ This function will turn all the letters into lowercase. """ token_per_sesi = [] for sesi in token: token_per_chat = [] for chat in sesi: token = [] for word in chat: token.append(word.lower()) token_per_chat.append(token) token_per_sesi.append(token_per_chat) return token_per_sesi
def repeatedString(s, n): """Either 1,000,000,000,000 The length of S could be less than N. The length of S could be greater than N The length of S could be equal to N """ # The number of times the letter 'a' occurs in the string S. num_a = s.count('a') # If the length of S is less than N, there must be some number of times # that S wholy divides into N, and there may or may not be a remainder when # doing so. if len(s) < n: whole = n // len(s) remainder = n % len(s) # If the remainder is 0, then we just need to count the number of times # 'a' occurrs in S, and then multiply this by how many times S wholy # divides into N. if remainder == 0: answer = num_a * whole return answer else: return num_a * whole + s[:remainder].count('a') elif len(s) > n: return s[:n].count('a') return
def leading_spaces(s: str) -> int: """Return the number of spaces at the start of str""" return len(s) - len(s.lstrip(" "))
def _height(bbox): """Return the height of a bounding box. Parameters ---------- bbox : tuple 4-tuple specifying ``(min_row, min_col, max_row, max_col)``. Returns ------- int The height of the bounding box in pixels. """ return bbox[2] - bbox[0] + 1
def yel(string): """ Color %string yellow. """ return "\033[33m%s\033[0m" % string
def max_key(dict): """ Returns the maximum key in an integer-keyed dictionary. Args: dict (dict): The integer-keyed dictionary. Returns: int: The maximum key. """ output = 0 for key, value in dict.items(): output = max(output, int(key)) return output
def onroot_vd(t, y, solver): """ onroot function to just continue if time <28 """ if t > 28: return 1 return 0
def recall_interval(recall): """Return the interval of recall classified to 11 equal intervals of 10 (the field range is 0-100)""" return ((recall*10)//1)*10
def range_list(start: int, end: int): """Problem 22: Create a list containing all integers within a given range. Parameters ---------- start : int end : int Returns ------- list A list including all numbers from `start` to `end` Raises ------ ValueError If the given `start` is smaller than `end` """ if end < start: raise ValueError('The `end` argument is smaller than `start`.') return list(range(start, end + 1))