content
stringlengths
42
6.51k
def _color_from_bin(bin, n_bins): """ Return color for bin.""" if n_bins <= 0: return 'white' ratio = bin/float(n_bins) if ratio <= 0.2: return '#6fdba5' elif ratio <= 0.3: return 'orange' elif ratio <= 0.5: # return DEFAULT_COLORSCALE[bin] return 'red' return 'red'
def y_pos(y0,v,t): """ Calculates the analytic vertical position in time @ In, y0, float, initial vertical position @ In, v, float, velocity of the projectile @ In, t, float, time of flight @ Out, y_pos, float, vertical position """ return y0 + v*t - 4.9*t*t
def pow_n(narray, n): """ Return array of numbers raised to arbitrary power n each """ return [pow(x, n) for x in narray]
def _merge_args_with_kwargs(args_dict, kwargs_dict): """Merge args with kwargs.""" ret = args_dict.copy() ret.update(kwargs_dict) return ret
def product(numbers): """Multiply together numbers.""" result = 1 for number in numbers: result *= number return result
def _mergedicts(main_dict, changes_dict, applied_changes, initial_path=''): """ Merge the 2 dictionaries. We cannot use update as it changes all the children of an entry """ for key, value in changes_dict.items(): current_path = '{}.{}'.format(initial_path, key) if key in main_dict.keys() and not isinstance(value, dict): if str(main_dict[key]) != str(value): applied_changes[current_path] = value main_dict[key] = value elif key in main_dict.keys(): modified_dict, new_changes = _mergedicts(main_dict[key], value, applied_changes, current_path) main_dict[key] = modified_dict applied_changes.update(new_changes) else: # Entry not found in current main dictionary, so we can update all main_dict[key] = changes_dict[key] applied_changes[current_path] = value return main_dict, applied_changes
def split_paragraphs(string): """ Split `string` into a list of paragraphs. A paragraph is delimited by empty lines, or lines containing only whitespace characters. """ para_list = [] curr_para = [] for line in string.splitlines(keepends=True): if line.strip(): curr_para.append(line) else: para_list.append(''.join(curr_para)) curr_para = [] if curr_para: para_list.append(''.join(curr_para)) return para_list
def key_in_kwargs(key, **kwargs): """ Tests if a key is found in function kwargs | str, kwargs --> bool """ kwarg_dict = {**kwargs} if key in kwarg_dict: return True return False
def remove_dot_segments(s): """Remove dot segments from the string. See also Section 5.2.4 of :rfc:`3986`. """ # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code segments = s.split('/') # Turn the path into a list of segments output = [] # Initialize the variable to use to store output for segment in segments: # '.' is the current directory, so ignore it, it is superfluous if segment == '.': continue # Anything other than '..', should be appended to the output elif segment != '..': output.append(segment) # In this case segment == '..', if we can, we should pop the last # element elif output: output.pop() # If the path starts with '/' and the output is empty or the first string # is non-empty if s.startswith('/') and (not output or output[0]): output.insert(0, '') # If the path starts with '/.' or '/..' ensure we add one more empty # string to add a trailing '/' if s.endswith(('/.', '/..')): output.append('') return '/'.join(output)
def ab_string(S): """ >>> ab_string("aaaaaaabbbbbbbbbb") True >>> ab_string("b") True >>> ab_string("aba") False >>> ab_string("aaba") False """ found_b = False for aa in S: if ( aa == "b"): found_b = True else: # must be a if (found_b): return False return True
def ABCD_eq(b,c,d): """ Basic estimator formula for count in 'A' (signal domain) DEFINITION: A = B x C / D ^ |C | A |----- |D | B 0------> """ return b * c / d
def record_repeated_copies(per_file_stats): """Return a dictionary of length-2 lists. The length-2 list whose key is i corresponds to the files that were copied i times. The first element in each length-2 list is how many bytes those files need, the second element is the list of those file names. >>> x = {'20130924_scamp_update_head.config': {'fromarchive': [1, 83923590]}, 'D00158966_r_c11_r131p01_scampcat.fits': {'toarchive': [1, 72000], 'fromarchive': [1, 72000]}} >>> record_repeated_copies(x) {1: [83923590, ['20130924_scamp_update_head.config']], 2: [144000, ['D00158966_r_c11_r131p01_scampcat.fits']]} """ R = {} for fname in list(per_file_stats.keys()): def safe_dereference(fname, direction, n): if direction in per_file_stats[fname]: return per_file_stats[fname][direction][n] else: return 0 def sum_stat(n): return safe_dereference(fname, 'fromarchive', n) + \ safe_dereference(fname, 'toarchive', n) times_copied = sum_stat(0) bytes_copied = sum_stat(1) if times_copied not in R: R[times_copied] = [0, []] R[times_copied][0] += bytes_copied R[times_copied][1].append(fname) return R
def string_list(argument): """Parse a list of strings. If no argument is given, return an empty list.""" return argument.split() if argument is not None else []
def GetAllowedAndroidApplications(args, messages): """Create list of allowed android applications.""" allowed_applications = [] for application in getattr(args, 'allowed_application', []) or []: android_application = messages.V2AndroidApplication( sha1Fingerprint=application['sha1_fingerprint'], packageName=application['package_name']) allowed_applications.append(android_application) return allowed_applications
def get_ce_endpoint(ce): """ Extracts the endpoint from a computing element *ce* and returns it. Example: .. code-block:: python get_ce_endpoint("grid-ce.physik.rwth-aachen.de:8443/cream-pbs-cms") # -> "grid-ce.physik.rwth-aachen.de:8443" """ return ce.split("/", 1)[0]
def fy(vy0, n): """ Computed by hand """ return n*(2*vy0 + 1 -n) / 2
def format(value, arg): """ Alters default filter "stringformat" to not add the % at the front, so the variable can be placed anywhere in the string. """ try: if value is not None: # return (str(arg)) % value return (str(value)) % arg else: return "" except (ValueError, TypeError): return ""
def getStateLabelsFromLineNo(line_no, n): """ Gets the indeces for labelling rho [i, j] from the line number of an array. Parameters: line_no (int): line number of an array e.g. position of a row in a matrix or column in rho_t n: the number of states in the system Returns: tuple: A tuple of the indeces for the matrix position """ division = int((line_no + 1)/n) # Gives label i remainder = (line_no + 1)%n # Gives label j if (remainder == 0): i = division j = n else: i = (division+1) j = remainder return (i,j)
def _remove_quotes(values): """Remove any quotes from quoted values.""" removed = [] for value in values: if value.startswith('"') and value.endswith('"'): value = value[1:-1] removed.append(value) return removed
def remove_whitespace_make_lowercase(data, exclude): """Removes whitespaces from input data and change input data to lowercase """ for field in data.keys(): if isinstance(data.get(field), str) and field != exclude: data[field] = data.get(field).strip().lower() return data
def convert_headers_str(_str): """ convert headers str to dict """ _list = [i.strip() for i in _str.split('\n')] headers_dict = dict() for i in _list: k, v = i.split(':', 1) headers_dict[k.strip()] = v.strip() return headers_dict
def obtener_nombre_pieza(simbolo): """ (str) -> str >>> obtener_nombre_pieza('p') 'Peon blanco' >>> obtener_nombre_pieza('R') 'Rey Negro' Retorna el nombre de la pieza del ajedrez dado su simbolo :param simbolo: la representacion de la pieza segun el enunciado :return: El nombre y color de la pieza """ tipo = 'Negro' if simbolo.islower(): tipo = 'blanco' retorno = simbolo.lower() if retorno == 'p': return 'Peon ' + tipo elif retorno == 't': return 'Torre ' + tipo elif retorno == 'k': return 'Caballo ' + tipo elif retorno == 'a': return 'Alfil ' + tipo elif retorno == 'q': return 'Reina ' + tipo elif retorno == 'r': return 'Rey ' + tipo else: return 'No es una pieza'
def constraint_reach_back_row(_, stats): """Return true if two cells in the back row are round trip reachable.""" return stats['rtr_back_row'] >= 2
def is_empty(value): """Check whether the given value should be considered "empty".""" return value is None or value == '' or ( isinstance(value, (list, tuple, dict)) and not value)
def repeat(n: int, keyword: str) -> str: """ Build the filter to find articles containing `keyword` at least `n` times. eg. repeat(2, "environment") finds articles containing the word "environment" at least twice. Only single word repetitions are allowed. """ if " " in keyword: raise ValueError("Only single words can be repeated") return f'repeat{str(n)}:"{keyword}"'
def GenerateTransitionMatrix(counts): """ Convert a countr matrix into a probability transition matrix. @param counts: for each key, how many times is the future node seen """ transitions = {} for key in counts: destination_actions = counts[key] # initialize the empty list transitions[key] = [] # how many times was this key seen noccurrences = 0 for action in destination_actions: noccurrences += destination_actions[action] # keep track of cumulative probabilities cumulative_probability = 0.0 for action in destination_actions: cumulative_probability += destination_actions[action] / noccurrences transitions[key].append((cumulative_probability, action)) return transitions
def get_edge_attrs(source_id, targe_id, node_label, edge_label, attrs_var): """Query for retreiving edge's attributes.""" query = ( "MATCH (n:{} {{ id: '{}' }})-[rel:{}]->(m:{} {{ id: '{}' }}) \n".format( node_label, source_id, edge_label, node_label, targe_id) + "RETURN properties(rel) as {}\n".format(attrs_var) ) return query
def division_complejos(num1:list,num2:list) -> list: """ Funcion que realiza la division de dos numeros complejos. :param num1: lista que representa primer numero complejo :param num2: lista que representa segundo numero complejo :return: lista que representa la division de los numeros complejos. """ res = [] res.append(round((num1[0]*num2[0]+num1[1]*num2[1])/(num2[0]**2 + num2[1]**2), 2)) res.append(round((num1[1]*num2[0]-num1[0]*num2[1])/(num2[0]**2 + num2[1]**2), 2)) return res
def get_status_new(code: int) -> str: """Get the torrent status using new status codes""" mapping = { 0: "stopped", 1: "check pending", 2: "checking", 3: "download pending", 4: "downloading", 5: "seed pending", 6: "seeding", } return mapping[code]
def interpolate(x1: float, x2: float, y1: float, y2: float, x: float): """Perform linear interpolation for x between (x1,y1) and (x2,y2) """ return ((y2 - y1) * x + x2 * y1 - x1 * y2) / (x2 - x1) if (x2-x1)>0 else y1 #print(val) #print("---") #return val
def run_length_encoding(seq): """define the run length encoding function""" compressed = [] count = 1 char = seq[0] for i in range(1, len(seq)): if seq[i] == char: count = count + 1 else: compressed.append([char, count]) char = seq[i] count = 1 compressed.append([char, count]) return compressed
def list_keys_to_expand(config, root=True, pre_keys=()): """List the keys corresponding to List or callable.""" if isinstance(config, dict): keys = () for k, v in sorted(config.items()): keys += list_keys_to_expand(v, root=False, pre_keys=pre_keys + (k,)) return keys elif (not root and isinstance(config, list)) or callable(config): assert pre_keys return (pre_keys,) elif root and isinstance(config, list): return tuple( list_keys_to_expand(v, root=False, pre_keys=pre_keys) for v in config) else: return ()
def get_axis_vector(axis_name): """ Convenience. Good for multiplying against a matrix. Args: axis_name (str): 'X' or 'Y' or 'Z' Returns: tuple: vector eg. (1,0,0) for 'X', (0,1,0) for 'Y' and (0,0,1) for 'Z' """ if axis_name == 'X': return (1,0,0) if axis_name == 'Y': return (0,1,0) if axis_name == 'Z': return (0,0,1)
def genus_PARnamePAR_species(tokens): """ Input: Brassica (cabbage) oleracea Output: <taxon genus="Brassica" species="oleracea" sub-prefix="" sub-species=""><sp>Brassica</sp> (cabbage) <sp>oleracea</sp> </taxon> """ (genus, name, species) = tokens[0:3] return f'''<taxon genus="{genus}" species="{species}" sub-prefix="" sub-species=""><sp>{genus}</sp> {name} <sp>{species}</sp></taxon>'''
def query_equalize(query: str) -> str: """removes whitespace/newline deltas from sql""" return ' '.join(query.replace('\n', ' ').split())
def as_list(item): """Make item a list from types which can index, have items, or can pop""" try: item.index return list(item) except AttributeError: try: return list(item.items()) except AttributeError: try: item.pop return list(item) except AttributeError: raise TypeError(f"Cannot make a list from {item!r}")
def mystery_3c(c1: float, c2: float, c3: float) -> int: """Function for question 3c.""" if c1 > 0: if c2 % 3 == 0: if c3 % c2 == 0: return 1 else: return 2 else: if c3 % c2 == 0: return 3 else: return 4 else: if c1 * c2 > 0: return 5 elif c2 * c3 > 0: return 6 elif c3 < 0: return 7 else: return 8
def intersection(st, ave): """Represent an intersection using the Cantor pairing function.""" return (st + ave) * (st + ave + 1) // 2 + ave
def expand_str_list(l, prefix="", suffix=""): """add strings to the beginning or to the end of the string """ return [prefix + x + suffix for x in l]
def region_from_az(az: str = "") -> str: """ :param az: us-east-1b :type az: us-east1 :return: :rtype: """ if not az: return "" parts = az.split("-") ret_val = parts[0] + "-" + parts[1] + "-" + parts[2][:-1] return ret_val
def fibonacci(n): """ Generate a list of fibonacci numbers up to and including n. """ result = [1, 1] if n <= 2: return result[0:n] counter = 2 while True: next_fib = result[counter-2] + result[counter-1] if next_fib > n: break result.append(next_fib) counter += 1 return result
def generate_primes(num1, num2): """Returns a list Prime numbers generated between the given range(num1, num2) """ if num1 > num2: raise Exception( "num1 can't be greater than num2. Specify the correct range.") if num1 == 0 or num2 == 0: raise Exception("Specify the correct range.") primes_generated = [] range_length = num2 - num1 + 1 primes = [True for i in range(range_length)] if num1 == 1: primes[num1] = False inc_value = 2 while inc_value * inc_value <= num2: if primes[inc_value] == True: for i in range(inc_value * inc_value, range_length, inc_value): primes[i] = False inc_value += 1 for prime in range(num1, range_length): if primes[prime]: primes_generated.append(prime) return primes_generated
def parse_int(string, default): """ Parses the string as a int by using a default value if is not possible. """ # If the string is not numeric if not string.isnumeric(): return default # Otherwise, return the string as int else: return int(string)
def jenkins_one_at_a_time_hash(s, size): """http://en.wikipedia.org/wiki/Jenkins_hash_function.""" h = 0 for c in s: h += ord(c) h += (h << 10) h ^= (h >> 6) h += (h << 3); h ^= (h >> 11); h += (h << 15); return h % size;
def isValidOptionSet(distractor,ans): """ Remove erroneously generated option sets Arguments: distractor: the wrong options ans: the correct answer Returns: True/False depending on whether the generated option sets are valid or not """ optionsCpy=distractor.copy() optionsCpy.append(ans) # add ans to the distractor set for i,op1 in enumerate(optionsCpy): for j,op2 in enumerate(optionsCpy): ## check if two of the options are same and just ## case is different then consider the option set ## as invalid if(i!=j): op1=str(op1).lower() op2=str(op2).lower() if(op1==op2): return False if(len(op1.split())==1 and len(op2.split())==1): if(op1[:-1]==op2 or op1==op2[:-1]): return False return True
def extract_source_files(imports, local_upload_path): """ Returns tuples of the imported sources files. """ imported_files = [] for imported_file in imports: if imported_file.startswith(local_upload_path): file_name = imported_file[len(local_upload_path):] file_content = imports[imported_file] imported_files.append((file_name.lstrip('/'), file_content)) return imported_files
def escape(s, quote=None): """ Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. """ s = s.replace("&", "&amp;") # Must be done first! s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") if quote: s = s.replace('"', "&quot;") return s
def _write_a_tikz_coordinate(name, xy, num_fmt): """Write a TikZ coordinate definition. Parameters ---------- name : str TikZ coordinate identified / name. xy : list or tuple of floats (x, y)-coordinates. num_fmt : str Specification of the numbers format, e.g. '.4f'. Returns ------- str TikZ coordinate definition without newline char. """ fmt_str = "{:" + num_fmt + "}" tex_str = "\\coordinate ({:s})".format(name) tex_str += " at (" tex_str += ", ".join(map(fmt_str.format, xy)) tex_str += ");" return tex_str
def from_lane_to_hex_string(lane, w): """Convert a lane value to a string of bytes written in hexadecimal""" lane_hex_b_e = ((b"%%0%dX" % (w // 4)) % lane) # Perform the conversion temp = b'' length = len(lane_hex_b_e) // 2 for i in range(length): offset = (length - i - 1) * 2 temp += lane_hex_b_e[offset:offset + 2] return temp.upper()
def diff_dict(a, b): """Returns a yaml-like textural diff of two dict. It is currently optimized for the .isolated format. """ out = '' for key in set(a) | set(b): va = a.get(key) vb = b.get(key) if va.__class__ != vb.__class__: out += '- %s: %r != %r\n' % (key, va, vb) elif isinstance(va, dict): c = diff_dict(va, vb) if c: out += '- %s:\n%s\n' % ( key, '\n'.join(' ' + l for l in c.splitlines())) elif va != vb: out += '- %s: %s != %s\n' % (key, va, vb) return out.rstrip()
def transform_triples(triples, relation_types, entities): """ Groups a list of relations triples by their relations and returns a suitable data structure. Args: triples (list): List of relation triples as tuples. relation_types (dict): Dictionary with relations as key and the amount of triples with this relation as a key. entities (set): Set of unique entities. Returns: tuple: Dictionary with relation as key and a list of entity tuples as value and an augmented set of unique entities. """ grouped_triples = {key: [] for key in range(len(relation_types.keys()))} for triple in triples: entities.add(triple[0]) entities.add(triple[2]) grouped_triples[triple[1]].append((triple[0], triple[2])) return grouped_triples, entities
def numberIsAWholeNumber(rawNumber): """ Checks if the input is a whole number or not by parsing. Params: rawNumber - A string holding the user's raw input (which may be a number) Returns: Flag representing whether the input is a whole number or not. """ try: int(rawNumber) return True except ValueError: return False
def consistent_det(A, E): """Checks if the attributes(A) is consistent with the examples(E)""" H = {} for e in E: attr_values = tuple(e[attr] for attr in A) if attr_values in H and H[attr_values] != e['GOAL']: return False H[attr_values] = e['GOAL'] return True
def gcd(m, n): """greatest common denominator, with euclid""" if n > m: m, n = n, m r = m % n # get the remainder if r == 0: return n return gcd(n, r)
def factorial(n: int) -> int: """Return the factorial of n. >>> factorial(5) 120 >>> factorial(1) 1 >>> factorial(0) 1 >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> factorial(1.1) Traceback (most recent call last): ... ValueError: n must be exact integer """ if not n >= 0: raise ValueError("n must be >= 0") if int(n) != n: raise ValueError("n must be exact integer") if n + 1 == n: # catch a value like 1e300 raise OverflowError("n too large") result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result
def convert_ipaddress(ipint): """Function for converting a 32 bit integer to a human readable ip address https://geekdeck.wordpress.com/2010/01/19/converting-a-decimal-number-to-ip-address-in-python/ :param ipint: 32 bit int ip address :type ipint: integer :return: human readable ip address """ ipint = int(ipint) ip="" for i in range(4): ip1 = "" for j in range(8): ip1=str(ipint % 2)+ip1 ipint = ipint >> 1 ip = str(int(ip1,2)) + "." + ip ip = ip.strip(".") return ip
def fix_actress_name(name): """Returns the updated name for any actress based on our replacement scheme""" """ if you want to ad any additional ways to fix names, simply add another elif line below elif name == 'name returned from javlibrary' return 'different name' """ if name == 'Kitagawa Eria': return 'Kitagawa Erika' elif name == 'Oshikawa Yuuri': return 'Oshikawa Yuri' return name
def get_trader_fcas_availability_agc_status_condition(params) -> bool: """Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS.""" # Check AGC status if presented with a regulating FCAS offer if params['trade_type'] in ['L5RE', 'R5RE']: # AGC is active='1', AGC is inactive='0' return True if params['agc_status'] == '1' else False # Return True if a presented with a contingency FCAS offer (AGC doesn't need to be enabled) else: return True
def invert_dict(dictionary): """Constructs a new dictionary with inverted mappings so that keys become values and vice versa. If the values of the original dictionary are not unique then only one of the original keys will be included in the new dictionary. """ return dict((value, key) for key, value in dictionary.items())
def to_list(stringlist, unquote=True): """Convert a string representing a list to real list.""" stringlist = stringlist[1:-1] return [ string.strip('"') if unquote else string for string in stringlist.split(",") ]
def _get_pairedvote(vote_id): """ Map vote its to a 0/1 flag for paired voting. """ return 1 if vote_id in [2, 5] else 0
def hello(args) -> int: """Say "hello"! """ print('hello!') return 0
def _make_options(o_dict): """Join options dict back into a valid options string. :param str options_dict: :return: options string for use in connection string :rtype: str """ return ' '.join( ["-c {}={}".format(k, o_dict[k]) for k in sorted(o_dict)])
def getPooledVariance( data ): """return pooled variance from a list of tuples (sample_size, variance).""" t, var = 0, 0 for n, s in data: t += n var += (n-1) * s assert t > len(data), "sample size smaller than samples combined" return var / float(t - len(data))
def index_acl(acl): """Return a ACL as a dictionary indexed by the 'entity' values of the ACL. We represent ACLs as lists of dictionaries, that makes it easy to convert them to JSON objects. When changing them though, we need to make sure there is a single element in the list for each `entity` value, so it is convenient to convert the list to a dictionary (indexed by `entity`) of dictionaries. This function performs that conversion. :param acl:list of dict :return: the ACL indexed by the entity of each entry. :rtype:dict """ # This can be expressed by a comprehension but turns out to be less # readable in that form. indexed = dict() for e in acl: indexed[e["entity"]] = e return indexed
def maptostr(target_list): """Casts a list of python types to a list of strings Args: target_list (list): list containing python types Returns: List containing strings Note: May no longer be needed in Python3 """ return [str(each) for each in target_list]
def options2args(options): """Convert a list of command line options to a args and kwargs """ args = list() kwargs = dict() for a in options: if "=" in a: a = a.split("=", maxsplit=1) kwargs[a[0].lstrip("-")] = a[1] else: args.append(a) return args, kwargs
def taxname( rowhead ): """make g.s taxa names look nicer""" if "s__" in rowhead: return rowhead.split( "." )[1].replace( "s__", "" ).replace( "_", " " ) elif "g__" in rowhead: return rowhead.replace( "g__", "" ).replace( "_", " " ) else: return rowhead
def add(*args): """ Return sum of any number of arrays. """ return [sum(vals) for vals in zip(*args)]
def _add_hf_to_spc_dct(hf0k, spc_dct, spc_name, spc_locs_idx, spc_mod): """ Put a new hf0k in the species dictioanry """ if 'Hfs' not in spc_dct[spc_name]: spc_dct[spc_name]['Hfs'] = {} if spc_locs_idx not in spc_dct[spc_name]['Hfs']: spc_dct[spc_name]['Hfs'][spc_locs_idx] = {} spc_dct[spc_name]['Hfs'][spc_locs_idx][spc_mod] = [hf0k] return spc_dct
def nicefy_props(data): """split keydef into key and modifiers """ from_, to = 'Keypad+', 'KeypadPlus' data = data.replace(from_, to) test = data.split('+') mods = '' if 'Ctrl' in data: mods += 'C' if 'Alt' in data: mods += 'A' if 'Shift' in data: mods += 'S' key = test[-1].replace(to, from_) return key, mods
def get_clip(ct): """ Ientify the number of bases that are soft or hard-clipped prior to a supplementary alignment of a query sequence (i.e., ONT read) using the pysam `cigar_tuple`. We use the number of bases clipped prior to an alignment as a proxy for that alignment's relative order in the original query, and therefore, its relative position in the viral genome. """ MATCH = 0 SOFT_CLIP = 4 HARD_CLIP = 5 clip = '-' # Look at the first CIGAR entry in the CIGAR string. if ct[0][0] in (SOFT_CLIP, HARD_CLIP): clip = ct[0][1] elif ct[0][0] == MATCH: clip = 0 return clip
def get_ordinal(n): """Convert number to its ordinal (e.g., 1 to 1st) Parameters ---------- n : int Number to be converted to ordinal Returns ---------- str the ordinal of n """ return "%d%s" % ( n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4], )
def compute_grid(index, n_files, min_H, min_W, patch_size): """ Compute the coordinate on a grid of indices corresponding to 'index'. The indices are in the form of [i, tl_x, tl_y], where 'i' is the file index. tl_x and tl_y are the top left coordinates of the patched image. To get a patch from any image, tl_y and tl_x must be multiplied by patch_size. Parameters: ---------- index : int Index of the patched dataset Between 0 and 'total_patches'-1 n_files : int Number of image files in the dataset min_H : int Minimum image height among all images min_W : int Minimum image width among all images patch_size : int The size of each squared patch Returns ------- i : int tl_y : int tl_x : int """ # This allows to generate virtually infinite data from bootstrapping the same data index %= (n_files * min_H * min_W) // patch_size**2 # Get the file index among the available file names i = index // ((min_H * min_W) // patch_size**2) index %= (min_H * min_W) // patch_size**2 # Get the patch position in the file tl_y = index // (min_W // patch_size) tl_x = index % (min_W // patch_size) return i, tl_y, tl_x
def collect_codelist_values(path, data, pointer=''): """ Collects ``codelist`` values from JSON Schema. From https://github.com/open-contracting/jscc/blob/main/jscc/testing/checks.py#L674 """ codelists = set() if isinstance(data, list): for index, item in enumerate(data): codelists.update(collect_codelist_values(path, item, pointer='{}/{}'.format(pointer, index))) elif isinstance(data, dict): if 'codelist' in data: codelists.add(data['codelist']) for key, value in data.items(): codelists.update(collect_codelist_values(path, value, pointer='{}/{}'.format(pointer, key))) return codelists
def gardner_anhydrite(Vp, A=2.19, B=0.16): """ Vp in km/sec """ Rho = A*Vp**B return Rho
def _ensure_extension(filename: str, extension: str): """Add the extension if needed.""" if filename.endswith(extension): return filename return filename + extension
def trembling_velocity(im_list): """ The displacement of each frame compared to the previous, this is done by detecting particles, and averaging their velocity at each time point. :param im_list: A consecutive list of frames :return: The average velocity of all the particles at a certain time point. Returns the list of them in x and y direction. """ vx_list = [0.0] vy_list = [0.0] return vx_list, vy_list
def unique(items): """Convert a sorted list of items into a unique list, taking the first occurrence of each duplicate item. Parameters ---------- items : list-like Returns ------- list """ s = set() result = [] for item in items: if not item in s: result.append(item) s.add(item) return result
def money_style(amount: float) -> str: """Return a corresponding bootstrap style to an amount of money :param amount: The amount of money :returns: The bootstrap style """ return 'success' if amount >= 0 else 'danger'
def _byte_to_int(data: bytes) -> int: """ Returns integer value of big endian byte data :param data: :return: Integer value :rtype: int """ return ord(data[0:1]) + (ord(data[1:2]) * 0x100) + (ord(data[2:3]) * 0x10000) + (ord(data[3:4]) * 0x1000000)
def step_edge_distance(num_of_steps, extent, step): """ You have a line segment with a given extent (length). In distance coordinates such as points, 0 is at the beginning of the segment increasing to the extent at the other end. A number line is defined with step increment 0 at the center of the line segment. Steps increase positively toward the extent and negatively toward the 0 coordinate. There is no step increment defined at either boundary (0 or the extent). Let's say the line segment is 100 pt long and we want 5 steps. The zero step will be at coordinate 50. All negative steps will have a value less than 50 and all positive steps will be greater than 50. To make this work we divide the line segment into equally spaced increments by dividing the extent by the total number of steps plus one. With 5 steps then, we get 6 increments each 20 pt wide. There will be three on each side of the zero step. This means the number line will be -2, -1, 0, 1, 2 giving US our five step positions. Given a step number, return the distance coordinate. In our example, step 0 will return 50 pt. Step -1 will return 30 pt and so on. Note that no step will return either the extent or 0 pt since the whole idea is to avoid stepping to the edge of the line segment. :param num_of_steps: Line segment is divided into this number of steps :param extent: Length of line segment :param step: You want the distance of this step from the beginning of the line segment :return: Distance from edge of extent """ # divide the face into equal size steps, 5 anchor positions = 6 steps stem_step_size = extent / (num_of_steps + 1) # add distance from center going away in either direction based on +/- anchor position return extent / 2 + step * stem_step_size
def make_validation_func(func, args=None, expand_args=True): """Create a validation function based on our input""" validation_func = func if args is not None: if expand_args: validation_func = validation_func(*args) else: validation_func = validation_func(args) return validation_func
def build_profile(first, last, **user_info): """Create a dictionary including all information of the users as we know""" profile = {'first_name': first, 'last_name': last} for key, value in user_info.items(): profile[key] = value return profile
def convert_path_list_to_path_map(path_list): """ The same path can have multiple methods. For example: /vcenter/vm can have 'get', 'patch', 'put' Rearrange list into a map/object which is the format expected by swagger-ui key is the path ie. /vcenter/vm/ value is a an object which contains key as method names and value as path objects """ path_dict = {} for path in path_list: x = path_dict.get(path['path']) if x is None: x = {path['method']: path} path_dict[path['path']] = x else: x[path['method']] = path return path_dict
def get_parsed_context(context_arg): """Return context arg stub.""" return {'parsed_context': context_arg}
def get_dim(sheet): """ Get the dimensions of data """ try: col_count = sheet.get_all_records() except: col_count = [[]] row = len(col_count) col = len(col_count[0]) return row, col
def filter_features(features, geom_type='Polygon'): """Filter input GeoJSON-like features to a given geometry type.""" return [f for f in features if f['geometry']['type'] == geom_type]
def create_grid( x: int, y: int, d: int, ) -> list: """Create a grid of digits Parameters ---------- x : int The number of elements in the x-direction y : int The number of elements in the y-direction d : int The digit to create the grid of Returns ------- list The representative grid """ grid = [[d]*(x) for i in range(y)] if y == 1: grid = grid[0] return grid
def avg(new, avg, times): """ :param new: int, the new score :param avg: float, the average of score of the class :param times: int, numbers of the scores of the class :return: float, the new average """ new_avg = (avg * (times - 1) + new) / times return new_avg
def linear_approximation_real(x, x1, y1, x2, y2): """Linear approximation for float arguments""" return (y1 - y2) / (x1 - x2) * x + (y2 * x1 - x2 * y1) / (x1 - x2)
def lemma_from_lexemes(lexemes, separator=' '): """ given a list of dictionaries, each dictionary representing a lexeme, reconstruct the lemma :param list lexemes: list of dictionaries :param string separator: how to join the lexemes if 'breakBefore' = 'false' :rtype: str :return: the lemma """ order_to_lexeme = {} for lexeme in lexemes: order = int(lexeme['order']) order_to_lexeme[order] = lexeme parts = [] for order, lexeme in order_to_lexeme.items(): if lexeme['breakBefore'] == 'true': part = lexeme['name'] + separator else: part = lexeme['name'] parts.append(part) lemma = ''.join(parts) return lemma
def NoTests(path, dent, is_dir): """Filter function that can be passed to FindCFiles in order to remove test sources.""" if is_dir: return dent != 'test' return 'test.' not in dent
def calculate_weighted_average(rated_stars): """ Function that calculates the recipe weighted average rating """ numerator = 0 denominator = 0 for key, value in rated_stars.items(): numerator += int(key) * value denominator += value return numerator/denominator
def print_num(n): """ there must be a package that does this better. oh well""" if n >= 1000000000: return "{}{}".format(round(float(n) / 1000000000, 2), "B") elif n >= 1000000: return "{}{}".format(round(float(n) / 1000000, 2), "M") elif n >= 1000: return "{}{}".format(round(float(n) / 1000, 2), "K") else: return str(n)
def gcd(a, b): """ Find GCD(a, b).""" # GCD(a, b) = GCD(b, a mod b). while (b != 0): # Calculate the remainder. remainder = a % b # Calculate GCD(b, remainder). a = b b = remainder # GCD(a, 0) is a. return a
def get_components(items): """Return a list of pairs of IDs and numbers in items. get_components(list(str)) -> list((str, int)) """ components = [] for item in items: item = item.strip() itemid, _, itemnumstr = item.partition(':') itemid = itemid.strip() itemnumstr = itemnumstr.strip() components.append((itemid, int(itemnumstr))) return components
def fake_call(command, **kwargs): """ Instead of shell.call, call a command whose output equals the command. :param command: Command that will be echoed. :return: Returns a tuple of (process output code, output) """ return (0, str(command))
def cluster_set_name(stem, identity): """Get a setname that specifies the %identity value..""" if identity == 1.0: digits = "10000" else: digits = f"{identity:.4f}"[2:] return f"{stem}-nr-{digits}"
def pypi_prepare_rst(rst): """Add a notice that the rst was auto-generated""" head = """\ .. This file is automatically generated by setup.py from README.md and CHANGELOG.md. """ rst = head.encode('utf-8') + rst return rst