content
stringlengths
42
6.51k
def get_color_from_similarity(similarity_score: float) -> str: """ Return css style according to similarity score """ if float(similarity_score) > 15: return "#990033; font-weight: bold" if float(similarity_score) > 10: return "#ff6600" if float(similarity_score) > 5: return "#f...
def get_string(element): """Helper for safely pulling string from XML""" return None if element == None else element.string
def sort_by_points(hn_list): """ Returns a sorted list of dictionaries from alternative_hacker_news to be ordered by score (highest first). """ sorted_list = sorted(hn_list, key=lambda k: k["score"], reverse=True) return sorted_list
def and_join(strings): """Join the given ``strings`` by commas with last `' and '` conjuction. >>> and_join(['Korea', 'Japan', 'China', 'Taiwan']) 'Korea, Japan, China, and Taiwan' :param strings: a list of words to join :type string: :class:`collections.abc.Sequence` :returns: a joined string...
def convert_to_aws_federated_user_format(string): """Make string compatible with AWS ECR repository naming Arguments: string {string} -- Desired ECR repository name Returns: string -- Valid ECR repository name """ string = string.replace(" ", "-") result = "" for ch in stri...
def in_flight_entertainment(flight_length, movie_lengths): """ Loops through the movie lengths and checks whether there are 2 movies to watch which sum up to the flight length :param flight_length: length of the flight in minutes :param movie_lengths: list of movie lengths :return: 2 recommended...
def fibonacci_matrix_mul(n): """ :param n: F(n) :return: val """ if n == 0: return 0 if n == 1: return 1 mul = [[0,1],[1,1]] def matrix_mul(matrix1, matrix2): """ :param matrix1:2*2 matrix :param matrix2: 2*2 matrix :return: 2*2 matrix ...
def convertRomanNumeral(romNumeral): """ converts Roman numerals into ordinary numbers. Params: romNumeral (String) - the Roman numeral string to be converted Returns: num (int): ordinary numbers equivalant of the roman numeral. Examples: >>> num = con...
def test_get_early_out(hour_out,check_out,tolerance): """menghitung berapa lama pegawai pulang lebih awal""" if hour_out > check_out: if (hour_out - check_out) < tolerance: return ' ' else: return hour_out - check_out else: return ' '
def retrograde(motif): """Reverse the order of notes in a motif. None of the notes' parameters are altered. Arguments: motif (list of ints) Returns: A list of ints """ new_motif = [] for i in range(len(motif)-1, -1, -1): new_motif.append(motif[i]) return new_motif
def sn_temp_ratio(signal_Tant, noise_Trms, output=None, verbose=0): """ Returns the signal-to-noise ratio. Parameters ---------- signal_Tant : signal (antenna) temperature [K] noise_Trms : noise rms temperature [K] output : output dictionary (default: Non...
def extract_metadata_from_query_results(query_results): """ Given a Sparql query result, extract nationality, gender and birthdate :param query_results: :return: """ if query_results["results"]["bindings"]: raw_metadata = query_results["results"]["bindings"][0] gender = raw_metad...
def actionIndexInt2Tuple(actionIdx, numActionList): """Transforms an action index to tuple of action indices. Args: actionIdx (int): action index of the discrete action set. numActionList (list): consists of the number of actions in evader and pursuer's action sets. Returns: tuple of...
def _title_to_filename(title: str) -> str: """Formats a title to be a safe filename. Strips down to alphanumeric chars and replaces spaces with underscores. """ return "".join(c for c in title if c.isalnum() or c == " ").replace(" ", "_")
def indent(t, indent=0): """Indent text.""" return '\n'.join(' ' * indent + p for p in t.split('\n'))
def isfloat(value): """ Determine if string value can be converted to a float. Return True if value can be converted to a float and False otherwise. Parameters ---------- value : string String value to try to convert to a float. Returns ------- bool : bool ...
def format_range(low, high, width): """Format a range from low to high inclusively, with a certain width.""" if low == high: return "%0*d" % (width, low) else: return "%0*d-%0*d" % (width, low, width, high)
def contains(node, value): """ Return whether tree rooted at node contains value. @param BinaryTree|None node: binary tree to search for value @param object value: value to search for @rtype: bool >>> contains(None, 5) False >>> contains(BinaryTree(5, BinaryTree(7), BinaryTree(9)), 7) ...
def fuzzy_name(str_in): """ convert to lower cases and remove common delimiters """ if isinstance(str_in, str): return str_in.lower().replace('_', '').replace('-', '') else: return [_s.lower().replace('_', '').replace('-', '') if isinstance(_s, str) else _s for _s in str_in]
def get_stretch(image_name, sample_name): """extract stretch value from filename ex: hpr10p100031.TIF --> 0.1% """ image_name = image_name.replace(sample_name, '') image_name = image_name.split('.')[0] u, d = image_name.split('p') d = d[:1] s = float(u) + float(d)/10 return s
def fancy_ind(inds, shape): """ This simple function gives the index of the flattened array given the indices in an unflattened array. Parameters ---------- inds : list- or array-like List of indices in the unflattened array. For sensical results, must all be less than value at co...
def range(actual_value, lower_limit, higher_limit): """Assert that actual_value is within range (inclusive).""" result = lower_limit <= actual_value <= higher_limit if result: return result else: raise AssertionError( "{!r} is OUTSIDE RANGE of {!r} to {!r} inclusive".format( ...
def decode_text(text): """Decodes a string from HTML.""" output = text output = output.replace('\\n', '\n') output = output.replace('\\t', '\t') output = output.replace('\s', '\\') output = output.replace('&lt;', '<') output = output.replace('&gt;', '>') output = output.replace('&quot;',...
def add_dictionnaries(dict_1, dict_2): """Add to dictionnaries. Assumes both dictionnaries have the same keys. Parameters ---------- dict_1 : dict First dictionnary. dict_2 : dict Second dictionnary. Returns ------- dict Sum of both dictionnaries. "...
def pop_file(in_files): """ Select the first file from a list of filenames. Used to grab the first echo's file when processing multi-echo data through workflows that only accept a single file. Examples -------- >>> pop_file('some/file.nii.gz') 'some/file.nii.gz' >>> pop_file(['...
def scan_year(visit, studyid='TON'): """ Retrieve the year in which a scan was collected. Parameters ---------- visit : str or int Visit number studyid: str, optional Specifies the study from which files will be retrieved. Valid values are 'THD' and 'TON'. Returns ...
def is_p2tr(script: bytes) -> bool: """ Determine whether a script is a P2TR output script. :param script: The script :returns: Whether the script is a P2TR output script """ return len(script) == 34 and script[0] == 0x51 and script[1] == 0x20
def cc_bad_mock(url, request): """ Mock for carrier checking, worst case. """ badbody = str('<?xml version="1.0" encoding="UTF-8"?><response ttl="600000"><country id="222" name="United States"/><carrier id="0" name="default" icon="-1" downloadlimit="50" allowedoverride="false"/></response>') return ...
def n_blocks(n_frames, block_length): """Calculates how many blocks of _block_size_ frames with frame_shift separation can be taken from n_frames""" return n_frames - block_length + 1
def move_down(rows, t): """ A method that takes number of rows in the matrix and coordinates of bomb's position and returns coordinates of neighbour located bellow the bomb. It returns None if there isn't such a neighbour """ x, y = t if x == rows: return None else: return (...
def reverse(lst): """Reverse a list """ return lst[::-1]
def parse_list_to_string(tags): """ Parses a list of tags into a single string with the tags separated by comma :param tags: A list of tags :return: A string with tags separated by comma """ return ', '.join(tags)
def comp2dict(composition): """Takes composition: Si20 O10, returns dict of atoms {'Si':20,'O':10}""" import re pat = re.compile('([A-z]+|[0-9]+)') m = re.findall(pat,composition) return dict(list(zip(m[::2],list(map(int,m[1::2])))))
def dictsize(value): """Turn python dict into JSON formatted string""" if not value: return '(n/a)' return len(str(value))
def _int_to_tuple_conv(axes): """ Converts ints to tuples in input axes, expected by most validation checks. """ for x in [0, 1]: if isinstance(axes[x], int): axes[x] = (axes[x],) return axes
def sort_separation(separation): """Sort a separation. :param separation: Initial separation. :return: Sorted list of separation. """ if len(separation[0]) > len(separation[2]): return [sorted(separation[2]), sorted(separation[1]), sorted(separation[0])] return [sorted(separation[0]), s...
def rgb_color_wheel(wheel_pos): """Color wheel to allow for cycling through the rainbow of RGB colors.""" wheel_pos = wheel_pos % 255 if wheel_pos < 85: return 255 - wheel_pos * 3, 0, wheel_pos * 3 elif wheel_pos < 170: wheel_pos -= 85 return 0, wheel_pos * 3, 255 - wheel_pos * ...
def capitalize_all(x): """Capitalize all words of a sentence""" _str = [word.capitalize() for word in x.split(' ')] return ' '.join(_str)
def get_data_config(config, spec_len): """ Prepares configuration dictionary for validation dataset. """ data_config = {} data_config.update({'fps': config['fps'], 'sample_rate': config['sample_rate'], 'frame_len': config['frame_len'], ...
def is_symbol(s): """A string s is a symbol if it starts with an alphabetic char. >>> is_symbol('R2D2') True """ return isinstance(s, str) and s[:1].isalpha()
def chunk_data(data, size): """Creates a list of chunks of the specified `size`. Args: data (list): self-explanatory. size (int): desired size of each chunk, the last one can be <= `size`. Returns: coll (list): lists of lists. """ coll = [] start_indx = 0 while star...
def f(x: int, n: int) -> float: """ Calcula el resultado de la serie. """ return sum([((x - i) ** n) / i for i in range(1, n + 1)])
def prepend(string, prefix): """Append something to the beginning of another string. Parameters ---------- string : str String to prepend to. prefix : str String to add to the beginning. Returns ------- str String with the addition to the beginning. Notes ...
def safe_print_list_integers(my_list=[], _x=0): """ safe_print_list_integers """ counter = 0 for i in range(_x): try: print("{:d}".format(my_list[i]), end="") counter += 1 except (ValueError, TypeError): continue print() return counter
def get_width(x: int, gw: float, divisor: int=8 ): """ Using gw to control the number of kernels that must be multiples of 8. return math.ceil(x / divisor) * divisor """ if x*gw % divisor == 0: return int(x*gw) return (int(x*gw/divisor)+1)*divisor
def selectSort(list1, list2): """ Razeni 2 poli najednou (list) pomoci metody select sort input: list1 - prvni pole (hlavni pole pro razeni) list2 - druhe pole (vedlejsi pole) (kopirujici pozice pro razeni podle hlavniho pole list1) returns: d...
def proxy_exception(host, list): """Return 1 if host is contained in list or host's suffix matches an entry in list that begins with a leading dot.""" for exception in list: if host == exception: return 1 try: if exception[0] == '.' and host[-len(exception):] == excep...
def unique(it): """Return a list of unique elements in the iterable, preserving the order. Usage:: >>> unique([None, "spam", 2, "spam", "A", "spam", "spam", "eggs", "spam"]) [None, 'spam', 2, 'A', 'eggs'] """ seen = set() ret = [] for elm in it: if elm not in seen: ...
def _identity_decorator(func, *args, **kwargs): """Identity decorator. This isn't as useless as it sounds: given a function with a ``__signature__`` attribute, it generates a wrapper that really does have that signature. """ return func(*args, **kwargs)
def items_sum(items, field): """Take a list of items, and return the sum of a given field.""" if items: sum = 0 for item in items: value = getattr(item, field) if type(value) in (int, float): sum += value return sum else: return None
def _compute_fans(shape): """ Taken from https://github.com/tensorflow/tensorflow/blob/2b96f3662bd776e277f86997659e61046b56c315/tensorflow/python/ops/init_ops_v2.py#L994 Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Ret...
def _get_sqa_table_id(wtq_table_id): """Goes from 'csv/123-csv/123.csv' to 'table_csv/123-123.csv'.""" return u'table_csv/' + wtq_table_id[4:].replace('/', '-').replace('-csv', '')
def get_num_frames(dur, anal): """Given the duration of a track and a dictionary containing analysis info, return the number of frames.""" total_samples = dur * anal["sample_rate"] return int(total_samples / anal["hop_size"])
def __bounding_box(p1,p2): """Returns left, bottom, right and top coordinate values""" if p1[0] < p2[0]: left=p1[0] right=p2[0] else: left=p2[0] right=p1[0] if p1[1] < p2[1]: bottom=p1[1] top=p2[1] else: bottom=p2[1] top=p1...
def count_sign_changes(values): """ Returns the number of sign changes in a list of values. """ count = 0 prev_v = 0 for i, v in enumerate(values): if i == 0: prev_v = v else: if prev_v * v < 0: count += 1 prev_v = v return count
def find_char(pixel, weighted_chars): """Find and return character from dict with similar darkness to image pixel""" return min(weighted_chars.keys(), key=lambda c: abs(pixel - weighted_chars[c]))
def bCOM(r, ra, b0): """ Anisotropy profile from (Cuddeford 1991; Osipkov 1979; Merritt 1985) inversion. Parameters ---------- r : array_like, float Distance from center of the system. ra : float Anisotropy radius. b0 : float Anisotropy at r = 0. Returns ---...
def _mat_mat_add_fp(x, y): """Add to matrices.""" return [[a + b for a, b in zip(x_row, y_row)] for x_row, y_row in zip(x, y)]
def underscored(s: str) -> str: """Turn spaces in the string ``str`` into underscores. Used primarely for filename formatting. """ return '_'.join(s.split(' '))
def unprocess_args(args): """Unprocesses processed config args. Given a dictionary of arguments ('arg'), returns a dictionary where all values have been converted to string representation. Returns: args, where all values have been replaced by a str representation. """ unprocessed_args ...
def decrypt_seiga_drm(enc_bytes, key): """Decrypt the light DRM applied to certain Seiga images.""" n = [] a = 8 for i in range(a): start = 2 * i value = int(key[start:start + 2], 16) n.append(value) dec_bytes = bytearray(enc_bytes) for i in range(len(enc_bytes)): ...
def build_filename(artifact_id, version, extension, classifier=None): """ Return a filename for a Maven artifact built from its coordinates. """ extension = extension or '' classifier = classifier or '' if classifier: classifier = f'-{classifier}' return f'{artifact_id}-{version}{cla...
def filter_dict_by_key_value(dict_, key, value): """ helper function to filter a dict by a dict key :param dict_: ``dict`` :param key: dict key :param value: dict key value :returns: filtered ``dict`` """ return {k: v for (k, v) in dict_.items() if v[key] == value}
def average(measurements): """ Use the builtin functions sum and len to make a quick average function """ # Handle division by zero error if len(measurements) != 0: return sum(measurements)/len(measurements) else: # When you use the average later, make sure to include something l...
def comm(lhs, rhs): """Returns (left-only, common, right-only) """ com = lhs & rhs return (lhs-com), com, (rhs-com)
def int_to_binstr(i, bits): """Convert integer to a '01' string. Args: bits (int): Number of bits for this integer. Returns: str: binary representation of the integer. """ output = '' for j in range(0,bits): bit = (i & (1 << j)) >> j ou...
def is_str_empty(string): """ Check is string empty/NoNe or not. :param string: :return: """ if string is None: # check for None return True if not string or not string.strip(): # check for whitespaces string return True return False
def fibonacci_recursive(n): """ Compute the Fibonacci numbers with given number by recursive method :param n: given number :type n: int :return: the Fibonacci numbers :rtype: int """ if n == 0: return 0 elif n == 1: return 1 elif n < 0: return -1 ret...
def produced_by(entry): """ Modify source activity names to clarify data meaning :param entry: original source name :return: modified activity name """ if "ArtsEntRec" in entry: return "Arts Entertainment Recreation" if "DurableWholesaleTrucking" in entry: return "Durable Who...
def authorize_header(auth_token) -> str: """create a properly formatted `authorization` header for Pomerium Args: auth_token: string format service account credentials """ return 'Pomerium ' + auth_token
def create_metadata( input_name_list, input_type_list, input_shape_list, output_name_list, output_type_list, output_shape_list, model_input_list=None, model_output_list=None, custom_meta_dict=None, ): """ Facilitates creation of a metadata ...
def calc_points_hit(num_transfers, free_transfers): """ Current rules say we lose 4 points for every transfer beyond the number of free transfers we have. Num transfers can be an integer, or "W", "F", "Bx", or "Tx" (wildcard, free hit, bench-boost or triple-caption). For Bx and Tx the "x" corres...
def numberofdupes(string, idx): """return the number of times in a row the letter at index idx is duplicated""" # "abccdefgh", 2 returns 1 initial_idx = idx last = string[idx] while idx+1 < len(string) and string[idx+1] == last: idx += 1 return idx-initial_idx
def merge_values(list1, list2): """Merge two selection value lists and dedup. All selection values should be simple value types. """ tmp = list1[:] if not tmp: return list2 else: tmp.extend(list2) return list(set(tmp))
def filter_fields(header, data, fields): """Filter (header, data) with selected header fields. Args: header ([str]): The header. data ([[float]]): The data, with the same number of columns as header. fields ([str]): The fields that need to be written. Returns: (header ([str]), data ([[float]])) ...
def calculate(below): """Returns the sum of all the multiples of 3 or 5 below the specified number""" answer = sum(x for x in range(below) if (x % 3 == 0 or x % 5 == 0)) answer = str(answer) return answer
def huber_loss(r, delta): """Huber loss function, refer to wiki https://en.wikipedia.org/wiki/Huber_loss""" return (abs(r) <= delta) * r ** 2 / 2 + (abs(r) > delta) * delta * (abs(r) - delta / 2)
def createJDL(jooID, directory, jobCE): """ _createJDL_ Create a simple JDL string list """ jdl = [] jdl.append("universe = globus\n") jdl.append("should_transfer_executable = TRUE\n") jdl.append("notification = NEVER\n") jdl.append("Executable = %s/submit.sh\n" % (directory)) ...
def safestr(value): """ Turns ``None`` into the string "<None>". :param str value: The value to safely stringify. :returns: The stringified version of ``value``. """ return value or '<None>'
def convert_mac_colon_to_dot_format(mac_addr): """ Convert mac address in colon format to dot format For e.g convert aa:bb:cc:dd:ee:ff to aabb.ccdd.eeff Args(str): mac address in colon format Returns(str): mac address in dot format """ mac = mac_addr.split(":") mac_add...
def humanize_bytes(num, suffix='B'): """ Via # https://stackoverflow.com/a/1094933""" for unit in ['','K','M','G','T','P','E','Z']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f %s%s" % (num, 'Yi', suffix)
def func_xy_ab_kwargs(x, y, a=2, b=3, **kwargs): """func. Parameters ---------- x, y: float a, b: int kwargs: dict Returns ------- x, y: float a, b: int kwargs: dict """ return x, y, a, b, None, None, None, kwargs
def filter_more_characters(words, anagram): """ Filters the words which contain a symbol more times than it is present in the anagram. """ ret = [] append_flag = True for word in words: word_chars = list(word) anagram_chars = list(anagram) word_chars_set = set(word) ...
def _find_all_pairs(list): """ returns all pairs created from the given list. (a, b) is not the same as (b, a). """ pairs = set(); for value_a in list: for value_b in list: pairs.add((value_a, value_b)) return pairs
def mul(array): """ Return the product of all element of the array """ res = 1 for ele in array: res *= ele return res
def compute_cos2phi(dxs, dys, square_radius): """Compuet cos 2 phi.""" return (dxs - dys) / square_radius
def get_clarifai_tags(clarifai_response, probability): """Get the response from the Clarifai API and return results filtered by concepts with a confidence set by probability parameter (default 50%)""" results = [] concepts = [] # Parse response for Color model try: concepts = [ ...
def V_tank_Reflux(Reflux_mass, tau, rho_Reflux_20, dzeta_reserve): """ Calculates the tank for waste. Parameters ---------- Reflux_mass : float The mass flowrate of Reflux, [kg/s] tau : float The time, [s] rho_Reflux_20 : float The destiny of waste for 20 degrees celc...
def build_obj_ref_list(objects): """ :param objects: Python list of requested objects. :returns: Tcl list of all requested objects references. """ return ' '.join([o.ref for o in objects])
def is_prime(n): """ Very slow implementation """ for i in range(2, n): if n % i == 0: return False return True
def get_all_refs(schema): """Get all ref links in a schema. Traverses a schema and extracts all relative ref links from the schema, returning a set containing the results. Parameters: schema: An OAS schema in the form of nested dicts to be traversed. Returns: set: All of the ref l...
def max_gini(n, ys): """Calculates the normalisation coefficient for the generalised Gini index. Parameters ---------- n : int The number of agents in the simulation. ys : list of int The agents' cumulative utilities. Returns ------- int The normalisation coeffi...
def ElfHash(name): """Compute the ELF hash of a given input string.""" h = 0 for c in name: h = (h << 4) + ord(c) g = h & 0xf0000000 h ^= g h ^= g >> 24 return h & 0xffffffff
def group_arg_and_key(parameter_arg_and_keys): """ Group argnames based on key :param parameter_arg_and_keys: [{"name": <arg_name>, "key": <arg_key>}] :return: {"<arg_key>": [<arg_name1>, <arg_name2>]} """ keys_argnames_dict = {} for parameter_arg_and_key in parameter_arg_and_keys: typ = parameter_arg...
def dictFromTokenList(paramlist): """Return a dictionary formed from the terms in paramlist. paramlist is a sequence of items in the form parametername, =, value. If there are duplicates, the last one wins.""" ret = {} msg = "Ill-formed parameter list: keywords and values must have the...
def longest (s1, s2, s3): """Longest of three strings. You may assume that the longest string is unique. (What would you do if it wasn't?) Params: s1 (string) s2 (string) s3 (string) Returns: (string) longest string """ # INSERT YOUR CODE HERE, replacing 'pass' ...
def clean_dict(target, remove=None): """Recursively remove items matching a value 'remove' from the dictionary :type target: dict """ if type(target) is not dict: raise ValueError("Target is required to be a dict") remove_keys = [] for key in target.keys(): if type(target[key])...
def apply_from_data(act_fun, d): """ Computes the effect (substitution) of an action. :param act_fun: process action (a dictionary mapping variables to expressions) :param d: a data space :return: a substitution """ return dict([(x, f(d)) for (x,f) in act_fun.items()])
def flag_warning(voltage, check): """Set flag for whether voltage threshold has been exceeded Args: voltage (float): float value to be checked Returns: bool: bool of threshold check """ if (voltage < 299.99 and voltage > -299.99) and check: return True return False
def ubtou(str_in): """ Shorthand for converting unicode bytes to UTF-8 """ if not isinstance(str_in, bytes): return str_in return str_in.decode('utf-8')