content
stringlengths
42
6.51k
def _conv_number(number, typen=float): """Convert a number. Parameters ---------- number Number represented a float. typen : The default is ``float``. Returns ------- """ if typen is float: try: return float(number) except: return number elif typen is int: try: return int(number) except: return number
def _truncate_with_offset(resource, value_list, offset): """Truncate a list of dictionaries with a given offset. """ if not offset: return resource offset = offset.lower() for i, j in enumerate(value_list): # if offset matches one of the values in value_list, # the truncated list should start with the one after current offset if j == offset: return resource[i + 1:] # if offset does not exist in value_list, find the nearest # location and truncate from that location. if j > offset: return resource[i:] return []
def get_device_type_id(name): """ Returns the ATCADeviceType value based on the device name """ devices = {'ATSHA204A': 0, 'ATECC108A': 1, 'ATECC508A': 2, 'ATECC608A': 3, 'UNKNOWN': 0x20} return devices.get(name.upper())
def merge(l1, l2): """ l1, l2: Lists of integers (might be empty). Arrays are assumed to be sorted. Returns the lists merged. """ n = len(l1) + len(l2) merged = [] i, j, s = 0, 0, 0 while i < len(l1) and j < len(l2): if l1[i] < l2[j]: merged.append(l1[i]) i += 1 else: merged.append(l2[j]) j += 1 s += (n//2)-i complement = [e for e in l1[i:]] if i < len(l1) else [e for e in l2[j:]] assert len(complement) + len(merged) is n return (s, merged + complement)
def word(item, lex): """This function returns true if item is word in lexicon that has not been analyzed, i.e. it has no attached syntactic category""" # If item is a key in lex, return True if isinstance(item, list): return False if item in lex: return True return False
def fill(array, value, start=0, end=None): """Fills elements of array with value from `start` up to, but not including, `end`. Args: array (list): List to fill. value (mixed): Value to fill with. start (int, optional): Index to start filling. Defaults to ``0``. end (int, optional): Index to end filling. Defaults to ``len(array)``. Returns: list: Filled `array`. Example: >>> fill([1, 2, 3, 4, 5], 0) [0, 0, 0, 0, 0] >>> fill([1, 2, 3, 4, 5], 0, 1, 3) [1, 0, 0, 4, 5] >>> fill([1, 2, 3, 4, 5], 0, 0, 100) [0, 0, 0, 0, 0] Warning: `array` is modified in place. .. versionadded:: 3.1.0 """ if end is None: end = len(array) else: end = min([end, len(array)]) # Use this style of assignment so that `array` is mutated. array[:] = array[:start] + [value] * len(array[start:end]) + array[end:] return array
def make_s3_raw_record(bucket, key): """Helper for creating the s3 raw record""" # size = len(s3_data) raw_record = { 's3': { 'configurationId': 'testConfigRule', 'object': { 'eTag': '0123456789abcdef0123456789abcdef', 'sequencer': '0A1B2C3D4E5F678901', 'key': key, 'size': 100 }, 'bucket': { 'arn': 'arn:aws:s3:::mybucket', 'name': bucket, 'ownerIdentity': { 'principalId': 'EXAMPLE' } } }, 'awsRegion': 'us-east-1' } return raw_record
def lot_status(parkingLot): """ return the status of Parking Lot ARGS: parkingLot(ParkingLot Object) """ returnString = '' if parkingLot: print('Slot No.\tRegistration No\tColour') parkingSlot = parkingLot.get_slots() for parkedCar in parkingSlot.values(): if parkedCar is not None: returnString += str(parkedCar.get_slot()) + '\t' + \ parkedCar.get_registration_number() + '\t' + \ parkedCar.get_colour() + '\n' else: returnString = 'Parking lot is not defined' return returnString
def get_similarity_score(dict1, dict2, dissimilarity = False): """ The keys of dict1 and dict2 are all lowercase, you will NOT need to worry about case sensitivity. Args: dict1: frequency dictionary of words or n-grams for one text dict2: frequency dictionary of words or n-grams for another text dissimilarity: Boolean, optional parameter. Default to False. If this is True, return the dissimilarity score, 100*(DIFF/ALL), instead. Returns: int, a percentage between 0 and 100, inclusive representing how similar the texts are to each other The difference in text frequencies = DIFF sums words from these three scenarios: * If a word or n-gram occurs in dict1 and dict2 then get the difference in frequencies * If a word or n-gram occurs only in dict1 then take the frequency from dict1 * If a word or n-gram occurs only in dict2 then take the frequency from dict2 The total frequencies = ALL is calculated by summing all frequencies in both dict1 and dict2. Return 100*(1-(DIFF/ALL)) rounded to the nearest whole number if dissimilarity is False, otherwise returns 100*(DIFF/ALL) """ DIFF = 0 for i in dict1: x = False #Boolean used to not add repeated frequencies as it will be seen later for j in dict2: if i == j: #use of == instead of i in j as for example word "meme" could #be in "memes" and would therefore cause a problem DIFF += abs(dict1[i] - dict2[j]) #if the word/n-gram appears in both dictionnaires then #the absolute value of the difference between the frequencies #in each dictionnary is added to DIFF x = True if x == False: #Boolean used so that frequencies of a word/n-gram are not added again #and again to DIFF DIFF += dict1[i] for j in dict2: x = False #same use of boolean for same reasons as previou for loop for i in dict1: if i == j: #use of == due to the same reason x = True #this time the absolute value of the difference between the #frequencies doesn't have to be added as it already has been if x == False: DIFF += dict2[j] ALL = 0 for i in dict1: ALL += dict1[i] #all the frequencies of the first dictionnary are added to ALL for j in dict2: ALL += dict2[j] #same occurs as in the previous loop but for the second dictionnary #Depending on the input of dissimilarity this will occur if dissimilarity == False: result = round(100*(1 - (DIFF/ALL))) #similarity between the dictionnaries of word/n-grams is the result else: result = round(100*(DIFF/ALL)) #dissimilarity between the dictionnaries of word/n-grams is the result return result
def normalize_recommend(rec_list, max_len): """ If len(rec_list) < max_len, rec_list will be dropped. Otherwise, rec_list will be truncated. """ if len(rec_list) < max_len: return [] else: return rec_list[-max_len:]
def probability_multiply(probability, token_frequency, n): """Assigns score to document based on multiplication of probabilities. Probability is token frequency devided by length of document. In this metric only documents containing all query words have positive probability. Args: probability (float): Previously calculated probability. token_frequency (float): Number of appearances of token in text. n (int): Length of text. Returns: probability_value (float): New caclculated probability. """ probability_value = probability*(token_frequency/n) return probability_value
def InsetLineColourRev(argument): """Reverse dictionary for switching colour argurments""" switcher = { 'k' : 'Black', 'dimgrey' : 'Dark Grey', 'darkgrey' : 'Grey', 'lightgrey' : 'Light Grey', 'white' : 'White' } return switcher.get(argument, 'k')
def energy_au(neff): #energy in atomic units """ returns the energy of the state in atomic units. """ return -(0.5 * (1.0 / ((neff)**2) ))
def assign_ids(lang, data): """Add ID values for groups and characters""" group_id = 1 char_id = 1 for purity_group in data.values(): for group in purity_group["groups"].values(): group["ID"] = f"g-{lang}-{group_id}" group_id += 1 for cluster in group["clusters"]: for char_data in cluster.values(): char_data["ID"] = f"c-{lang}-{char_id}" char_id += 1 return data
def required(label, field, data, **kwargs): """Validates presence value. - when bool, return True - when None, return False, - when inexistent key, return False """ if not field in data: return False value = data[field] if value == None: return False elif type(value) is bool: return True elif not value: return False return True
def wrap(text, width=80): """ Wraps a string at a fixed width. Arguments --------- text : str Text to be wrapped width : int Line width Returns ------- str Wrapped string """ return "\n".join( [text[i:i + width] for i in range(0, len(text), width)] )
def get_min_hit_end_distance(l1, l2): """ Given two lists of kmer hit ends on a sequence (from get_kmer_hit_ends()), return the minimum distance between two hit ends in the two lists. In other words, the closest positions in both lists. >>> l1 = [2,10,20] >>> l2 = [12,15,30] >>> get_min_hit_end_distance(l1,l2) 2 """ assert l1, "l1 empty" assert l2, "l2 empty" min_dist = 1000000 for e1 in l1: for e2 in l2: dist_e1e2 = abs(e1-e2) if dist_e1e2 < min_dist: min_dist = dist_e1e2 assert min_dist != 1000000, "no min_dist extracted" return min_dist
def str2bin(msg): """Convert a binary string into a 16 bit binary message.""" assert isinstance(msg, bytes), 'must give a byte obj' return ''.join([bin(c)[2:].zfill(16) for c in msg]).encode()
def name_is_private(name: str) -> bool: """Determines whether a given name is private.""" return name.startswith("~")
def deltatime_format(a, b): """ Compute and format the time elapsed between two points in time. Args: a Earlier point-in-time b Later point-in-time Returns: Elapsed time integer (in s), Formatted elapsed time string (human-readable way) """ # Elapsed time (in seconds) t = b - a # Elapsed time (formatted) d = t s = d % 60 d //= 60 m = d % 60 d //= 60 h = d % 24 d //= 24 # Return elapsed time return t, f"{d} day(s), {h} hour(s), {m} min(s), {s} sec(s)"
def is_numlike(obj): """ Return True if `obj` looks like a number """ try: obj + 1 except: return False return True
def isqrt(n: int) -> int: """Returns the square root of an integer.""" x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x
def NnotNone(*it): """ Returns the number of elements of it tha are not None. Parameters ---------- it : iterable iterable of elements that are either None, or not None Returns ------- int """ return sum([i is not None for i in it])
def parse_number(input_string, parsing_hex=False): """ # hex: ABCDEF # atoi (int, float), integer/float @param input_string: input string @param parsing_hex: ABCDEF @return: """ input_string = str(input_string).strip().strip('+').rstrip('.') result, multiplier, division = 0, 10, 1 sign = -1 if input_string and input_string[0] == '-' else 1 if sign == -1: input_string = input_string.strip('-') for item in input_string: # print('ch:', item) if item == '.': if division > 1: return None multiplier, division = 1, 10 elif item < '0' or item > '9': return None elif item >= '0' and item <= '9': v = ord(item) - ord('0') div = v / division if division > 1 else v result = result * multiplier + div # print(s, v, result) if division != 1: division *= 10 return None if input_string == '' else result * sign
def parse_date(string_value): """ Used to parse date on which match is played. """ dd, mm, yyyy = string_value.split("-") return int(yyyy), int(mm), int(dd)
def findimagenumber (filename): """find the number for each image file""" #split the file so that name is a string equal to OBSDATE+number name=filename.split('/')[-1].split('.')[0] return int(name[9:])
def transform_metadata(record): """Format the metadata record we got from the database to adhere to the response schema.""" response = dict(record) response["id"] = response.pop("datasetId") response["name"] = None response["description"] = response.pop("description") response["assemblyId"] = response.pop("assemblyId") response["createDateTime"] = None response["updateDateTime"] = None response["dataUseConditions"] = None response["version"] = None response["variantCount"] = 0 if response.get("variantCount") is None else response.get("variantCount") response["callCount"] = 0 if response.get("callCount") is None else response.get("callCount") response["sampleCount"] = 0 if response.get("sampleCount") is None else response.get("sampleCount") response["externalURL"] = None response["info"] = {"accessType": response.get("accessType"), "authorized": 'true' if response.pop("accessType") == "PUBLIC" else 'false'} return response
def hexToStr(hexStr): """ Convert a string hex byte values into a byte string """ bytes = [] hexStr = ''.join(hexStr.split(" ")) for i in range(0, len(hexStr)-2, 2): bytes.append(chr(int(hexStr[i:i+2], 16))) return ''.join( bytes )
def as_int_or_float(val): """Infers Python int vs. float from string representation.""" if type(val) == str: ret_val = float(val) if '.' in val else int(val) return ret_val return val
def convert_to_fortran_string(string): """ converts some parameter strings to the format for the inpgen :param string: some string :returns: string in right format (extra "" if not already present) """ if not string.strip().startswith("\"") or \ not string.strip().endswith("\""): return f'"{string}"' else: return string
def check_step_motion_from_dissonance( movement: int, is_last_element_consonant: bool, **kwargs ) -> bool: """ Check that there is step motion from a dissonating element. Note that this rule prohibits double neighboring tones. :param movement: melodic interval (in scale degrees) for line continuation :param is_last_element_consonant: indicator whether last element of counterpoint line (not including a new continuation in question) forms consonance with cantus firmus :return: indicator whether a continuation is in accordance with the rule """ if is_last_element_consonant: return True return movement in [-1, 1]
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: List of dictionaries. Structured data with the following schema: [ { "uid": string, "pid": integer, "ppid": integer, "c": integer, "stime": string, "tty": string, # ? or ?? = Null "tt": string, # ?? = Null "time": string, "cmd": string, "user": string, "cpu_percent": float, "mem_percent": float, "vsz": integer, "rss": integer, "stat": string, "start": string, "command": string } ] """ for entry in proc_data: # change key name '%cpu' to 'cpu_percent' if '%cpu' in entry: entry['cpu_percent'] = entry.pop('%cpu') # change key name '%mem' to 'mem_percent' if '%mem' in entry: entry['mem_percent'] = entry.pop('%mem') # change to int int_list = ['pid', 'ppid', 'c', 'vsz', 'rss'] for key in int_list: if key in entry: try: key_int = int(entry[key]) entry[key] = key_int except (ValueError): entry[key] = None # change to float float_list = ['cpu_percent', 'mem_percent'] for key in float_list: if key in entry: try: key_float = float(entry[key]) entry[key] = key_float except (ValueError): entry[key] = None if 'tty' in entry: if entry['tty'] == '?' or entry['tty'] == '??': entry['tty'] = None if 'tt' in entry: if entry['tt'] == '??': entry['tt'] = None return proc_data
def memoized_longest_palindromic_subsequence(input_string): """ Parameters ---------- input_string : str String with palindromic subsequence Returns ------- int length of the longest palindromic subsequence >>> memoized_longest_palindromic_subsequence("abdbca") 5 >>> memoized_longest_palindromic_subsequence("cddpd") 3 >>> memoized_longest_palindromic_subsequence("pqr") 1 """ cache = {} def helper(start, end): if (start, end) in cache: return cache[(start, end)] if start == end: return 1 if start > end: return 0 if input_string[start] == input_string[end]: cache[(start, end)] = 2 + helper(start + 1, end - 1) return cache[(start, end)] cache[(start, end)] = max(helper(start + 1, end), helper(start, end - 1)) return cache[(start, end)] return helper(0, len(input_string) - 1)
def mate(generations: int, litter: int) -> int: """ Calculate population at end""" fib = [0, 1] for _ in range(generations - 1): fib.append((fib[-2] * litter) + fib[-1]) pop = fib[-1] return pop
def print_delays_header(v=1): """ Print header for summary of delay information. Parameters ---------- v : int verbose mode if 1. Returns ------- str_out : str line with header. """ str_out=("D "+"st".rjust(3)+ "t0 [s]".rjust(14)+"total delay [us]".rjust(20)+\ "clock [us]".rjust(20)+\ "clock rate [us/s]".rjust(20)+\ "total rate [us/s]".rjust(20)+\ "total accel [us/s/s]".rjust(25)) if v==1: print(str_out) return(str_out)
def _horner(x, coeffs): """Horner's method to evaluate polynomials.""" res = coeffs[0] for c in coeffs[1:]: res = c + x * res return res
def boxes_required(qty, box_capacity=6): """ Calculate how many egg boxes will be required for a given quatity of eggs. :param qty: Number of eggs :param box_capacity: How many eggs will fit in a box :return: The number of boxes that are required """ return int(qty / box_capacity) + 1
def scale_model_weights(weight, scalar): """Function for scaling a models weights for federated averaging""" weight_final = [] steps = len(weight) for i in range(steps): weight_final.append(scalar * weight[i]) return weight_final
def local_time_constant(longitude: float) -> float: """Local time constant K in minutes - DK: Lokal tids konstant""" time_median_longitude = int(longitude/15)*15 longitude_deg = longitude / abs(longitude) * (abs(int(longitude)) + abs(longitude) % 1 * 100 / 60) local_time_constant = 4 * (time_median_longitude - longitude_deg) return local_time_constant
def get_language(path: str): """ Get website language in url path. Args: path (str): path """ # The path are in the following format: # <optional base_url>/<year>/<lang>/.... # ex: /2021/zh-hant/about/history, /2015apac/en/about/index.html, /2019/en-us/ # Use for loop to find language for part in path.split("/"): if "en" in part: return "en" if "zh" in part: return "zh" return "en"
def extract_update(input): """extract the update data, from which we compute new metrics""" update = input['update'] update['_id'] = input['_id'] return update
def parse_siteclass_proportions(line_floats): """For models which have multiple site classes, find the proportion of the alignment assigned to each class. """ site_classes = {} if len(line_floats) > 0: for n in range(len(line_floats)): site_classes[n] = {"proportion" : line_floats[n]} return site_classes
def stabilize_steering_angle(curr_steering_angle, new_steering_angle, num_of_lane_lines, max_angle_deviation_two_lines=5, max_angle_deviation_one_lane=1): """ Using last steering angle to stabilize the steering angle This can be improved to use last N angles, etc if new angle is too different from current angle, only turn by max_angle_deviation degrees """ if num_of_lane_lines == 2 : # if both lane lines detected, then we can deviate more max_angle_deviation = max_angle_deviation_two_lines else : # if only one lane detected, don't deviate too much max_angle_deviation = max_angle_deviation_one_lane angle_deviation = new_steering_angle - curr_steering_angle if abs(angle_deviation) > max_angle_deviation: stabilized_steering_angle = int(curr_steering_angle + max_angle_deviation * angle_deviation / abs(angle_deviation)) else: stabilized_steering_angle = new_steering_angle return stabilized_steering_angle
def dict_to_string(d, num_dict_round_floats=6, style='dictionary'): """given a dictionary, returns a string Arguments: d {dictionary} -- num_dict_round_floats {int} -- num of digits to which the float numbers on the dict should be round style {string} """ separator = '' descriptor = '' if style == 'dictionary': separator = ';' descriptor = ': ' elif style == 'constructor': separator = ',\n' descriptor = '=' s = '' for key, value in d.items(): if isinstance(value, float): s += '{}{}{}{} '.format(key, descriptor, round(value, num_dict_round_floats), separator) else: s += '{}{}{}{} '.format(key, descriptor, value, separator) return s
def compute_precision_recall(correct_chunk_cnt, found_pred_cnt, found_correct_cnt): """Computes and returns the precision and recall. Args: correct_chunk_cnt: The count of correctly predicted chunks. found_pred_cnt: The count of predicted chunks. found_correct_cnt : The actual count of chunks. Returns: The slot precision and recall """ if found_pred_cnt > 0: precision = 100 * correct_chunk_cnt / found_pred_cnt else: precision = 0 if found_correct_cnt > 0: recall = 100 * correct_chunk_cnt / found_correct_cnt else: recall = 0 return precision, recall
def _selStrFromList(item_str, lst_str): """ Selects a string from a list if it is a substring of the item. Parameters ---------- item_str: str string for which the selection is done list_str: list-str list from which selection is done Returns ------- str """ strs = [s for s in lst_str if item_str == s] if len(strs) != 1: strs = [s for s in lst_str if s in item_str] if len(strs) != 1: raise ValueError("Cannot find %s uniquely in %s" % (item_str, str(lst_str))) return strs[0]
def strip_scheme_www_and_query(url): """Remove the scheme and query section of a URL.""" if url: return url.split("//")[-1].split("?")[0].lstrip("www.") else: return ""
def GetSupportPoint(left, right): """ Returns supported point. Args: left: Left point right: Right point Returns: Point """ return (right[0], left[1])
def __material_mu(d): """ Fixed length data fields for music. """ return (d[0:2], d[2], d[3], d[4], d[5], d[6:12], d[12:14], d[14], d[15], d[16])
def cycle(permutation, start): """ Compute a cycle of a permutation. :param permutation: Permutation in one-line notation (length n tuple of the numbers 0, 1, ..., n-1). :param start: Permutation element to start with. :return: Tuple of elements we pass until we cycle back to the start element. .. rubric:: Examples >>> cycle((2, 3, 0, 1), 0) (0, 2) >>> cycle((2, 3, 0, 1), 1) (1, 3) """ cycle_list = [start] next_elem = permutation[start] while next_elem != start: cycle_list.append(next_elem) next_elem = permutation[next_elem] return tuple(cycle_list)
def eiffel_confidence_level_modified_event(name="Eiffel Graphql API Tests"): """Eiffel confidence level modified event.""" return { "meta": { "version": "3.0.0", "source": {"name": "eiffel-graphql-api-tests"}, "type": "EiffelConfidenceLevelModifiedEvent", "id": "c44242ba-5329-4610-9334-2ac70f5134b2", "time": 1574922251254, }, "links": [ {"type": "SUBJECT", "target": "2c48516a-24f5-4f9e-b9c7-6fe3457acb95"} ], "data": {"name": name, "value": "SUCCESS"}, }
def env_str_to_int(varname, val): """Convert environment variable decimal value `val` from `varname` to an int and return it.""" try: return int(val) except Exception: raise ValueError("Invalid value for " + repr(varname) + " should have a decimal integer value but is " + repr(str(val)))
def range_out_of_set(list): """Filters the single interfaces Filters the single interface sets, leaves out the ones with multiple elements and returns them as a list. Args: list (list): list of sets Returns: list: list of strings which is interface name """ same_config_ints = [] for element in list: if len(element) > 1: same_config_ints.append(sorted(element)) return same_config_ints
def remove_namespace(inp): """Remove namespace from input string. A namespace in this context is the first substring before the '/' character Parameters ---------- inp : Input string Returns ------- string with namespace removed. """ ind = inp.find('/') if ind != -1: return inp[ind+1:] return inp
def supports_float(value: object) -> bool: # noqa: E302 """Check if a float-like object has been passed (:class:`~typing.SupportsFloat`). Examples -------- .. code:: python >>> from nanoutils import supports_float >>> supports_float(1.0) True >>> supports_float(1) True >>> supports_float('1.0') True >>> supports_float('not a float') False Parameters ---------- value : :class:`object` The to-be evaluated object. Returns ------- :class:`bool` Whether or not the passed **value** is float-like or not. """ try: float(value) # type: ignore return True except Exception: return False
def counting_stats(response_stat_collection: dict) -> int: """ Count a correct total of features in all collections :param response_stat_collection: the collection field'd in response's statistics :returns: count of all features """ count = 0 for stat_collection in response_stat_collection.values(): count += stat_collection return count
def read_labeled_image_forward_list(data_dir, data_list): """Reads txt file containing paths to images and ground truths. Args: data_dir: path to the directory with images and masks. data_list: path to the file with lines of the form '/path/to/image /path/to/image-labels'. Returns: Two lists with all file names for images and image-labels, respectively. """ f = open(data_list, 'r') images = [] catgs = [] for line in f: image, catg = line.strip("\n").split(' ') images.append(data_dir + image) catgs.append(data_dir + catg) return images, catgs
def get_right_child_index(parent_index, heap): """ Get the index of the right child given the parent node's index. """ # Remember, this is a 1-based index. if parent_index * 2 + 1 >= len(heap): # There is no right child return 0 return parent_index * 2 + 1
def grid_edge_is_closed_from_dict(boundary_conditions): """Get a list of closed-boundary status at grid edges. Get a list that indicates grid edges that are closed boundaries. The returned list provides a boolean that gives the boundary condition status for edges order as [*bottom*, *left*, *top*, *right*]. *boundary_conditions* is a dict whose keys indicate edge location (as "bottom", "left", "top", "right") and values must be one of "open", or "closed". If an edge location key is missing, that edge is assumed to be *open*. Parameters ---------- boundary_conditions : dict Boundary condition for grid edges. Returns ------- list List of booleans indicating if an edge is a closed boundary. Examples -------- >>> from landlab.grid.raster import grid_edge_is_closed_from_dict >>> grid_edge_is_closed_from_dict(dict(bottom='closed', top='open')) [False, False, False, True] >>> grid_edge_is_closed_from_dict({}) [False, False, False, False] """ for condition in boundary_conditions.values(): if condition not in ['open', 'closed']: raise ValueError('%s: boundary condition type not understood', condition) return [boundary_conditions.get(loc, 'open') == 'closed' for loc in ['right', 'top', 'left', 'bottom']]
def _restrict_reject_flat(reject, flat, raw): """Restrict a reject and flat dict based on channel presence""" reject = {} if reject is None else reject flat = {} if flat is None else flat assert isinstance(reject, dict) assert isinstance(flat, dict) use_reject, use_flat = dict(), dict() for in_, out in zip([reject, flat], [use_reject, use_flat]): use_keys = [key for key in in_.keys() if key in raw] for key in use_keys: out[key] = in_[key] return use_reject, use_flat
def calculate_bucket_count_in_heap_at_level(k, l): """ Calculate the number of buckets in a k-ary heap at level l. """ assert l >= 0 return k**l
def get_boundary_indicators_for_sorted_array(sorted_array): """ Parameters ---------- sorted_array: list[int] Returns ------- list[bool] list[bool] """ start_indicators = [True] for i in range(1, len(sorted_array)): if sorted_array[i] != sorted_array[i - 1]: start_indicators.append(True) else: start_indicators.append(False) end_indicators = [True] for i in range(len(sorted_array) - 2, -1, -1): if sorted_array[i] != sorted_array[i + 1]: end_indicators.append(True) else: end_indicators.append(False) end_indicators = end_indicators[::-1] return start_indicators, end_indicators
def cube_to_axial(c): """ Converts a cube coord to an axial coord. :param c: A cube coord x, z, y. :return: An axial coord q, r. """ x, z, _ = c return x, z
def extract_sticker_id(body): """ Obtains the sticker ID from the event body Parameters ---------- body: dic Body of webhook event Returns ------- str file_id of sticker """ file_id = body["message"]["sticker"]["file_id"] return file_id
def mock_lookup_queue_length(url, request): """ Mocks an API call to check the queue length """ return {'status_code': 200, 'content-type': 'application/json', 'server': 'Apache', 'content': { "supportId": "123456789", "httpStatus": 200, "detail": "The queue may take a minute to reflect new or " "removed requests.", "queueLength": 100} }
def is_1_2(s, t): """ Determine whether s and t are identical except for a single character of which one of them is '1' and the other is '2'. """ differences = 0 one_two = {"1", "2"} for c1, c2 in zip(s, t): if c1 != c2: differences += 1 if differences == 2: return False if {c1, c2} != one_two: return False return differences == 1
def linear_combinaison(alpha = 1.0, m1 = {}, beta = None, m2 = {}): """ Return the linear combinaison m = alpha * m1 + beta * m2. """ if m2 == {}: m2 = m1 beta = 0.0 m = {} for (name, value) in m1.items(): m[name] = alpha * value + beta * m2.get(name, 0.0) return m
def if_else(n: int) -> str: """ >>> if_else(3) 'Weird' >>> if_else(24) 'Not Weird' """ if n % 2 or 6 <= n <= 20: return 'Weird' return 'Not Weird'
def ids2str(ids): """Given a list of integers, return a string '(int1,int2,...)'.""" return "(%s)" % ",".join(str(i) for i in ids)
def int2bin(n, count=24): """returns the binary of integer n, using count number of digits""" return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
def _filter_direct_matching(key: dict, all_data: list, *, inverse: bool=False) -> tuple: """Filter through all data to return only the documents which match the key. `inverse` keyword-only argument is for those cases when we want to retrieve all documents which do NOT match the `check`.""" if not inverse: def check(element: dict) -> bool: return all([True if i in element.items() else False for i in key.items()]) else: def check(element: dict) -> bool: return all([False if i in element.items() else True for i in key.items()]) results = filter(check, all_data) return tuple(results)
def new_metric(repo_name: str, metric_name: str, metric_value: float) -> dict: """Creates a new metric in the format required for CloudWatch :param repo_name: the repository name to associate with the metric :type repo_name: str :param metric_name: the name of the metric :type metric_name: str :param metric_value: the value of the metric :type metric_value: int :returns: the dictionary representing the metric :rtype: dict """ if not metric_name or not repo_name: print("Not creating new metric: missing metric/repo name") return {} if not isinstance(metric_value, (int, float)): if not isinstance(metric_value, str) or not metric_value.isnumeric(): print("Not creating new metric: metric value is an invalid type") return {} metric_value = float(metric_value) return { 'MetricName': metric_name, 'Dimensions': [ { 'Name': 'REPO_NAME', 'Value': repo_name } ], 'Unit': 'None', 'Value': metric_value }
def mmHg_to_unit(p): """ Converts pressure value in mmHg to g cm-1 s-2. Arguments --------- p : float Pressure value in mmHg Returns ------- return : float Pressure value in g cm-1 s-2 """ return 101325/76*p
def validate_format(input_format, valid_formats): """Check the input format is in list of valid formats :raise ValueError if not supported """ if not input_format in valid_formats: raise ValueError('{} data format is not in valid formats ({})'.format(input_format, valid_formats)) return input_format
def swap_row(content, row_index, row_info=[]): """ Swap row position into the table Arguments: - the table content, a list of list of strings: - First dimension: the columns - Second dimensions: the column's content - cursor index for col - cursor index for row Returns: - the table content, a list of list of strings: - First dimension: the columns - Second dimensions: the column's content """ for i in range(len(content)): row_saved = content[i][row_index] del content[i][row_index] if row_index == len(content[i]): content[i].insert(row_index-1, row_saved) else: content[i].insert(row_index+1, row_saved) return content
def field_items_text(content): """ Creates a comma separated string of values for a particular field """ if len(content): tag = content[0].find_all(class_="field-items")[0] if len(tag.contents): return ', '.join([c.text for c in tag.contents]) else: return tag.text return None
def compact_date(date): """ Converts an ISO 8601 format date string into a compact date. Parameters ---------- Date: a string date in iso format. Returns ---------- A string date without hyphens. """ return date.replace('-', '')
def get_number_of_anchor_boxes_per_anchor_point(scale:list,aspect_ratio:list): """Gets the number of bounding boxes per anchor point from the scale and aspect_ratio list""" return len([ar+s for ar in aspect_ratio for s in scale])
def bspline_numba(p, j, x): """Return the value at x in [0,1[ of the B-spline with integer nodes of degree p with support starting at j. Implemented recursively using the de Boor's recursion formula""" assert ((x >= 0.0) & (x <= 1.0)) if p == 0: if j == 0: return 1.0 else: return 0.0 else: w = (x-j)/p w1 = (x-j-1)/p return w * bspline_numba(p-1,j,x)+(1-w1)*bspline_numba(p-1,j+1,x)
def parse_bool(value, additional_true=None, additional_false=None): """Parses a value to a boolean value. If `value` is a string try to interpret it as a bool: * ['1', 't', 'y', 'true', 'yes', 'on'] ==> True * ['0', 'f', 'n', 'false', 'no', 'off'] ==> False Otherwise raise TypeError. Args: value: value to parse to a boolean. additional_true (list): optional additional string values that stand for True. additional_false (list): optional additional string values that stand for False. Returns: bool: True if `value` is true, False if `value` is false. Raises: ValueError: `value` does not parse. """ true_values = ['1', 't', 'y', 'true', 'yes', 'on'] false_values = ['0', 'f', 'n', 'false', 'no', 'off', 'none'] if additional_true: true_values.extend(additional_true) if additional_false: false_values.extend(additional_false) if isinstance(value, str): value = value.lower() if value in true_values: return True if value in false_values: return False raise TypeError return bool(value)
def _get_defined_keywords(section_string): """ gets a list of all the keywords defined in a section """ defined_keys = [] for line in section_string.splitlines(): tmp = line.strip().split(' ')[0] defined_keys.append(tmp.strip()) return defined_keys
def verify(text): """Verify that the url is valid in a very simple manners.""" if 'anonfiles.com' in text: return True return False
def set_level(request, level): """ Sets the minimum level of messages to be recorded, returning ``True`` if the level was recorded successfully. If set to ``None``, the default level will be used (see the ``get_level`` method). """ if not hasattr(request, '_messages'): return False request._messages.level = level return True
def get_center(box): """ Get bounding box centeroid. Arguments: box (list): List of bounding box coordinates returned from Azure Cognitive Services API. The list would comprise of x-coordinate, y-coordinate from the left-top corner of the image. Return: center (Dict): x and y coordinates of the centeroid """ x = int(box[0] + (box[4]-box[0])/2) y = int(box[1] + (box[5]-box[1])/2) center = {'x':x,'y':y} return center
def _dict_to_object(dict_): """ Convert a dictionary loaded from a JSON file to an object """ if '__class__' in dict_: module = __import__(dict_['__module__'], fromlist=[dict_['__class__']]) klass = getattr(module, dict_['__class__']) # Check that this is a class that we're expecting if dict_['__class__'] in ['datetime']: inst = klass(**dict_['__kwargs__']) else: msg = ('Unknown type to load from JSON: {}'. format(dict_['__class__'])) raise TypeError(msg) else: inst = dict_ return inst
def is_lego_id(vid, pid): """Determine if a LEGO Hub by checking the vendor id and product id.""" # Values obtained from PyBricks project: https://github.com/pybricks/technical-info/blob/master/assigned-numbers.md # 0x0694 0x0008 LEGO Technic Large Hub in DFU mode (SPIKE Prime) # 0x0694 0x0009 LEGO Technic Large Hub (SPIKE Prime) # 0x0694 0x0010 LEGO Technic Large Hub (MINDSTORMS Inventor) # 0x0694 0x0011 LEGO Technic Large Hub in DFU mode (MINDSTORMS Inventor) return vid == 0x0694 and (pid == 0x0008 or pid == 0x0009 or pid == 0x0010 or pid == 0x0011)
def read_file(file_name: str): """read file """ with open(file_name) as f: return f.read()
def jsonapi_id_schema(value=None): """Generate a Cerberus schema for validating a JSONAPI id value. :param value: The required value for the id value [optional] :type value: ``string`` :return: A Cerberus schema for the JSONAPI id value """ if value: return {'type': 'string', 'required': True, 'empty': False, 'allowed': [value]} else: return {'type': 'string', 'required': True, 'empty': False}
def cross_entropy_cost_derivative(a, y): """The derivative of the cross-entropy cost function. This function is used in backpropagation to calculate the error between the output of the network and the label. Where 'a' is the network input and 'y' is the label.""" return (a - y)
def _is_subclass(obj, superclass): """Safely check if obj is a subclass of superclass.""" try: return issubclass(obj, superclass) except Exception: return False
def ComputeIntercoPfx(svlan): """ Generates a 100.64/10 prefix based on the svlan-id Output if svlan=1001 : 100.67.233 """ byte1 = 100 byte2 = 64 + int(svlan/256) byte3 = svlan%256 return str(byte1)+"."+str(byte2)+"."+str(byte3)
def make_protein_index(proteins): """Indexes proteins.""" prot_index = {} skip = set(['sp', 'tr', 'gi', 'ref']) for i, p in enumerate(proteins): accs = p.accession.split('|') for acc in accs: if acc in skip: continue prot_index[acc] = i return prot_index
def satoshi_str(number): """ string prices rounded to satoshi """ return "%.8f" % float(number)
def process_size(size): """ Docker SDK provides size in bytes, which is processed here to provide Docker CLI-like output. """ final_size = '' if size < 1000: final_size = f'{size}B' elif size > 1000 and size < 1000000: size = round(size / 1000, 1) final_size = f'{size}KB' elif size > 1000000 and size < 1000000000 : size = round(size / 1000000, 1) final_size = f'{size}MB' elif size > 1000000000: size = round(size / 1000000000, 1) final_size = f'{size}GB' return final_size
def _select_pattern_problem(prob, patterns): """ Selects a benchmark type based on the problem kind. """ if '-reg' in prob: return patterns['regressor'] if '-cl' in prob and '-dec' in prob: return patterns['classifier_raw_scores'] if '-cl' in prob: return patterns['classifier'] if 'cluster' in prob: return patterns['clustering'] if 'outlier' in prob: return patterns['outlier'] if 'num+y-tr' in prob: return patterns['trainable_transform'] if 'num-tr-pos' in prob: return patterns['transform_positive'] if 'num-tr' in prob: return patterns['transform'] if 'm-label' in prob: return patterns['multi_classifier'] raise ValueError( "Unable to guess the right pattern for '{}'.".format(prob))
def find_the_duplicate(nums): """Find duplicate number in nums. Given a list of nums with, at most, one duplicate, return the duplicate. If there is no duplicate, return None >>> find_the_duplicate([1, 2, 1, 4, 3, 12]) 1 >>> find_the_duplicate([6, 1, 9, 5, 3, 4, 9]) 9 >>> find_the_duplicate([2, 1, 3, 4]) is None True """ # import collections # print([item for item, count in collections.Counter(nums).items() if count > 1]) # from iteration_utilities import duplicates # return list(duplicates(nums)) # Couldn't get the above to work, trying again # unique_nums = list(set(nums)) # print(nums) # print(unique_nums) # return [item for item in unique_nums if item not in nums] # return list(set(nums) - set(unique_nums)) # Couldn't get the above to work, trying again dupli_validator = [] for num in nums: if num not in dupli_validator: dupli_validator.append(num) else: return num return None
def eq_of_motion(t, w, p): """ A simple mass with a force input Arguments: w : the states, [x, x_dot] t : the current timestep p : the parameters p = [m, curr_force] Returns: sysODE : 1st order differential equations """ m, curr_force = p sysODE = [w[1], 1.0 / m * curr_force] return sysODE
def xyzw_to_wxyz(arr): """ Convert quaternions from pyBullet to numpy. """ return [arr[3], arr[0], arr[1], arr[2]]
def _contains_access_modifier(line): """Checks whether the line contains some Java access modifier in it. Args: line: the line to check. Returns: bool: `True` if the line contains access modifier and `False` otherwise. """ return 'public ' in line or 'private ' in line or 'protected ' in line
def get_first_text_flag(config): """Creates a valid flag with the flag format using the flag format and the first text flag, if it exists. Args: config (dict): The normalized challenge config Returns: string: A valid flag. May be an empty string, in which case it's probably not a valid flag. This happens if there is no text type flag. """ text_flag = None for flag in config["flags"]: if flag["type"] == "text": text_flag = flag["flag"] break else: return "" if not config["flag_format_prefix"]: return text_flag return config["flag_format_prefix"] + text_flag + config["flag_format_suffix"]