content
stringlengths
42
6.51k
def get_args_section_name(layer: int): """Return the specified layer's parser name""" return "__layer{layer}_parser".format(layer=layer)
def line_statements(line): """Break up line into a list of component Fortran statements Note, because this is a simple script, we can cheat on the interpretation of two consecutive quote marks. >>> line_statements('integer :: i, j') ['integer :: i, j'] >>> line_statements('integer :: i; real :: j') ['integer :: i', ' real :: j'] >>> line_statements('integer :: i ! Do not break; here') ['integer :: i ! Do not break; here'] >>> line_statements("write(6, *) 'This is all one statement; y''all;'") ["write(6, *) 'This is all one statement; y''all;'"] >>> line_statements('write(6, *) "This is all one statement; y""all;"') ['write(6, *) "This is all one statement; y""all;"'] >>> line_statements(" ! This is a comment statement; y'all;") [" ! This is a comment statement; y'all;"] >>> line_statements("!! ") ['!! '] """ statements = list() ind_start = 0 ind_end = 0 line_len = len(line) in_single_char = False in_double_char = False while ind_end < line_len: if in_single_char: if line[ind_end] == "'": in_single_char = False # End if (no else, just copy stuff in string) elif in_double_char: if line[ind_end] == '"': in_double_char = False # End if (no else, just copy stuff in string) elif line[ind_end] == "'": in_single_char = True elif line[ind_end] == '"': in_double_char = True elif line[ind_end] == '!': # Commend in non-character context, suck in rest of line ind_end = line_len - 1 elif line[ind_end] == ';': # The whole reason for this routine, the statement separator if ind_end > ind_start: statements.append(line[ind_start:ind_end]) # End if ind_start = ind_end + 1 ind_end = ind_start - 1 # End if (no else, other characters will be copied) ind_end = ind_end + 1 # End while # Cleanup if ind_end > ind_start: statements.append(line[ind_start:ind_end]) # End if return statements
def __collinear(a, b, c, thresh=1e-10): """Checks if 3 2D points are collinear.""" x1,y1 = a; x2,y2 = b; x3,y3 = c return abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)) < thresh
def equals(col, val): """Return a string that has col = val.""" return f"{col} = {val}"
def split(slicable, fraction): """ splits data into test-train set or dev-validation set; does not shuffle. params: slicable - an object that responds to len() and [], works on dataframes fraction - a value between 0 and 1 returns: (x, y) - where x has (1-fraction) percent entries and y has the rest """ partition = int(len(slicable) * (1.0 - fraction)); return( (slicable[:partition], slicable[partition:]) );
def check_start_or_end(dates, today): """ Function: check_start_or_end Description: checks if given date starts or ends today Input: - dates - a list containing start and end date (strings) for an event - today - today's date (string) Output: - 0 if no event starts or ends today - 1 if event starts and ends today - 2 if event starts today and ends on a later date - 3 if event started on a previous date and ends today """ if today == dates[0]: if today == dates[1]: return 1 else: return 2 elif today == dates[1]: return 3 else: return 0
def lines(a, b): """Return lines in both a and b""" linesOfA = set() tokensA = a.split("\n") linesOfA.update(tokensA) linesOfB = set() tokensB = b.split("\n") linesOfB.update(tokensB) # compute intersection i.e. set which contains only lines of both, a and b result = linesOfA.intersection(linesOfB) return result
def parse(line): """ """ ret = [] index, start, end = 0, 0, 0 length = len(line) while True: if line[index] == '"': index = index + 1 end = index + line[index:].find('"') ret.append(line[index:end]) index = end + 1 start = end + 2 elif line[index] == ' ': ret.append(line[start:index]) start = index + 1 index = index + 1 if index >= length: break return ret
def filter_kwargs(kwargs, prefix): """Keep only kwargs starting with `prefix` and strip `prefix` from keys of kept items.""" return {k.replace(prefix, ''): v for k, v in kwargs.items() if k.startswith(prefix)}
def cleanup_code(content: str): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n')
def scoring_key(gender: str, event_code: str) -> str: """Utility function to get the <gender>-<event> scoring key.""" return ("%s-%s" % (gender, event_code)).upper()
def hxltm_hastag_de_csvhxlated(csv_caput: list) -> list: """hxltm_hastag_de_csvhxlated [summary] Make this type of conversion: - 'item__conceptum__codicem' => '#item+conceptum+codicem' - 'item__rem__i_ara__is_arab' => '#item+rem+i_ara+is_arab' - '' => '' Args: csv_caput (list): Array of input items Returns: [list]: """ resultatum = [] for item in csv_caput: if len(item): resultatum.append('#' + item.replace('__', '+').replace('?', '')) else: resultatum.append('') return resultatum
def get_lru(mem_cells, max_size=100): """Least recently used (LRU) cache mechanism. :param mem_cells - sequence of memory cells that should be placed in cache, list, in example, 1, 2, 3, 4, 5, 4, 6]. :param max_size - cache size, generally in memory cells, usually in bytes, in example, 4. :return final cache state, list with memory cells; for given examples of mem_cells and max_size is [5, 6, 3, 4].""" cache = list() age_bits = dict() for order, i in enumerate(mem_cells): # Check out if memory cell is presented in the cache try: cell_index = cache.index(i) except ValueError: # Cell isn't presented in cache. if len(cache) == max_size: # Memory cache is filled up; replace LRU cell # Find LRU cell index lru_index = sorted(age_bits.items(), key=lambda x: x[1])[0][0] # Replace LRU cell with new one. cache[lru_index] = i else: # Add cell in available cache slot. cache.append(i) # Update cell' age bit age_bits[cache.index(i)] = order else: # Cell already presented in cache. Updated age bit for that cell age_bits[cell_index] = order return cache
def handle_object_placement(handle_to_self_field, potential_object, objectType, list=False): """ Helper function to checks to see if we can safely set a given field (handle_to_self_field) to a potential_object by checking whether or not it is an instance of objectType. :param handle_to_self_field: the field the object is to be assigned to :param potential_object: the potential instance of an object :param objectType: the type of object being looked for :param list: whether or not handle_to_self_field should be a list :return: properly referencable object, or False if the object wasn't of the expected type """ if isinstance(potential_object, objectType): if list: handle_to_self_field.append(potential_object) else: handle_to_self_field = potential_object return handle_to_self_field return False
def get_of_colour(shape, target_colours): """ From a shape gets cells of colour. >>> get_of_colour([(0, 1, 2), (1, 1, 2), (3, 3, 5), (9, 1, 5), (5, 1, 8)], [2]) [(0, 1, 2), (1, 1, 2)] >>> get_of_colour([(0, 1, 2), (1, 1, 2), (3, 3, 5), (9, 1, 5), (5, 1, 8)], [2, 5]) [(0, 1, 2), (1, 1, 2), (3, 3, 5), (9, 1, 5)] >>> get_of_colour([(0, 1, 2), (1, 1, 2), (3, 3, 5), (9, 1, 5), (5, 1, 8)], [5, 8]) [(3, 3, 5), (9, 1, 5), (5, 1, 8)] """ out = [] for cell in shape: y, x, colour = cell if colour in target_colours: out.append(cell) return out
def _enleverAlea(text): """Gets rid of the stupid thing that they did, idk what it really is for, but i guess it adds security""" sansalea = [] for i, b in enumerate(text): if i % 2 == 0: sansalea.append(b) return ''.join(sansalea)
def append_write(filename="", text=""): """ writes at the end of a file """ chars = 0 with open(filename, mode="a", encoding="utf-8") as f: chars += f.write(text) f.close() return chars
def string2numList(strn): """Converts a string to a list of integers based on ASCII values""" """origin pickle has bug """ return [ord(chars) for chars in list(strn)]
def strCanFormPalindrome(keyStr): """ determine if any anagram of keyStr can form a palindrome @param keyStr: a string for which to determine if any of its anagram can form a palindrome @return boolean true or false. ASSUMPTION: All characters are lower case. """ charOccurrence = [ 0 for i in range(26)] # initialize a list of size 26, a-z, with occurrence of all characters = 0 for ch in keyStr: charOccurrence[ ord(ch) - 97 ] = keyStr.count(ch) # at i_th position store number of occurrence of char oddOccurrence = 0 # initialize oddOccurrences = 0 for num in charOccurrence: if oddOccurrence > 1: return False if(num % 2 == 1): oddOccurrence += 1 return True
def find_swift_version_copt_value(copts): """Returns the value of the `-swift-version` argument, if found. Args: copts: The list of copts to be scanned. Returns: The value of the `-swift-version` argument, or None if it was not found in the copt list. """ # Note that the argument can occur multiple times, and the last one wins. last_swift_version = None count = len(copts) for i in range(count): copt = copts[i] if copt == "-swift-version" and i + 1 < count: last_swift_version = copts[i + 1] return last_swift_version
def phase_signal_n_times(signal, times, phaser): """Phase signal number of times using phaser function.""" for _ in range(times): signal = phaser(signal) return signal
def find_range(delT): """ tind the range to radar using Stull eq. 8.16 Parameters ---------- delT: float the round-trip travel times (units: micro sec) Returns ------- radar_range: float range from target to radar (units: km) """ ### BEGIN SOLUTION c = 3e8 #speed of light (m/s) delT = delT*(1.e-6) #convert microseconds to s radar_range = c*delT/2 return radar_range*1.e-3
def _k_simplex_neighbor_index_list(d, k): """Given a d-simplex with d being 2 or 3, indexes for neighbor simplexes in the scipy.Delaunay triangulation are provided for all k-simplices with k<d that are part of the d-simplex.""" if d == 2 and k == 1: return 2, 0, 1 elif d == 3 and k == 2: return 3, 2, 1, 0 else: raise ValueError
def get_vpath_list(vpath): """ return a list of the elements of the already canonicalized vpath """ vpath_list = [v for v in vpath.split("/") if len(v) > 0] return vpath_list
def as_undirected(edges): """ Represent a directed edge as undirected. Parameters --------- edges : array-like of Edge array of directed edges (u,v,k) Returns ------- list of tuples """ edge_set = frozenset( [ frozenset((edge[0], edge[1])) for edge in edges]) return [ tuple(edge) for edge in edge_set ]
def is_square_free(n: int) -> bool: """ https://en.wikipedia.org/wiki/Square-free_integer >>> is_square_free(1) True >>> is_square_free(4) False >>> is_square_free(46) True """ from math import sqrt for i in range(2, round(sqrt(n)) + 1): if n % (i**2) == 0: return False return True
def unchained_function(function): """Return true if the function is unchained.""" return function % 2 == 0
def ensure_raw(x): """Return raw tensor from x, unless it already is a raw tensor""" try: return x.raw except AttributeError: return x
def DefineDofDependencyScalar(scalar, variable_list): """ This method injects a dependency into a scalar from a variable list Keyword arguments: scalar -- The scalar to be injected variable_list -- The variable list injected """ return scalar(*variable_list)
def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ i = 0 c = complex(x,y) z = 0.0j for i in range(max_iters): z = z*z + c if (z.real*z.real + z.imag*z.imag) >= 4: return z, i return z, 0
def identify(nick, host): """Return IRC commands which identify the bot to the server.""" fmt = {'nick': nick, 'host': host} return 'NICK %(nick)s\r\nUSER %(nick)s %(host)s 0 :%(nick)s' % fmt
def state2bin(s, num_bins, limits): """ :param s: a state. (possibly multidimensional) ndarray, with dimension d = dimensionality of state space. :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit of each discrete dimension, and row[1] are corresponding upper limits. Returns the bin number (index) corresponding to state s given a discretization num_bins between each column of limits[0] and limits[1]. The return value has same dimensionality as ``s``. \n Note that ``s`` may be continuous. \n \n Examples: \n s = 0, limits = [-1,5], num_bins = 6 => 1 \n s = .001, limits = [-1,5], num_bins = 6 => 1 \n s = .4, limits = [-.5,.5], num_bins = 3 => 2 \n """ if s == limits[1]: return num_bins - 1 width = limits[1] - limits[0] if s > limits[1]: print( "Tools.py: WARNING: ", s, " > ", limits[1], ". Using the chopped value of s" ) print("Ignoring", limits[1] - s) s = limits[1] elif s < limits[0]: print( "Tools.py: WARNING: ", s, " < ", limits[0], ". Using the chopped value of s" ) s = limits[0] return int((s - limits[0]) * num_bins / (width * 1.0))
def rpad(array, n=70): """Right padding.""" current_len = len(array) if current_len > n: return array[: n - 1] extra = n - current_len return array + ([0] * extra)
def _IgnorePaused(instance_info): """Removes information about whether a Xen state is paused from the state. As it turns out, an instance can be reported as paused in almost any condition. Paused instances can be paused, running instances can be paused for scheduling, and any other condition can appear to be paused as a result of races or improbable conditions in Xen's status reporting. As we do not use Xen's pause commands in any way at the time, we can simply ignore the paused field and save ourselves a lot of trouble. Should we ever use the pause commands, several samples would be needed before we could confirm the domain as paused. """ return instance_info.replace('p', '-')
def convert_to_valid_colour_bounds(*arg): """ Purpose: Converts a colour bound of strings/floats to a bound of ints Args: *arg - list of bounds passed into the function Returns: colours - a list of the updated bounds. """ args_num = len(arg) colours = [] for i in range(0, args_num): colours.append((int(float(arg[i][0])), int(float(arg[i][1])), int(float(arg[i][2])))) return colours
def _correlation_matrix(oob_predictions_and_indices): """Computes the correlation between the single estimators of the ensemble model. Args: oob_predictions_and_indices (List[Tuple[np.array, np.array]]): Out-of-bag indices and predictions for each estimator of the ensemble model. Returns: np.array, shape=(n_estimators, n_estimators): Correlation matrix of the estimators of the ensemble model. """ import numpy as np correlation_matrix = [] for i in oob_predictions_and_indices: for j in oob_predictions_and_indices: intersecting_indices = np.intersect1d(i[1], j[1]) intersecting_predictions_i = i[0][intersecting_indices] intersecting_predictions_j = j[0][intersecting_indices] correlation_matrix.append(np.corrcoef(intersecting_predictions_i, intersecting_predictions_j)[0][1]) dimension = len(oob_predictions_and_indices) correlation_matrix = np.reshape(correlation_matrix, (dimension, dimension)).tolist() return correlation_matrix
def calc(kbps, burst_time=1.5): """Calculate Normal and Max Burst values""" bps = kbps * 1000 burst_normal = int(round(bps / 8 * burst_time, 0)) burst_max = 2 * burst_normal return (burst_normal, burst_max)
def res_ene(alpha, beta): """ resonance energy Eres = Er - i*Gamma/2 from alpha and beta assumes a quadratic term: lambda = k**2 + 2*a**2*k + a**4 + b**2 solve for lambda = 0 """ Er = beta**2 - alpha**4 G = 4*alpha**2 * abs(beta) return Er, G
def is_derepFas(title): """ Takes a fasta title line (with or without the initial '>'), and tests to see whether it looks like a usearch dereplicated title line - i.e., does it end "size=n;"? """ title = title.strip(';') try: countclause = title.split(';')[-1] #try to split at ';' try: if countclause.split('=')[0]=='size': #try to split at '='; and if it splits, is the first part "size"? derepped = True else: derepped = False except: derepped = False except: derepped = False return(derepped)
def none_string(vr, def_str, none_str = ""): """Return DEF_STR or NONE_STR depends on weather VR is None or empty string. @param { any } vr : Any variable you want to check. @param { string } def_str : Default string. @param { string } none_str : None string. """ if vr == None or vr == "" or vr == False: return none_str return def_str
def splitMyString(c, str_in): """ Version 2: Using built-in methods Returns a list of strings separated by character 'c' where 'c' is the "splitter" character and 'str_in' is the string. Example Usage: splitMyString('*', 'aaa*sss*fff') returns: ['aaa', 'sss', 'fff'] splitMyString('a', 'abbacfa') will returns: ['', 'bb', 'cf, ''] """ return_val = str_in.split(c) return return_val
def split_identifier(identifier): """Splits string at _ or between lower case and uppercase letters.""" prev_split = 0 parts = [] if '_' in identifier: parts = [s.lower() for s in identifier.split('_')] else: for i in range(len(identifier) - 1): if identifier[i + 1].isupper(): parts.append(identifier[prev_split:i + 1].lower()) prev_split = i + 1 last = identifier[prev_split:] if last: parts.append(last.lower()) return parts
def get_human_readable(size, precision=2): """ Get human readable file size """ suffixes=['B','KiB','MiB','GiB','TiB'] suffixIndex = 0 while size >= 1024: suffixIndex += 1 size = size/1024.0 return "%.*f %s"%(precision,size,suffixes[suffixIndex])
def or_query(*qrys): """create a and query from a given set of querys. :param qrys: the respective queries """ return "(" + "|".join([qry for qry in qrys if qry]) + ")"
def extract_top_level_dict(current_dict): """ Builds a graph dictionary from the passed depth_keys, value pair. Useful for dynamically passing external params :param depth_keys: A list of strings making up the name of a variable. Used to make a graph for that params tree. :param value: Param value :param key_exists: If none then assume new dict, else load existing dict and add new key->value pairs to it. :return: A dictionary graph of the params already added to the graph. """ output_dict = dict() for key in current_dict.keys(): name = key.replace("layer_dict.", "") name = name.replace("layer_dict.", "") name = name.replace("block_dict.", "") name = name.replace("module-", "") top_level = name.split(".")[0] sub_level = ".".join(name.split(".")[1:]) if top_level not in output_dict: if sub_level == "": output_dict[top_level] = current_dict[key] else: output_dict[top_level] = {sub_level: current_dict[key]} else: new_item = {key: value for key, value in output_dict[top_level].items()} new_item[sub_level] = current_dict[key] output_dict[top_level] = new_item # print(current_dict.keys(), output_dict.keys()) return output_dict
def inverse2d(a): """ Returns the matrix inverse of 2x2 matrix "a". :param a: The original 2x2 matrix. :return: Its matrix inverse. """ result = [[0, 0], [0, 0]] det_a = (a[1][1] * a[0][0]) - (a[0][1] * a[1][0]) for a_row in range(len(result)): for a_col in range(len(result[a_row])): result[a_row][a_col] = round(a[a_row][a_col] * (1/det_a), 6) buffer = result[1][1] result[0][1] *= -1 result[1][0] *= -1 result[1][1] = result[0][0] result[0][0] = buffer return result
def format(cmds, sep=" , "): """Format the alias command""" return sep.join(" ".join(cmd) for cmd in cmds)
def maxima(records): """ Calculate the indices of the records in the provided list with the min buy and max sell prices. :param records: List of dictionaries containing price information. :return: A tuple containing the indices for the records with min buy and max sell price in the input list. """ bi = 0 si = 0 bmin = records[0]['buy'] smax = records[0]['sell'] for ii in range(1, len(records)): record = records[ii] if record['buy'] < bmin: bi = ii bmin = record['buy'] if record['sell'] > smax: si = ii smax = record['sell'] return bi, si
def str_to_bytes(value): """Return bytes object from UTF-8 formatted string.""" return bytes(str(value), 'UTF-8')
def make_rename_col_dict(cols, graduating_year): """ Returns dictionary to rename columns respective to each graduating year e.g., 'GPA_2008' --> 'GPA_8th_grade' for students in class of 2012 Returns ---------- dict Parameters ---------- cols : array list of all columns to rename graduating_year : int expected graduating year for a cohort """ d = {col: col for col in cols} mappings = zip(range(8, 13), range(graduating_year-4, graduating_year+1)) for grade, year in mappings: append = str(grade) + 'th_grade' temp = {col: col.replace(str(year), append) for col in cols if str(year) in col} d.update(temp) return d
def get_recipes_from_dict(input_dict: dict) -> dict: """Get recipes from dict Attributes: input_dict (dict): ISO_639_1 language code Returns: recipes (dict): collection of recipes for input language """ if not isinstance(input_dict, dict): raise TypeError("Input is not type dict") recipes = input_dict return recipes
def deep_merge(a, b): """ Deep Merge. If a and b are both lists, all elements in b are added into a. If a and b are both dictionaries, elements in b are recursively added to a. :param a: object items will be merged into :param b: object items will be merged from """ if a is None: return b if b is None: return a if isinstance(a, list): assert isinstance(b, list) a.extend(b) return a if isinstance(a, dict): assert isinstance(b, dict) for (k, v) in b.items(): if k in a: a[k] = deep_merge(a[k], v) else: a[k] = v return a return b
def inverse(a, n): """Find the multiplicative inverse of one number over a given range. Adapted from Wikipedia: Extended Euclidian Algorithm - http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm Returns the multiplicative inverse of a over the finite range n. The result is a number which, when multiplied by a, will return 1 over range n. Keyword arguments: a -- The integer whose multiplicative inverse should be found. n -- A positive integer defining the numeric range to evaluate. """ t = 0 newt = 1 r = n newr = a while newr != 0: quotient = r // newr t, newt = newt, t - quotient * newt r, newr = newr, r - quotient * newr if r > 1: return None if t < 0: t = t + n return t
def get_input_list(input_val, default_val): """ Method to get a list from a comma separated string. :param input_val: Input string or list :param default_val: Default value (generally used for a spider) :return: listified string or default_val if input is not a list or string. """ if isinstance(input_val, list): return input_val elif isinstance(input_val, str): return input_val.split(',') else: return default_val
def normalizeEntities(formattedEntities): """ Normalizes the provider's entity types to match the ones used in our evaluation. Arguments: formattedEntities {List} -- List of recognized named entities and their types. Returns: List -- A copy of the input list with modified entity types. """ fEcopy = formattedEntities for i in range(len(fEcopy)): if fEcopy[i]['type'] == "PERSON": fEcopy[i]['type'] = "Person" elif fEcopy[i]['type'] == "LOCATION": fEcopy[i]['type'] = "Location" elif fEcopy[i]['type'] == "ORGANIZATION": fEcopy[i]['type'] = "Organization" elif fEcopy[i]['type'] == "EVENT": fEcopy[i]['type'] = "Event" elif fEcopy[i]['type'] == "COMMERCIAL_ITEM": fEcopy[i]['type'] = "Product" return fEcopy
def shorten_authors(auth_string, display_auth = 5): """ Shortens article author list. By convention first display_auth-1 authors and the last author are shown. The rest is replaced by '...'. Parameters ---------- auth_string : str Article authors separated by comma. display_auth : int, optional Maximum number of autors to display. The default is 5. Returns ------- str Authors with middle ones substituted by '...'. """ s = auth_string.split(',') s = [x.strip() for x in s] if len(s) >= (display_auth+1): s = s[0:(display_auth-1)] + ["..."] + [s[-1]] return ", ".join(s)
def return_index(character: str) -> int: """ Computes the character index (which needs to fit into the 26 characters list)""" if character.islower(): return ord(character) - ord("a") else: return ord(character) - ord("A")
def parse_name(name): """ Parses a name to return the metadata. Names are formatted like PARAM1=VALUE1__PARAM2=VALUE2__PARAM3 (note PARAM3 has no value) Parameters ---------- name: str Name of the folder. Output ------ out: dict """ entries = name.split('__') out = {} for e in entries: if '=' in e: k, v = e.split('=') else: k = e v = None out[k] = v return out
def convertActionToVelocity(action): """ Converts the action (an integer from 0 to 8) to the changes in velocity in x and y according to the following table dV_x | -1 0 1 ---------------- -1 | 0 1 2 | dVy 0 | 3 4 5 | 1 | 6 7 8 @type action: int A number between 0 and 8. @type: tuple[int] The changes in x velocity and y velocity represented as (dV_x, dV_y) """ if not 0 <= action <= 8: raise ValueError("That's not a valid action!") dV_x = action % 3 - 1 dV_y = action // 3 - 1 return dV_x, dV_y
def latex(input): """Create the latex output version of the input.""" if isinstance(input, float): input = "%.4f" % input return "{" + str(input) + "}" elif isinstance(input, int): return "{" + str(input) + "}" elif isinstance(input, dict): return str(input).replace('{', '').replace('}', '').replace( "'", '').replace('_', '') else: return ""
def dela1(n,a0,a1,x,y): """ Dela1 dela1 dela1 dela Args: n: (array): write your description a0: (array): write your description a1: (array): write your description x: (array): write your description y: (array): write your description """ s=0; for i in range(n): s+=(a0+a1*x[i]-y[i])*x[i] return s/n
def build_complement(dna): """ :param dna: str, a DNA stand :return: str, the complement of dna """ ans = '' for i in range(len(dna)): if dna[i] == 'A': ans += 'T' elif dna[i] == 'T': ans += 'A' elif dna[i] == 'C': ans += 'G' elif dna[i] == 'G': ans += 'C' return ans
def _sorted_nodes(nodes): """Sort nodes on their names.""" return sorted(nodes, key=lambda node: node.name)
def utf8chars(u): """Format an Unicode character in a \\mubyte-friendly style. character ordinal value should be < 0x10000.""" if u < 0x80: return '^^%02x' % u if u < 0x800: return '^^%02x^^%02x' % (0xc0 | (u >> 6), 0x80 | (0x3f & u)) return '^^%02x^^%02x^^%02x' % (0xe0 | (u >> 12), 0x80 | (0x3f & (u >> 6)), 0x80 | (0x3f & u))
def result(player_1, player_2): """Analyserar informationen som funktionen gameplay har genererat. Parameters ---------- x : int representerar spelare 1:s spelprestation y : int representerar spelare 2:s spelprestation Returns ------- str : skriver ut resultatet Examples -------- >>> result(18,12) Os win! """ if player_1 == 0 and player_2 == 0: return "Draw" elif player_1 != 0 and player_1 < player_2: return "Xs win!" elif player_2 != 0 and player_1 > player_2: return "Os win!" elif player_1 == 0 and player_2 > 0: return "Os win!" elif player_1 > 0 and player_2 == 0: return "Xs win!"
def get_rounds(number): """Create a list containing the current and next two round numbers. :param number: int - current round number. :return: list - current round and the two that follow. """ return [number, number + 1, number + 2]
def _get_border(border, size): """Get the border size of the image""" i = 1 while size - border // i <= border // i: i *= 2 return border // i
def to_minus_plus(a): """ translate to -1 +1 """ return 2*(a-0.5)
def hasattr_recursive(item, attr_string): """hasattr for nested attributes Parameters ---------- item : object Any python object with attributes attr_string : string A string of attributes separated by periods (ex: first.second) Note ---- An example would be a module with submodules: `hasattr_recursive(os, 'path.basename')` would return True """ cur_item = item for key in attr_string.split('.'): try: cur_item = getattr(cur_item, key) except AttributeError: return False return True
def _calculate_log2_num_bytes(value: int) -> int: """ Determine the number of bytes required to encode the input value. Artificially limited to max of 8 bytes to be compliant :param value: :return: The calculate the number of bytes """ for log2_num_bytes in range(4): limit = 1 << ((1 << log2_num_bytes) * 8) if value < limit: return log2_num_bytes raise RuntimeError('Unable to calculate the number of bytes required for this value')
def split_stable_id(stable_id): """Split stable id, returning: * Document (root) stable ID * Context polymorphic type * Character offset start, end *relative to document start* Returns tuple of four values. """ split1 = stable_id.split("::") if len(split1) == 2: split2 = split1[1].split(":") if len(split2) == 3: return split1[0], split2[0], int(split2[1]), int(split2[2]) raise ValueError("Malformed stable_id:", stable_id)
def create_kp(args): """ Generate a KP given a tuple of input, edge, output """ source, edge, target = args return { "url": "http://mykp", "infores": "mykp", "maturity": "development", "operations": [ { "subject_category": source, "predicate": f"-{edge}->", "object_category": target, } ], }
def get_class_name(object): """Returns the class name of a given object.""" return object.__class__.__name__
def growth_pos_check(clods, pos): """for checking the position of a growing seed tip Like position_calc but amended for growing seed each time the seed grows there is a cheek for clod collisions :param clods: All the clod objects in the bed :param pos: The proposed position of the seed tip :return: found int 0 for no clod hit or the number of the clod hit """ found = 0 if len(clods) > 0: for x in range(0, len(clods)): if (pos[0]) >= (clods[x].pos[0] - clods[x].radi) and (pos[0]) <= (clods[x].pos[0] + clods[x].radi): # check x only move on if a clash is found if (pos[1]) >= (clods[x].pos[1] - clods[x].radi) and (pos[1]) <= (clods[x].pos[1] + clods[x].radi): # check y #print "pos seedling tip = " + str(pos) #print "hiting clod " + str(x) + " or " + str(clods[x].clod_no) + " at pos = " + str(clods[x].pos) + " rdi=" + str(clods[x].radi) if (pos[2]) >= (clods[x].pos[2] - clods[x].radi) and (pos[2]) <= (clods[x].pos[2] + clods[x].radi): # check z #print "FAIL" found = clods[x].clod_no # the seed grouth is inpeaded! return found
def _get_tags(tags): """Translate the {Name:x, Value:y} crap we get back from aws into a dictionary.""" if tags is None: return {} return {x['Key']: x['Value'] for x in tags}
def encode_list_index(list_index: int) -> bytes: """Encode an index for lists in a key path to bytes.""" return list_index.to_bytes(2, byteorder='big')
def cappa2npsh(cappa, head): """Calculate the npsh required for a given pump's typical number. :param cappa (float): typical number :param head (float): head [m] :return npsh_req (float): neat positive suction head required [m] """ npsh_req = .25 * cappa**(4/3) * head return npsh_req
def vecDistanceSquared(inPtA, inPtB): """calculate the square of the distance between two points""" ddx = inPtA[0] - inPtB[0] ddy = inPtA[1] - inPtB[1] ddz = inPtA[2] - inPtB[2] return ddx*ddx + ddy*ddy + ddz*ddz
def process_index(index, intensity, interaction_symbol): """ Process index to get edge tuple. Disregard edge weight. Args: index (str): index of the edge list dataframe. intensity (float): intensity of the edge. interaction_symbol (str): symbol used to separate node labels. Returns: tuple: a tuple containing edge labels. """ return tuple(index.split(interaction_symbol))
def format_sub_response(sub_response): """ format and return given subscription response into dictionary """ return { "transfer_to": sub_response["transfer_to"], "transactions": sub_response["transactions"], "verifications": sub_response["verifications"] }
def get_solution(story): """ Find the answer to the question: "What are the instances of vowels (excluding y) contained in story? Repeat them in order." :param story: the list of letters to find vowels in :return: a list of vowels """ story.append('#') my_outputs = story + [letter for letter in story if letter in ['a', 'e', 'i', 'o', 'u']] return my_outputs
def pretty_list(the_list, conjunction = "and", none_string = "nothing"): """ Returns a grammatically correct string representing the given list. For example... >>> pretty_list(["John", "Bill", "Stacy"]) "John, Bill, and Stacy" >>> pretty_list(["Bill", "Jorgan"], "or") "Bill or Jorgan" >>> pretty_list([], none_string = "nobody") "nobody" """ the_list = list(the_list) if len(the_list) == 0: return none_string elif len(the_list) == 1: return str(the_list[0]) elif len(the_list) == 2: return str(the_list[0]) + " " + conjunction + " " + str(the_list[1]) else: # Add every item except the last two together seperated by commas result = ", ".join([str(s) for s in the_list[:-2]]) + ", " # Add the last two items, joined together by a command and the given # conjunction result += "%s, %s %s" % \ (str(the_list[-2]), conjunction, str(the_list[-1])) return result
def hasTag(tagName, typeOrPropertyObj): """check up if the as parameter given object has a tag with the given name Keyword arguments: tagName -- name of the tag to look for typeOrPropertyObj -- type or property object to check up """ if not hasattr(typeOrPropertyObj, 'tags'): return False for tag in typeOrPropertyObj.tags: if tag.name == tagName: return True return False
def gcd(a, b): """Euclidean algorith of finding GCD""" if b > a: return gcd(b, a) if a % b == 0: return b return gcd(b, a % b)
def getjflag(job): """Returns flag if job in finished state""" return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0
def get_text(value): """Get text from langstring object.""" return value["langstring"]["#text"]
def field_to_markdown(field): """Genera texto en markdown a partir de los metadatos de un `field`. Args: field (dict): Diccionario con metadatos de un `field`. Returns: str: Texto que describe un `field`. """ if "title" in field: field_title = "**{}**".format(field["title"]) else: raise Exception("Es necesario un `title` para describir un campo.") field_type = " ({})".format(field["type"]) if "type" in field else "" field_desc = ": {}".format( field["description"]) if "description" in field else "" text_template = "{title}{type}{description}" text = text_template.format( title=field_title, type=field_type, description=field_desc) return text
def decode_rle(input): """ Gets a stream of data and decompresses it under a Run-Length Decoding. :param input: The data to be decoded. :return: The decoded string. """ decode_str = "" count = "" for ch in input: # If not numerical if not ch.isdigit(): # Expand it for the decoding decode_str += ch * int(count) count = "" else: # Add it in the counter count += ch return decode_str
def calc_incs(_span): """Calculate the increments needed for timesteps within table :param flot _span: Span of time needed :return: Range needed to complete timesteps :rtype: int """ return int(_span*60/10)
def makeList(roots): """Checks if the given parameter is a list. If not, creates a list with the parameter as an item in it. Parameters ---------- roots : object The parameter to check. Returns ------- list A list containing the parameter. """ if isinstance(roots, (list, tuple)): return roots else: return [roots]
def skip_instance(context, family_name): """ Skip process if instance exists. :param context: (obj) Instance context :param family_name: (str/list) F :return: bool """ if not isinstance(family_name, list): family_name = [family_name] _exists = False for instance in context: if instance.data["family"] in family_name: _exists = True break return _exists
def get_security_args(security, d): """ Returns the parameters in d that are prepended with the string in security. """ ud = {} for key in d: if security + '_' in key: if key.startswith(security + '_'): ukey = key.replace(security + '_', '') ud[ukey] = d[key] return ud
def _getNextCurrControl(curr_control, res_control, max_control): """Compute the next possible control instruction Args: curr_control (list of int|str): last executed control res_control (list of int|str): resolution control max_control (list of int|str): maximum control Returns: int list: the next possible control None: no more possible instruction """ new_current_control = [] for c1, c2, c3 in zip(curr_control, res_control, max_control): new_c1 = int(c1) + int(c2) if new_c1 > int(c3): return else: new_current_control.append(new_c1) return new_current_control
def gql_project_users(fragment): """ Return the GraphQL projectUsers query """ return f''' query($where: ProjectUserWhere!, $first: PageSize!, $skip: Int!) {{ data: projectUsers(where: $where, first: $first, skip: $skip) {{ {fragment} }} }} '''
def is_anagram_0(s1, s2): """ This is my first solution, and it's incorrect because this method checks palindrome, not anagram. """ if s1 is None or s2 is None: return False if len(s1) != len(s2): return False s1_list = list(s1) s2_list = list(s2) for i in range((len(s1_list))): #print("{0}, {1}".format(s1_list[i], s2_list[-i])) if s1_list[i] != s2_list[len(s2_list)-1-i]: return False return True
def get_source_shape(data_shape, value_shape): """Returns the shape of value that will be used to broadcast against data.""" cannot_broadcast = False source_shape = value_shape for i, j in zip(reversed(data_shape), reversed(value_shape)): if j not in (1, i): cannot_broadcast = True for i in range(len(value_shape) - len(data_shape)): source_shape = data_shape if value_shape[i] != 1: cannot_broadcast = True if cannot_broadcast: raise ValueError(f'could not broadcast input array from shape {value_shape} to {data_shape}') return source_shape
def mode_to_mime_type(url_mode): """This extracts the MIME type from a mode CGI parameter: If the CGI parameter is for example: "...&mode= This truncates the beginning of the tsring after "mime:", hence the length of five chars. It sounds hard-coded byt in fact very stable and perfectly matches the need. """ return url_mode[5:]
def prepare_shortlistedFirms(shortlistedFirms): """ Make list with keys key = {identifier_id}_{identifier_scheme}_{lot_id} """ all_keys = set() for firm in shortlistedFirms: key = u"{firm_id}_{firm_scheme}".format(firm_id=firm['identifier']['id'], firm_scheme=firm['identifier']['scheme']) if firm.get('lots'): keys = set([u"{key}_{lot_id}".format(key=key, lot_id=lot['id']) for lot in firm.get('lots')]) else: keys = set([key]) all_keys |= keys return all_keys
def check_num(number_): """ Checks if the number is valid or not if valid then returns the number. """ try: if number_ == 'Q': exit() int(number_) if len(number_) > 4 or len(number_) < 4: print("Please check length of digits you entered: ") number = input() number = check_num(number) return number else: return number_ except ValueError: print("Please Enter Correct four digit number but not all same:") print("or To exit press Q") number_ = input() number = check_num(number_) return number
def PHMS2RA (rast, sep=":"): """ Convert a right ascension string to degrees return RA in degrees rast RA string as "hh:mm:ss.s" sep sympol to use to separate components instead of ":" """ ################################################################ pp = rast.split(sep) if len(pp)>0: hour = int(pp[0]) else: hour = 0 if len(pp)>1: min = int(pp[1]) else: min = 0 if len(pp)>2: ssec = float(pp[2]) else: ssec = 0.0 ra = hour + min/60.0 + ssec/3600.0 return ra*15.0 # end PHMS2RA