content
stringlengths
42
6.51k
def read_optional_from_dict(input_dict, key, standard_val=None, typecast=None): """Tries to read an option from a dictionary. If not found, a standard value is returned instead. If no standard value is informed, None is returned. Data can also be converted by a type cast. ...
def _get_process_times(process_times, requests): """Read in service_time values from requests.""" # loop over requests, see if they have service times. if so, set for req in requests: if 'service_time' in req: process_times[int(req['@node'])] = float(req['service_time']) return proc...
def check_argument_groups(parser, arg_dict, group, argument, required): """ Check for use of arguments. Raise an error if the parser uses an argument that belongs to an argument group (i.e. mode) but the group flag is not used or if the argument is required in the argument group and it's not used. ...
def matscalarMul(mat, scalar): """Return matrix * scalar.""" dim = len(mat) return tuple( tuple( mat[i][j] * scalar for j in range(dim) ) for i in range(dim) )
def idecibel(x): """Calculates the inverse of input decibel values :math:`z=10^{x \\over 10}` Parameters ---------- x : a number or an array Examples -------- >>> from wradlib.trafo import idecibel >>> print(idecibel(10.)) 10.0 """ return 10.0 ** (x / 10.0)
def apply_rules(user, subscription, subscription_rules, rule_logic): """ Apply logic to rules set for each subscription. In a way this authorizes who can see the subscription. Rules can be applied in two ways: All rules must apply and some rules must apply. user: models.User() subscription: ...
def _gp_int(tok): """Get a int from a token, if it fails, returns the string (PRIVATE).""" try: return int(tok) except ValueError: return str(tok)
def radix_sort(lst, base=10): """ Sorts by using the radix sort. This version only works with positive integers. Sorts by creating buckets and putting each number in to its corresponding bucket by looking at each consecutive digit.""" if len(lst) < 2: return lst def lst_to_buckets(lst, base, it...
def _type(obj): """Verb: No-op.""" print(type(obj)) return obj
def _extract_default_values(config_schema): """ :param config_schema: A json-schema describing configuration options. :type config_schema: dict :returns: a dictionary with the default specified by the schema :rtype: dict | None """ defaults = {} if 'properties' not in config_schema: ...
def _refine_index_filename(filename): """ get the current file name for CSV index """ return f"{filename}.index"
def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. """ return int(((val - src[0]) / float(src[1] - src[0])) * (dst[1] - dst[0]) + dst[0])
def polyline2linesegments(polyline): """Convert a polyline to a sequence of lines""" if len(polyline) < 2: raise ValueError("A polyline must have at least length 2") result = [] for p0, p1 in zip(polyline, polyline[1:]): result.append((p0, p1)) return result
def convert_diagram_to_relative(diag, max_dim): """Convert the persistence diagram using duality. Here, add one to the dimension. :param diag: persistence diagram in the Gudhi format. :type diag: list of tuples (dim, (birth, death)). """ relative_betti = {} for p in diag: dim = p[0] ...
def sanitize_ap_name(input_name): """ Returns access_point name that begins with a number or lowercase letter, 3 to 50 chars long, no dash at begin or end, no underscores, uppercase letters, or periods :param input_name: """ output_name = input_name.translate( str.maketrans({'_':...
def dms2dd(degrees, minutes, seconds, quadrant): """ Convert degrees, minutes, seconds, quadrant to decimal degrees :param degrees: coordinate degrees :type degrees: int :param minutes: coordinate minutes :type minutes: int :param seconds: coordinate seconds :type seconds: int :par...
def isprime(n=936): """Write a function, is_prime, that takes a single integer argument and returns True when the argument is a prime number and False otherwise.""" if n < 3: return False for i in range(2, n): if n % i == 0: return False return True
def seconds_since_midnight( time_spec ): """ Interprets the argument as a time of day specification. The 'time_spec' can be a number between zero and 24 or a string containing am, pm, and colons (such as "3pm" or "21:30"). If the interpretation fails, an exception is raised. Returns the number of...
def number(value, message_error=None, message_valid=None): """ value : value element DOM. Example : document['id].value message_error : str message message_valid: str message function return tuple """ if isinstance(value, (int, float, complex)): if message_valid: retur...
def trim_common_prefixes(strs, min_len=0): """trim common prefixes""" trimmed = 0 if len(strs) > 1: s1 = min(strs) s2 = max(strs) for i in range(len(s1) - min_len): if s1[i] != s2[i]: break trimmed = i + 1 if trimmed > 0: strs =...
def format_mobileconfig_fix(mobileconfig): """Takes a list of domains and setting from a mobileconfig, and reformats it for the output of the fix section of the guide. """ rulefix = "" for domain, settings in mobileconfig.items(): if domain == "com.apple.ManagedClient.preferences": r...
def convert_booleans(kwargs): """Converts standard true/false/none values to bools and None""" for key, value in kwargs.items(): if not isinstance(value, str): continue if value.upper() == 'TRUE': value = True elif value.upper() == 'FALSE': value = Fal...
def _valid_source_node(node: str) -> bool: """Check if it is valid source node in BEL. :param node: string representing the node :return: boolean checking whether the node is a valid target in BEL """ # Check that it is an abundance if not node.startswith('a'): return False # check ...
def get_process_params(process_args, param_dict): """ Get parameters from a process, if they are in its definition. Arguments: process_args {dict} -- arguments sent by a process {'argument_name': value} e.g. {'data': {'from_node': 'dc_0'}, 'index': 2} param_...
def _FindLatestMinorVersion(debuggees): """Given a list of debuggees, find the one with the highest minor version. Args: debuggees: A list of Debuggee objects. Returns: If all debuggees have the same name, return the one with the highest integer value in its 'minorversion' label. If any member of the...
def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes): """Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max s...
def unique_name(key, name, name_dict, name_max=-1, clean_func=None, sep="."): """ Helper function for storing unique names which may have special characters stripped and restricted to a maximum length. :arg key: unique item this name belongs to, name_dict[key] will be reused when available. ...
def resource_for_link(link, includes, resources=None, locale=None): """Returns the resource that matches the link""" if resources is not None: cache_key = "{0}:{1}:{2}".format( link['sys']['linkType'], link['sys']['id'], locale ) if cache_key in resou...
def i32(x): """Converts a long (for instance 0x80005000L) to a signed 32-bit-int. Python2.4 will convert numbers >= 0x80005000 to large numbers instead of negative ints. This is not what we want for typical win32 constants. Usage: >>> i32(0x80005000L) -2147363168 """ # x...
def validateLabel(value): """Validate label for group/nodeset/pset. """ if 0 == len(value): raise ValueError("Label for boundary condition group/nodeset/pset in mesh not specified.") return value
def color_picker(total_items, current_item, palette): """ pick color for charge states""" if total_items < len(palette): return palette[current_item] if total_items >= len(palette): return palette[current_item % len(palette)]
def escape_csv_formula(value): """ Escapes formulae (strings that start with =) to prevent spreadsheet software vulnerabilities being exploited :param value: the value being added to a CSV cell """ if isinstance(value, str) and value.startswith('='): return "'" + value return value
def _unpack_proportions(values): """List of N-1 ratios from N proportions""" if len(values) == 1: return [] half = len(values) // 2 (num, denom) = (sum(values[half:]), sum(values[:half])) assert num > 0 and denom > 0 ratio = num / denom return ( [ratio] + _unpack_prop...
def _prepare_params(params): """return params as SmashGG friendly query string""" query_string = '' if len(params) == 0: return query_string prefix = '?expand[]=' query_string = prefix + '&expand[]='.join(params) return query_string
def _generateParams(param_dict): """ Will take a dictionary, where *potentially* some values are lists. Will return a list of dictionaries with no lists, where each possible list member combination is included. """ keys = param_dict.keys() list_key = None for key in keys: if isinstan...
def jaccard(seq1, seq2): """ Obtained from: https://github.com/doukremt/distance/blob/master/distance/_simpledists.py on Sept 8 2015 Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where ...
def lowercase(str): """ Function to convert a given string to lowercase Args: str: the string Return: Lowercase str """ return str.lower()
def interpolate(p1, p2, d_param, dist): """ interpolate between points """ alpha = min(max(d_param / dist, 0.), 1.) return (1. - alpha) * p1 + alpha * p2
def sum_square_difference(ceiling): """Compute the difference between the sum of squares and the square of the sum of the natural numbers up to and including the provided ceiling. """ numbers = range(ceiling + 1) sum_squares = sum(map(lambda number: number**2, numbers)) square_sum = sum(numbers...
def make_plural(condition, value): """Stupidly makes value plural (adds s) if condition is True""" return str(value) + "s" if condition else str(value)
def arrange_lyrics(arrangement, song_data): """ Returns the lyrics of a song arranged by the song data. :param arrangement: A list of strings describing the arrangement of the lyrics. We do not do checking in this function, so the type must be correct. :t...
def get_current_row(row_info, join_key_value): """check if key is in the csv""" if join_key_value in row_info: return row_info[join_key_value] return {}
def twos_complement_to_int(val, length=4): """ Two's complement representation to integer. We assume that the number is always negative. 1. Invert all the bits through the number 2. Add one """ invertor = int('1' * length, 2) return -((int(val, 2) ^ invertor) + 1)
def training_folds(fold, k=10): """ Return a tuple of all the training folds. >>> training_folds(7) (0, 1, 2, 3, 4, 5, 6, 8, 9) """ assert fold < k return tuple(num for num in range(10) if num != fold)
def get_csv(csv, type): """ Convert a comma separated string of values to list of given type :param csv: Comma separated string :type csv: str :param type: a type casting function, e.g. float, int, str :type type: function :returns: A list of values of type type :rtype: list[type] ...
def partition_set(elements, relation=None, innerset=False, reflexive=False, transitive=False): """Returns the equivlence classes from `elements`. Given `relation`, we test each element in `elements` against the other elements and form the equivalence classes induced by `relation`. By ...
def cap_match_string(match): """ Attach beginning of line and end of line characters to the given string. Ensures that raw topics like /test do not match other topics containing the same string (e.g. /items/test would result in a regex match at char 7) regex goes through each position in the string ...
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]...
def get_single_pos(chunk_containing_pos): """Return only first pos and it's content.""" pos_char_end_idx = chunk_containing_pos.find(" ") pos = chunk_containing_pos[:pos_char_end_idx] pos_content = chunk_containing_pos[(pos_char_end_idx + 1) :] return pos, pos_content
def contains_any(haystack, needles): """Tests if any needle is a substring of haystack. Args: haystack: a string needles: list of strings Returns: True if any element of needles is a substring of haystack, False otherwise. """ for n in needles: if n in haystack: return True ret...
def format_internal_tas(row): """Concatenate TAS components into a single field for internal use.""" # This formatting should match formatting in dataactcore.models.stagingModels concatTas tas = ''.join([ row['allocation_transfer_agency'] if row['allocation_transfer_agency'] else '000', row[...
def signature_payload(headers, body = None): """Converts a message into a payload to be fed to the signature algorithm. The Checkout API requires every request and response to be signed. The first step in the signature process is to convert the request or response into a payload string. This function ...
def keep_comment(text, min_ascii_fraction=0.75, min_length=1): """ For purposes of vocabulary creation ignore non-ascii documents """ len_total = len(text) if len_total < min_length: return False len_ascii = sum(c.isalpha() for c in text) frac_ascii = float(len_ascii) / float(len_total) ...
def rep1(s): """REGEX: build repeat 1 or more.""" return s + '+'
def rshift(val, n): """ Implements signed right-shift. See: http://stackoverflow.com/a/5833119/15677 """ return (val % 0x100000000) >> n
def checkTrustline(asset :str, issuer:str, available_assets: list) -> bool: """ Check if in the balances of the account an asset like that alredy exists to establish a trustline """ for elem in available_assets: if elem["sponsor"] == asset: return True return False
def verse(bottle): """Sing a verse""" bottle_str = str(bottle) s1 = 's' if bottle > 1 else '' s2 = 's' if bottle != 2 else '' next_bottle = str(bottle - 1) if bottle > 1 else 'No more' return '\n'.join([ f'{bottle_str} bottle{s1} of beer on the wall,', f'{bottle_str} bottle{s1}...
def sort_key(string): """e.g., sort 'INT8' before 'INT16'""" return string.replace("8", "08")
def param_to_string(parameters) -> str: """Convert a list / tuple of parameters returned from IE to a string""" if isinstance(parameters, (list, tuple)): return ', '.join([str(x) for x in parameters]) else: return str(parameters)
def str_to_var_name(verbose_name): """Convert a string to a variable compatible name. Examples: IP Addresses > ip_addresses """ return verbose_name.lower().replace(" ", "_").replace("-", "_")
def rebuild(expr): """ Rebuild a SymPy tree This function recursively calls constructors in the expression tree. This forces canonicalization and removes ugliness introduced by the use of Basic.__new__ """ try: return type(expr)(*list(map(rebuild, expr.args))) except Exception: ...
def spike_height(x, x_old): """ Compute the size of a trending spike (normed - constant units). """ # Sign of trending spike sign = 1.0 if x < x_old: sign = -1.0 # Magnitude mag = abs(x**0.25 - x_old**0.25) # Minnow boost mag *= 1.0 + 2E4/(x + 100.0)**2 return sig...
def abaqus_to_meshio_type(element_type): """Map Abaqus elment type to meshio types. Parameters ---------- element_type : str Abaqus element type (e.g C3D8R) Returns ------- str Meshio element type (e.g. hexahedron) """ # trusss if "T2D2" in element_type or "T3...
def checkio(list): """ sums even-indexes elements and multiply at the last """ soma=0 if len(list)>0: for pos, item in enumerate(list): if pos%2==0: soma=soma+item mult=soma*list[-1] return mult else: return 0
def _determine_levels(index): """Determine the correct levels argument to groupby.""" if isinstance(index, (tuple, list)) and len(index) > 1: return list(range(len(index))) else: return 0
def transform_input_ids(input_ids_0, input_ids_1, tokenizer_func): """ Take the input ids for sequences 0 and 1 (claim and evidence) and a tokenizer function. Apply function to tuples of claim-evidence. Return list of token type ids. """ transformed_ids = list(map( lambda ids_tuple: toke...
def split_with_spaces(sentence): """ Takes string with partial sentence and returns list of words with spaces included. Leading space is attached to first word. Later spaces attached to prior word. """ sentence_list = [] curr_word = "" for c in sentence: if c == " " and ...
def appro(point: tuple, offset: tuple) -> tuple: """Add offset to point. point: tuple(x, y, z) offset: tuple(x, y, z) return: tuple(x, y, z) """ new_point = list() for p, o in zip(point, offset): new_point.append(p + o) return tuple(new_point)
def _tree_to_sequence(c): """ Converts a contraction tree to a contraction path as it has to be returned by path optimizers. A contraction tree can either be an int (=no contraction) or a tuple containing the terms to be contracted. An arbitrary number (>= 1) of terms can be contracted at once. Note...
def truncate_string(string, length=80, title=True): """ Returns a truncated string with '..' at the end if it is longer than the length parameter. If the title param is true a span with the original string as title (for mouse over) is added. """ if string is None: return '' # pragma: no cov...
def add_bit_least_significant(pixel_part, bit): """Change least significant bit of a byte""" pixel_part_binary = bin(pixel_part) last_bit = int(pixel_part_binary[-1]) calculated_last_bit = last_bit & bit return int(pixel_part_binary[:-1]+str(calculated_last_bit), 2)
def fix_tags(tags): """ Handles the tags Checks if the tags are an array, if yes make them a comma-separated string """ if isinstance(tags, list): tags = ",".join(tags) return tags
def dict_to_device(data, device): """Move dict of tensors to device""" out = dict() for k in data.keys(): out[k] = data[k].to(device) return out
def get_list_of_primes_pre_calc(gen): """ Same as get list of primes, but used when prime sieve is already done :param gen: The prime sieve :return: A list containing only the prime numbers """ return [ind for ind, i in enumerate(gen) if i]
def get_line_cf(x0, y0, x1, y1): """ line y = ax + b. returns a,b """ sameX = abs(x1 - x0) < 1e-6 sameY = abs(y1 - y0) < 1e-6 if sameX and sameY: return None, None if sameX: a = None b = x0 elif sameY: a = 0 b = y0 else: a = (y1 - y0...
def get_colour_code(colour): """ This function returns the integer associated with the input string for the ARC problems. """ colour_mapping = {'black':0, 'blue':1, 'red':2, 'green':3, 'yellow':4, ...
def parse_duration(row: str) -> int: """Parses duration value string 'Xhr', 'Ymin' or 'Zsec' and returns (X::Y::Z) as seconds""" import re def filter_digits(s): return "".join(re.findall('\d+', s)) seconds = 0 if 'hr' in row: hr, row = row.split('hr') seconds += int(filter_digit...
def flatten_list_of_lists(l): """ http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ return [item for sublist in l for item in sublist]
def get_api_request_dict(properties): """Build a resource based on a list of properties given as key-value pairs. Leave properties with empty values out of the inserted resource. :param properties: a dict :return: """ resource = {} for p in properties: # Given a key like "snippet.t...
def getRelationsAndRNByCharacter(cname: str, rn: int) -> str: """Return a query to get the relation and Ryu Number of a character. The query retrieves the character's name, as well as the title and Ryu Number of all games that the character appears in with a Ryu Number greater than or equal ...
def xd(t, L, StartTime): """ defines the input to the system """ # Pick your input as one of the xd definitions below # For an unshaped input xd = L * (t >= StartTime) # For a ZV shaped input, designed for 1HZ and no damping # xd = 0.5 * L * (t >= StartTime) + 0.5 * L * (...
def _translate(messages, language_code): """Helper function to assist in handling multiple translations of a message.""" try: the_message = messages[language_code] except KeyError: the_message = messages["en"] return the_message
def get_error(exception=None): """Gets errno from exception or returns one""" return getattr(exception, "errno", 1)
def build_html_component_with_html(html_string): """ This function builds the html string for a component. :param html_string: html_string of the component :param title: Title of the html component :return: html_string """ html = """ <div class="row"> <div class="col-md-12">...
def makepath(dirname, basename): """ Create a full path given the directory name and the base name Args: dirname: path to directory basename: name of file or directory """ return dirname + "/" + basename
def makeSentenceLengths(s): """ use the text in the input string s to create the sentencelength dictionary.""" frequency = 0 length = 0 LoW = s.split() # splits the string into string of each word sl = [] # list of sentence lengths # create loop to iterate through all indices # check ...
def filter_empty_values(mapping_object: dict) -> dict: """Remove entries in the dict object where the value is `None`. >>> foobar = {'username': 'rafaelcaricio', 'team': None} >>> filter_empty_values(foobar) {'username': 'rafaelcaricio'} :param mapping_object: Dict object to be filtered """ ...
def extract_cluster_from_device_id(_id): """Parse cluster from device ID""" if not _id: return None parts = _id.split(".") if len(parts) != 2 or not parts[1]: return None node_details = parts[1].split("_") if len(node_details) != 2 or not node_details[0]: return None ...
def stop(job_id, event, action, resource, _count): """App stop event type""" job_name = '{}:event={}:action={}'.format( resource, event, action ) func_kwargs = dict( job_id=job_id, app_name=resource, ) return job_name, func_kwargs
def Distance_modulus_to_distance(dm, absorption=0.0): """ Returns the distance in kpc for a distance modulus. dm (float): distance modulus. absorption (float): absorption to the source. """ distance = 10.**(((dm-absorption)+5.)/5.) / 1000. return distance
def truncate(x, d): """ Truncate a number to d decimal places Args: x: the number to truncate d: the number of decimal places; -ve to truncate to powers Returns: truncated number """ if d > 0: mult = 10.0 ** d return int(x * mult) / mult else: mult =...
def next_code(value: int, mul: int = 252533, div: int = 33554393) -> int: """ Returns the value of the next code given the value of the current code The first code is `20151125`. After that, each code is generated by taking the previous one, multiplying it by `252533`, and then keeping the remainder...
def color_spot(htmlcolorcode, text=None): """ HTML snippet: span with class 'colorspot' and `htmlcolorcode` as background color """ if text is None: text = htmlcolorcode return u'<span class="colorspot" style="background-color:%s;">&nbsp;&nbsp;&nbsp;</span>&nbsp;%s' % (htmlcolorcode, tex...
def url_Exomol_iso(molecule,isotope_full_name): """return URL for ExoMol for isotope """ url=u"https://exomol.com/data/molecules/"+str(molecule)+"/"+str(isotope_full_name) return url
def slice_1(x): """Given x return slice(x, x).""" return slice(x, x)
def get_typed_features(features, ftype="string", parents=None): """ Recursively get a list of all features of a certain dtype :param features: :param ftype: :param parents: :return: a list of tuples > e.g. ('A', 'B', 'C') for feature example['A']['B']['C'] """ if parents is None: ...
def scrap_middle_name(file): """ Getting folder name from the splitted file_name If the file_name is data_FXVOL_20130612.xml, then the folder name returned will be 'FXVOL' """ if file.startswith('data_') and file.endswith('.xml') and file.count('_') == 2: split_name = file.split('_') ...
def convertWQElementsStatusToWFStatus(elementsStatusSet): """ Defined Workflow status from its WorkQeuueElement status. :param: elementsStatusSet - dictionary of {request_name: set of all WQE status of this request, ...} :returns: request status Here is the mapping between request status and it GQE...
def is_symmetrical(matrix): """Checks if a matrix is symmetrical""" result = True for i in range(8): row = matrix[i*8:(i+1)*8] result = result and (row[0:3] == row[4:]) return result
def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ # raise NotImplementedError possibleSet = set() # turn = player(board) for i in range(len(board)) : for j in range(len(board[i])): if board[i][j] == None : newBo...