content
stringlengths
42
6.51k
def stag_density_ratio(M, gamma): """Stagnation density / static density ratio. Arguments: M (scalar): Mach number [units: dimensionless]. gamma (scalar): Heat capacity ratio [units: dimensionless]. Returns: scalar: the stagnation density ratio :math:`\\rho_0 / \\rho` [units: dimen...
def reverse(string): """ >>> reverse('Robin') 'niboR' """ if len(string) < 2: return string else: return reverse(string[1:]) + string[0]
def vflip(anns, size): """ Vertically flip the bounding boxes of the given PIL Image. Parameters ---------- anns : ``List[Dict]`` Sequences of annotation of objects, containing `bbox` of [l, t, w, h]. size : ``Sequence[int]`` Size of the original image. """ w, h = size ...
def follows(trace, distance=1): """Returns a mapping (aka. dict) from pairs of activities to frequency. A pair (a, b) is part of the mapping if activity b directly follows activity a, in any of the traces. Parameters ---------- distance: int Distance two activities have to be appart to ...
def clean_and_split(input_val, split_by_char=',', enclosure_char='{|}|[|]', strip_chars='"', also_remove_single_inv_comma=False): """ Returns a dictionary of split columns Used for amenities and host verifications within get_cleaned_listings() :params input_val array: :params sp...
def normalize(iter): """ Normally takes the output of `extrapolate` and makes a dictionary suitable for applying to a connector. """ rd = {} for (k, v) in iter: sd = rd for sk in k[:len(k)-1]: sd = sd.setdefault(sk, {}) sd[k[-1]] = v return rd
def _version_for_config(version, config): """Returns the version string for retrieving a framework version's specific config.""" if "version_aliases" in config: if version in config["version_aliases"].keys(): return config["version_aliases"][version] return version
def tick(text: str): """Add '`' to text""" return f"`{text}`"
def splitSecondLevelEntry(name): """Split second-level entry and return (first, second) pair. If name is not a second level entry then (None, name) is returned. """ xs = None if name.count('::') > 1 and ' ' in name: xs = name.split(' ', 1) elif '#' in name: xs = name.split('#', ...
def handle_same_string(str1, alist): """ if a string already exist in a list, add a number to it """ if str1 in alist: for i in range(1, 1000): str1_ = str1 + ' (%i)' % i if str1_ not in alist: return str1_ else: return str1
def remove_unrelated_domains(subdomains, domains): """ This function removes from the entire set hostnames found, the ones who do not end with the target provided domain name. So if in the list of domains we have example.com and our target/scope is example.it, then example.com will be removed becaus...
def have_txt_extension(l): """Check if .txt extension is present""" if ".txt" in str(l): return 1 else: return 0
def int_to_bits(i:int): """Take an integer as input and return the bits written version.""" return "{:0{}b}".format(i,i.bit_length())
def make_sequence(elements): """ Ensure that elements is a type of sequence, otherwise it converts it to a list with only one element. """ if isinstance(elements, (list, set, tuple)): return elements elif elements is None: return [] else: return [elements]
def calculate_alphabet_from_order(ORDER): """ Generates aplhabet from order """ LOWERCASE = "abcdefghijklmnopqrstuvwxyz" UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ALPHABET = "" for CHAR in ORDER: if CHAR.islower(): ALPHABET = "%s%s" % (ALPHABET, LOWERCASE) elif CHAR.isupper(): ALPHABET...
def amax(lst): """ return max value by deviation from 0 :param lst iterable: list of values to find max in :returns: max value by deviation from 0 """ return max([abs(x) for x in lst])
def is_templated(module): """Returns an indication where a particular module is templated """ if "attr" not in module: return False elif module["attr"] in ["templated"]: return True else: return False
def is_list(value): """Checks if value is a list""" return isinstance(value, list)
def median(subarr, k): """ Return the median of the subarray based on the value ok "k" """ even_k = (k % 2 == 0) if even_k: right = k / 2 left = right - 1 return (subarr[left] + subarr[right]) / 2 else: id = k // 2 return subarr[id]
def generate_sol_patterns(patterns, ngrams): """A method to generate SOL patterns given the textual patterns and ngrams. Parameters ---------- patterns : type List Textual Patterns ngrams : type List of tuples NGrams Returns ------- type List Returns SOL Pattern...
def incrementdefault(obj: dict, key, default: int = 0) -> int: """Increments value stored in the `obj` under `key`. Returns the incremented value. If value with specified key does not exist, then initializes it with `default` and then increments it. """ val = obj.setdefault(key, default) + 1 ...
def dict_to_parameter_list(d): """ :type d: dict :rtype: list[dict] """ return [{u'name': k, u'value': v} for k, v in d.items()]
def find_recipes_2(pattern): """ Calculate the number of recipes in the sequence before the given pattern appears. :param pattern: the pattern to identify :return: the number of recipes to the left of the pattern >>> find_recipes_2('51589') 9 >>> find_recipes_2('01245') 5 >>> find_r...
def is_serialised(serialised): """ Detects whether a ``bytes`` object represents an integer. :param serialised: A ``bytes`` instance which must be identified as being an integer or not. :return: ``True`` if the ``bytes`` likely represent an integer, or ``False`` if they do not. """ first_byte = True for byte i...
def get_valid_crop_size(crop_size, upscale_factor): """ If we upscale by upscale_factor, then hr_image needs to be dividable by upscale_factor to have a valid lr_image. """ return crop_size - (crop_size % upscale_factor)
def generate_resp_obj(content_type, responses): """ Generate response object """ resp_obj = { "type": "object", "properties": dict(), "additionalProperties": False, } for resp_key, resp_val in responses.items(): if 'content' in responses[resp_key] and ( ...
def open_time(km, brevet_distance): """ input: km brevet_distance is one of the standered distances 200,300,400,600,1000 retun: Opening time in minutes """ ## brevet_dict[brevet_distance]=[max_time,min_speed] brevet_max = {200:353, 300:540,400:728,600:1128,100...
def starts_with_triple(string): """Return True if the string starts with triple single/double quotes.""" return (string.strip().startswith('"""') or string.strip().startswith("'''"))
def reverse_transformation(text): """ Reverses a given string so that the first character becomes the last one """ return text[::-1]
def getRelativeFreePlaceIndexForCoordinate(freePlaceMap, x, y): """ Returns the Index in the FreePlaceValueArray in witch the given Coordinate is in :param freePlaceMap: The FreePlaceMap to check on :param x: The X Coordinate to Check for :param y: The Y Coordinate to Check for :return: The foun...
def ok(n): """ Successful import of ``n`` records :param int n: number of records which should have been imported """ return n, 0, 0, 0
def model_snowaccumulation(tsmax = 0.0, tmax = 0.0, trmax = 0.0, precip = 0.0): """ - Name: SnowAccumulation -Version: 1.0, -Time step: 1 - Description: * Title: snowfall accumulation calculation * Author: STICS * Reference: do...
def get_useful_fields(repos, repo_count): """Selects the useful fields from the repos Arguments: repos {list} -- the list of repos to be cleaned repo_count {int} -- the number of repos Returns: {dict} -- the standard output format for the program """ filtered_repos = [] ...
def similar(x,y): """ function that checks for the similarity between the words of two strings. :param x: first string :param y: second string :return: returns a float number which is the result of the division of the length of the intersection between the two strings' wor...
def power_set(arr): """ 8.4 Power Set: Write a method to return all subsets of a set. """ if len(arr) == 0: return [ [] ] # only the empty set head, tail = arr[0], arr[1:] tail_subsets = power_set(tail) head_subsets = [] for sub in tail_subsets: new_sub = sub[:] new_sub.a...
def inverse_a_mod_p(a, p): """ Use the Bezout law to calculate the inverse of e to the modulus of phi. """ s, t, sn, tn, r = 1, 0, 0, 1, 1 while r != 0: q = p // a r = p - q * a st, tt = sn * (-q) + s, tn * (-q) + t s, t = sn, tn sn, tn = st, tt ...
def validateDSType(dsType): """ >>> validateDSType('counter') 'COUNTER' >>> validateDSType('ford prefect') Traceback (most recent call last): ValueError: A data source type must be one of the following: GAUGE COUNTER DERIVE ABSOLUTE COMPUTE """ dsType = dsType.upper() valid = ['GAUGE...
def indent_string_block(s, indent=2): """ Indents all the lines of s by indent number of spaces """ indent_str = ' ' * indent return indent_str + s.replace('\n', '\n' + indent_str)
def has_function_call(instructions): """ A function to determine whether the instruction contain any calls to any functions. :param instructions: The instructions to check for function calls :return: Whether the instructions contain any calls to any functions as a boolean value """ for line in i...
def parse_args(args:dict): """Parse arguments passed to a graphql query name or nodes and returns a string of arguments Args: dict (list): The arguments you want passed to your node or query name. An example for retrieving balances is: {"cryptocurrency":"bitcoin"} Retu...
def group_32(s): """Convert from 8-bit bytes to 5-bit array of integers""" result = [] unused_bits = 0 current = 0 for c in s: unused_bits += 8 current = (current << 8) + c while unused_bits > 5: unused_bits -= 5 result.append(current >> unused_bits) ...
def _stacktrace_end(stacktrace, size): """ Gets the last `size` bytes of the stacktrace """ stacktrace_length = len(stacktrace) if stacktrace_length <= size: return stacktrace return stacktrace[:-(stacktrace_length-size)]
def emails_parse(emails_dict): """ Parse the output of ``SESConnection.list_verified_emails()`` and get a list of emails. """ return sorted([email for email in emails_dict['VerifiedEmailAddresses']])
def gql_api_keys(fragment): """ Return the GraphQL assets query """ return f''' query($where: ApiKeyWhere!, $first: PageSize!, $skip: Int!) {{ data: apiKeys(where: $where, skip: $skip, first: $first) {{ {fragment} }} }} '''
def _sliceString(s,vec): """Slice string s at integer inds in vec""" return ''.join([s[i] for i in vec])
def _is_within_rect(xy, p1, p2): """ If xy is withing rectangle defined by p1, p2 """ for i in range(2): if p1[i] <= xy[i] <= p2[i] or p2[i] <= xy[i] <= p1[i]: continue else: return False return True
def get_chunks(labels): """ It supports IOB2 or IOBES tagging scheme. You may also want to try https://github.com/sighsmile/conlleval. """ chunks = [] start_idx,end_idx = 0,0 for idx in range(1,len(labels)-1): chunkStart, chunkEnd = False,False if labels[idx-1] not in...
def bytecount(numbytes): """Convert byte count to display string as bytes, KB, MB or GB. 1st parameter = # bytes (may be negative) Returns a short string version, such as '17 bytes' or '47.6 GB' """ retval = "-" if numbytes < 0 else "" # leading '-' for negative values absvalue = abs(numbytes)...
def parse_isomer_spin(spin): """Parses nubase style spin information returns dictionary {value, extrapolated} """ result = {} result['extrapolated'] = True if spin.count('#') > 0 else False if result['extrapolated']: spin = spin.replace('#', ' ') result['value'] = spin[0:8].strip() ...
def _extract_defines_from_option_list(lst): """Extracts preprocessor defines from a list of -D strings.""" defines = [] for item in lst: if item.startswith("-D"): defines.append(item[2:]) return defines
def rule_lift(f11, f10, f01, f00): """ Computes the lift for a rule `a -> b` based on the contingency table. params: f11 = count a and b appearing together f10 = count of a appearing without b f01 = count of b appearing without a f00 = count of neither a nor b appearing r...
def isiter(obj): """Checks whether given object is iterable.""" return obj is not None and hasattr(obj, '__iter__')
def canon_nexiq(msg): """ Format is: 13:48:06.1133090 - RX - 172 254 137 4 212 128 194 137 """ m = msg.strip().split(" ")[4:] newmsg = [int(x) for x in m] # print(newmsg) return newmsg
def _get_options(opts, with_keyty_valty): """Returns a triple of the options: a key field type, a value field type, and a flag of needs of output generation.""" if ((not with_keyty_valty) and (("key" in opts) or ("value" in opts))): raise Exception("Bad option: key= or value= not allowed") keyt...
def invert_dict(front_dict): """ Take a dict of key->values and return values->[keys] """ back_dict = { value : [] for value in front_dict.values() } for key, value in front_dict.items(): back_dict[value].append(key) return back_dict
def _determine_fields(fields, radars): """ Determine which field should be mapped to the grid. """ if fields is None: fields = set(radars[0].fields.keys()) for radar in radars[1:]: fields = fields.intersection(radar.fields.keys()) fields = list(fields) return fields
def tupleSearch(findme, haystack): """Partial search of list of tuples. The "findme" argument is a tuple and this will find matches in "haystack" which is a list of tuples of the same size as "findme". An empty string as an item in "findme" is used as a wildcard for that item when searching "hayst...
def dict_merge(source, destination): """dest wins""" for key, value in source.items(): if isinstance(value, dict): # get node or create one node = destination.setdefault(key, {}) dict_merge(value, node) else: destination[key] = value return d...
def filterClusterByDis(data, cut): """ Filter inter-ligation clusters by distances """ for key in data: nr = [] for r in data[key]["records"]: d = (r[4] + r[5]) / 2 - (r[1] + r[2]) / 2 if d >= cut: nr.append(r) data[key]["records"] = nr ...
def parser_multiplex_buffer_utilisation_Descriptor(data,i,length,end): """\ parser_multiplex_buffer_utilisation_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "multiplex_buffer_utilisation", "content...
def levenshtein_distance(a, b): """Return the Levenshtein edit distance between two strings *a* and *b*.""" if a == b: return 0 if len(a) < len(b): a, b = b, a if not a: return len(b) previous_row = range(len(b) + 1) for i, column1 in enumerate(a): current_row = [...
def preorder_traversal_iterative(root): """ Return the preorder traversal of nodes' values. - Worst Time complexity: O(n) - Worst Space complexity: O(n) :param root: root node of given binary tree :type root: TreeNode or None :return: preorder traversal of nodes' values :rtype: list[in...
def normalize_framework(framework: str) -> str: """Normalize framework strings by lowering case.""" return framework.lower()
def hex_str_to_bytes(str_hex: str) -> bytes: """Convert hex string to bytes.""" str_hex = str_hex.lower() if str_hex.startswith("0x"): str_hex = str_hex[2:] if len(str_hex) & 1: str_hex = "0" + str_hex return bytes.fromhex(str_hex)
def group_text(text, n=5): """Groups the given text into n-letter groups separated by spaces.""" return ' '.join(''.join(text[i:i+n]) for i in range(0, len(text), n))
def normalize_knot_vector(knot_vector, decimals=18): """ Normalizes the input knot vector to [0, 1] domain. :param knot_vector: knot vector to be normalized :type knot_vector: list, tuple :param decimals: rounding number :type decimals: int :return: normalized knot vector :rtype: list "...
def add_items(inventory, items): """Add or increment items in inventory using elements from the items `list`. :param inventory: dict - dictionary of existing inventory. :param items: list - list of items to update the inventory with. :return: dict - the inventory updated with the new items. """ ...
def normaliseSum(*args): """Returns a list of all the arguments, so that they add up to 1 Args: *args: A variable number of arguments Returns: (list): list of all the arguments that all add up to 1 """ # convert the arguments to a list, so we can operate on it args = list(args...
def _merge_and_count_split_inv(left, right): """Return merged, sorted array and number of split inversions.""" max_left, max_right = len(left), len(right) if max_left == 0 or max_right == 0: return left + right, 0 merged = [] inv_count = 0 i = j = 0 while i < max_left and j < max_r...
def ispoweroftwo(n): """Return True if n is power of two.""" if n<=0: return False else: return n & (n-1) == 0
def capitalize_correct(phrase): """ Capitalizes words in a string, avoiding possessives being capitalized """ phrase = phrase.strip() return " ".join(w.capitalize() for w in phrase.split())
def crc32_combine(crc1, crc2, len2): """Explanation algorithm: http://stackoverflow.com/a/23126768/654160 crc32(crc32(0, seq1, len1), seq2, len2) == crc32_combine( crc32(0, seq1, len1), crc32(0, seq2, len2), len2)""" # degenerate case (also disallow negative lengths) if len2 <= 0: return...
def get_frequency_band(wavelength: float) -> str: """ Frequency bands in the microwave range are designated by letters. This standard is the IEEE radar bands. Parameter: ========== wavelength: float Wavelength in cm. Returns: ======== band: str Radar frequency band ...
def _check_repo_contents(contents_list: list, contents_ext: str): """Returns the list of files in a repo that match the requested extension. Args: contents_list (list): a list of repository content dictionaries from API. contents_ext (str): an extension to limit results. Return...
def get_pins(line): """ Extract the pin names from the vector line """ line = line.replace('{','') line = line.replace(')','') line = line.replace('(','') bits = line.split(',') return [s.strip() for s in bits[1:]]
def has_relative_protocol(uri): """Return True if URI has relative protocol '//' """ start = uri[:2] if start == '//': return True return False
def crop_resize(src, target, right=0, bottom=70): """rescale image to 300dpi""" cropargs = '-{}-{}'.format(right,bottom) return ['convert', src, '-crop' , cropargs, '-resize', '150%', target]
def find_ole_header(fi, data, offset, output): """ Used by guess_multibyte_xor_keys() """ i = 0 pos = 0 found = 0 length = len(data) while i < length: pos = data.find("".join(['\xd0', '\xcf', '\x11', '\xe0', '\xa1', '\xb1', '\x1a', '\xe1']), i) if pos == -1: ...
def extract_ontology_id_from_iri(url: str) -> str: """ Get the ontology short term from iri string :param url: iri of ontology :return: short term of ontology """ if type(url) is not str: raise TypeError("The method only take str as its input") if url.find('/') > -1: elmts = ...
def remove_url(tweet): """ Removes '<url>' tag from a tweet. INPUT: tweet: original tweet as a string OUTPUT: tweet with <url> tags removed """ return tweet.replace('<url>', '')
def dz_any1D(hbot,zeta,hc,dCs,N): """ same as dz_anyND but assume entries are flat arrays of same shape (fancy addressing, staggered access) or scalar. Just compute the product """ return (zeta + hbot)*(hc/N+dCs*hbot)/(hc + hbot)
def poly_eval(P,x): """ Evaluate the polynomial P at x """ out = 0 e = 1 for coef in P: out += coef*e e *= x return out
def serialize_columns(columns): """ Return the headers and frames resulting from serializing a list of Column Parameters ---------- columns : list list of Columns to serialize Returns ------- headers : list list of header metadata for each Column frames : list ...
def split(text): """Split an annotation file by sentence. Each sentence's annotation should be a single string.""" return text.strip().split('\n')[1:-1]
def getJobMetricDimensions(job): """ Store metrics in the same format as Cloudwatch in case we want to use Cloudwatch as a metrics store later :param job: JSON job data struture from dynamodb """ ret = {} dimensions = [] filters = {} job_dim= {} job_dim['Name'] = 'jobId' ...
def guess_max_depth(map_or_seq): """HACK A DID ACK - please delete me when cleaning up.""" if isinstance(map_or_seq, dict): return 1 + max(map(guess_max_depth, map_or_seq.values()), default=0) elif isinstance(map_or_seq, list): return 1 + max(map(guess_max_depth, map_or_seq[0].values()), def...
def round_up_next_multiple(x, mult): """Round integer `x` up to the next possible multiple of `mult`.""" rem = x % mult if rem > 0: return x - rem + mult else: return x
def _weight_table(dat): """ Return weight table. """ table = {} # weight tables for item in dat: if dat[item] not in table: table[dat[item]] = [(item, 1.0)] else: old = table[dat[item]] new = [] for old_item in old: ...
def istag(arg): """Return true if the argument starts with a dash ('-') and is not a number Parameters ---------- arg : str Returns ------- bool """ return arg.startswith('-') and len(arg) > 1 and arg[1] not in '0123456789'
def dir(object: object=None) -> object: """dir.""" return object.__dir__()
def get_available_moves(board_state): """ Return an array of board positions/indices that contain "None". Input: board_state: (0,1,0,None,None,None,None,None,None) a tuple of the board's state Output: an array of board positions/indices of possible moves: ...
def get_tag_type(tagtype, pairs): """ Given a list of (word,tag) pairs, return a list of words which are tagged as nouns/verbs/etc The tagtype could be 'NN', 'JJ', 'VB', etc """ return [w for (w, tag) in pairs if tag.startswith(tagtype)]
def is_same_behavior_id_str(behavior_id_str_1, behavior_id_str_2): """Checks if the two behavior ID strings are the same (e.g. 'fd' vs. 'fd_r' should return True). Args: behavior_id_str_1: Behavior ID as a string. behavior_id_str_2: Behavior ID as a string. """ return behavior_id_st...
def business_rule_3(amount: int, account: int, use_br: bool, threshold: int) -> bool: """ Account sends transactions with combined total value >= threshold within a day. Only works for scatter-gather. :param amount: transaction value :param account: number of involved accounts :param use_br: whethe...
def iyr_valid(passport): """ Check that iyr is valid iyr (Issue Year) - four digits; at least 2010 and at most 2020. :param passport: passport :return: boolean """ return len(passport['iyr']) == 4 and 2010 <= int(passport['iyr']) <= 2020
def headers(mime, length): """Returns a list of HTTP headers given the MIME type and the length of the content, in bytes (in integer or sting format).""" return [('Content-Type', mime), ('Content-Length', str(length))]
def extract_element(item_list, index): """ Safely extract indexed xpath element """ if index < len(item_list): return item_list[index].extract() else: return ""
def _GetArmVersion(arch): """Returns arm_version for the GN build with the given architecture.""" if arch == 'armeabi': return 6 elif arch == 'armeabi-v7a': return 7 elif arch in ['arm64-v8a', 'x86', 'x86_64']: return None else: raise Exception('Unknown arch: ' + arch...
def has_blank_ids(idlist): """ Search the list for empty ID fields and return true/false accordingly. """ return not(all(k for k in idlist))
def coords_add(coords0, coords1): """ Add two coordinates """ return tuple([x0 + x1 for x0, x1 in zip(coords0, coords1)])