content
stringlengths
42
6.51k
def break_string(string, length): """Attempts to line break a long string intelligently. Arguments: - string -- the string to be broken. - length -- the maximum length of the line. Returns: the line broken string. """ break_list = [] # Go through the string at points of maximum length, until the # string remaining is less than a line. while not (length > len(string)): # Step backwards looking for a space pos = length while string[pos] != " ": pos -= 1 # end while # In the event that there are no spaces along the entire length # of a line... if pos == 0: # Take the string up to the next to the last character in # line, and slice it out of the string. scratch = string[:length-1] string = string[length-1:] # Add a hyphen as the last character, add a newline # character, and append it to the list. scratch += "-\n" break_list.append(scratch) else: # Take the string up to (and including) the space, and slice # it out of the string. scratch = string[:pos+1] string = string[pos+1:] # Add a newline character and append it to the list. scratch += "\n" break_list.append(scratch) # end if # end while # Append the remainder of the string to the list. (If the while # loop never triggered, the whole string will be the only item in # the list.) break_list.append(string) # If the string was broken, reconstitute it now. (If the string is # only one line, this loop doesn't really do anything.) string = "" for line in break_list: string += line # end for return string
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ "*** YOUR CODE HERE ***" sum = 1 while n and k: sum *= n n -= 1 k -= 1 return sum
def firmVolumeFrac(volume, shares, sharesUnit=1000): """ Fraction of shares turned over Returns FLOAT """ # SHROUT in thousands shares_out = shares * sharesUnit return volume / shares_out
def is_valid_version_code(version): """ Checks that the given version code is valid. """ return version is not None and len(version) == 5 and \ int(version[:4]) in range(1990, 2050) and \ version[4] in ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
def symetry(m): """ Symetrisize the values of the matrix on the y axis. """ matrix = [] for row_index in range(len(m)): result_row = [] for value_index in range(len(m[0])): # symerization of matrix1 only by the row_index value (y axis) new_value = (float(m[row_index][value_index]) + float(m[-row_index - 1][value_index])) / 2 result_row.append(new_value) matrix.append(result_row) return matrix
def partition(arr, start, end): """ Helper function that partitions/orders array elements around a selected pivot values Time complexity: O(n) Space complexity: O(1) """ # Select pivot pivot = arr[end] # Initialize partition index as start partition_index = start # Whenever an element smaller/equal to pivot is found, swap it with the partition index element for i in range(start, end): if arr[i] <= pivot: arr[i], arr[partition_index] = arr[partition_index], arr[i] partition_index += 1 # Swap positions of partition index and pivot element arr[partition_index], arr[end] = arr[end], arr[partition_index] # Return index of pivot element return partition_index
def boost_node(n, label, next_label): """Returns code snippet for a leaf/boost node.""" return "%s: return %s;" % (label, n['score'])
def get_headers(header_row): """ Takes array of headers and sets up a dictionary corresponding to columns. """ ans = {} for i in range(len(header_row)): ans[header_row[i]] = i return ans
def _char_hts_as_lists(data): """returns a [[(base, height), ..], ..]""" # data is assumed row-oriented result = [] for d in data: try: d = d.to_dict() except AttributeError: # assume it's just a dict pass if d: d = list(d.items()) else: d = None result.append(d) return result
def to_html(r, g, b): """Convert rgb to html hex code.""" return "#{0:02x}{1:02x}{2:02x}".format(r, g, b)
def html_table_to_excel(table): """ html_table_to_excel(table): Takes an HTML table of data and formats it so that it can be inserted into an Excel Spreadsheet. """ data = {} table = table[table.index('<tr>'):table.index('</table>')] rows = table.strip('\n').split('</tr>')[:-1] for (x, row) in enumerate(rows): columns = row.strip('\n').split('</td>')[:-1] data[x] = {} for (y, col) in enumerate(columns): data[x][y] = col.replace('<tr>', '').replace('<td>', '').strip() return data
def parse_acl(acl_string): """ Parses a standard Swift ACL string into a referrers list and groups list. See :func:`clean_acl` for documentation of the standard Swift ACL format. :param acl_string: The standard Swift ACL string to parse. :returns: A tuple of (referrers, groups) where referrers is a list of referrer designations (without the leading .r:) and groups is a list of groups to allow access. """ referrers = [] groups = [] if acl_string: for value in acl_string.split(','): if value.startswith('.r:'): referrers.append(value[len('.r:'):]) else: groups.append(value) return referrers, groups
def argsort(a): """return index list to get `a` in order, ie ``a[argsort(a)[i]] == sorted(a)[i]`` """ return sorted(range(len(a)), key=a.__getitem__)
def sgn(x): """Return the sign of x.""" return -1 if x < 0 else 1
def condition_3(arg): """ CONDITION 3: It contains a double letter(At least 2 similar letters following each other like b in "abba". :param arg: :return: """ alphabets = "abcdefghijklmnopqrstuvwxyz" for letters in alphabets: sub_string = letters * 2 if sub_string in arg: return True else: return False
def is_even(n: int) -> bool: """ Checks if a number is even(lol). :param n: The number. :return: True if it is even else false. """ return n % 2 == 0
def convert_cpu_limit(cpus: float) -> int: """Convert a provided number of CPUs to the equivalent number of nano CPUs accepted by Docker. Args: cpus: Represents the full number of CPUs. Returns: The equivalent number of nano CPUs. This is the number accepted by Docker. """ return int(cpus * 1e9)
def get_luminance(pixel): """Use the pixels RGB values to calculate its luminance. Parameters ----------- pixel : tuple Returns ------- float Value is between 1.0 and 0.0 """ luminance = 0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2] luminance /= 255 return round(luminance, 2)
def serialize_folder(metadata): """Serializes metadata to a dict with the display name and path of the folder. """ # if path is root if metadata['path'] == '' or metadata['path'] == '/': name = '/ (Full Dropbox)' else: name = 'Dropbox' + metadata['path'] return { 'name': name, 'path': metadata['path'] }
def get_time_shift_pad_offset(time_shift_amount): """Gets time shift paddings and offsets. Arguments: time_shift_amount: time shift in samples, for example -100...100 Returns: Shifting parameters which will be used by shift_in_time() function above """ if time_shift_amount > 0: time_shift_padding = [[time_shift_amount, 0], [0, 0]] time_shift_offset = [0, 0] else: time_shift_padding = [[0, -time_shift_amount], [0, 0]] time_shift_offset = [-time_shift_amount, 0] return time_shift_padding, time_shift_offset
def str_to_bool(value): """ Convert a string representing a boolean to a real boolean """ if str(value).lower() in ["true", "yes", "o"]: return True elif str(value).lower() in ["false", "no", "n"]: return False else: raise ValueError("Not accepted boolean value: {}".format(value))
def get_mesos_disk_status(metrics): """Takes in the mesos metrics and analyzes them, returning the status. :param metrics: mesos metrics dictionary :returns: Tuple of the output array and is_ok bool """ total = metrics['master/disk_total'] used = metrics['master/disk_used'] available = total - used return total, used, available
def only_some_keys(dic, keys): """Return a copy of the dict with only the specified keys present. ``dic`` may be any mapping. The return value is always a Python dict. :: >> only_some_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]) >>> sorted(only_some_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]).items()) [('A', 1), ('C', 3)] """ ret = {} for key in keys: ret[key] = dic[key] # Raises KeyError. return ret
def and_expr(terms): """Creates an SMTLIB and statement formatted string Parameters ---------- terms: A list of float values to include in the expression """ expr = "(and" for term in terms: expr += "\n " + term expr += ")" return expr
def is_seq_qual(seq,ambt,chars='ACGT'): """ Test if sequence is of good quality based on the proportion of ambiguous characters. Arguments: - seq - a string of letters - ambt - ambiguous characters threshold (%) - chars - string of allowed characters """ # no. of sites in the record nsites = len(seq) # no. of ambiguous characters seq_ambc = sum([ i not in chars for i in seq]) # no. of gaps ( if any) ngaps = seq.count('-') # percentage of ambiguous characters try: seq_ambp = seq_ambc/(nsites-ngaps)*100 except ZeroDivisionError: return False # boolean output if seq_ambp > ambt: return False else: return True
def adj_factor(original_size): """Calculates adjustment factor to resize images to 300x200 This function uses the input tuple of original image size to determine image orientation, calculate an adjustment factor, and return a list of new width and height. Args: original_size (tuple): tuple of integers of orig width, height Returns: list: list of integers with newly-sized width, height """ # Determine if vertical or horizontal pic, which way to scale if original_size[0] > original_size[1]: # horizontal adj_factor = 300/original_size[0] else: # vertical or square adj_factor = 200/original_size[1] new_sizes = [] new_sizes.append(round(original_size[0] * adj_factor)) # New width new_sizes.append(round(original_size[1] * adj_factor)) # New height return new_sizes
def two(words): """ :param words: :return: """ new = [] s = len(words) for index in range(s): w = words[index] for next_index in range(index + 1, s): next_w = words[next_index] new.append(frozenset([w, next_w])) return new
def check_conv_type(conv_type, sampling): """Check valid convolution type.""" if not isinstance(conv_type, str): raise TypeError("'conv_type' must be a string.") if not isinstance(sampling, str): raise TypeError("'sampling' must be a string.") conv_type = conv_type.lower() if conv_type not in ['graph','image']: raise ValueError("'conv_type' must be either 'graph' or 'image'.") if conv_type == 'image': sampling = sampling.lower() if sampling != 'equiangular': raise ValueError("conv_type='image' is available only if sampling='equiangular'.") return conv_type
def lat2zone(lat): """ Convert longitude to single-letter UTM zone. """ zone = int(round(lat / 8. + 9.5)) return 'CDEFGHJKLMNPQRSTUVWX'[zone]
def success(message, data=None, code=200): """Return custom success message Args: message(string): message to return to the user data(dict): response data code(number): status code of the response Returns: tuple: custom success REST response """ response = {'status': 'success', 'data': data, 'message': message} return {key: value for key, value in response.items() if value}, code
def succ(n, P): """Return the successor of the permutation P in Sn. If there is no successor, we return None.""" Pn = P[:] + [-1] i = n-2 while Pn[i+1] < Pn[i]: i -= 1 if i == -1: return None j = n-1 while Pn[j] < Pn[i]: j -= 1 Pn[i], Pn[j] = Pn[j], Pn[i] Pn[i+1:n] = Pn[n-1:i:-1] return Pn[:-1]
def make_simple_covariance(xvar, yvar): """ Make simple spherical covariance, as can be passed as upper_left_cov or lower_right_cov. The resulting covariance is elliptical in 2-d and axis-aligned, there is no correlation component :param xvar: Horizontal covariance :param yvar: Vertical covariance :return: A 2x2 covariance matrix, as a list of lists. """ return [ [xvar, 0], [0, yvar] ]
def write_alpha_rarefaction( qza: str, qzv: str, metric: str, phylo: tuple, tree: tuple, meta: str, raref: str ) -> str: """ Parameters ---------- qza qzv metric phylo tree meta raref Returns ------- """ cmd = 'qiime diversity alpha-rarefaction \\\n' if metric in ['faith_pd']: if not phylo[0] or not tree[-1]: return '' if phylo[1]: cmd += '--i-table %s \\\n' % tree[0] else: cmd += '--i-table %s \\\n' % qza cmd += '--i-phylogeny %s \\\n' % tree[1] else: cmd += '--i-table %s \\\n' % qza cmd += '--m-metadata-file %s \\\n' % meta cmd += '--p-metrics %s \\\n' % metric if raref: cmd += '--p-max-depth %s \\\n' % raref.split('raref')[-1] else: cmd += '--p-max-depth 5000 \\\n' cmd += '--o-visualization %s\n\n' % qzv return cmd
def assemble_urls(year, name, subpages=['']): """ Combines team year, name and subpage strings to generate a list of URLs to scrape. """ urls = [] url_base = 'http://' + year + '.igem.org/Team:' + name for s in subpages: urls.append(url_base + s) return urls
def _reindent(string): """Reindent string""" return "\n".join(l.strip() for l in string.strip().split("\n"))
def _float_or_none(value): """ Helper function to convert the passed value to a float and return it, or return None. """ return float(value) if value is not None else None
def traverse(data, path): """Method to traverse dictionary data and return element at given path. """ result = data # need to check path, in case of standalone function use if isinstance(path, str): path = [i.strip() for i in path.split(".")] if isinstance(data, dict): for i in path: result = result.get(i, {}) elif isinstance(data, list): result = [traverse(i, path) for i in data] if result: return result else: return data
def contains(array, element): """[summary]Checks for element in list Arguments: array {[type]} -- [description] element {[type]} -- [description] Returns: [type] -- [description] """ print ("element: " + element) for item in array: print("find " + element + " in " + item) if item.find(element) == -1: continue else: print("element " + element + " found!") return True return False
def append(l: list, obj: object) -> list: """Extend or append to list""" if isinstance(obj, list): l.extend(obj) else: l.append(obj) return l
def flow_text(tokens, *, align_right=70, sep_width=1): """ :param tokens: list or tuple of strings :param align_right: integer, right alignment margin :param sep_width: integer, size of inline separator :return: list of lists of strings flowing the text to the margin """ flowed = [] length = 0 working = [] for i in range(len(tokens)): li = len(tokens[i]) if (len(working) > 0) and ((length + sep_width + li) > align_right): flowed.append(working) length = 0 working = [] if len(working) > 0: length = length + sep_width length = length + li working.append(tokens[i]) if len(working) > 0: flowed.append(working) return flowed
def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 """ return area_of_base * height / 3.0
def ordinal_number(number: int) -> str: """ Source: Gareth @ https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712 >>>ordinal_number(1) '1st' >>>ordinal_number(2) '2nd' >>>ordinal_number(4) '4th' """ return "%d%s" % (number, "tsnrhtdd"[(number // 10 % 10 != 1) * (number % 10 < 4) * number % 10::4])
def filter_keys(model_keys): """ Remove untrainable variables left in pytorch .pth file. Args: model_keys: List of PyTorch model's state_dict keys Returns: A string list containing only the trainable variables from the PyTorch model's state_dict keys """ to_remove = [] for key in model_keys: if ("attn.relative_position_index" in key) or ("attn_mask" in key): to_remove.append(key) for a in to_remove: model_keys.remove(a) return model_keys
def check_sudoku(true_vars): """ Check sudoku. :param true_vars: List of variables that your system assigned as true. Each var should be in the form of integers. :return: """ import math as m s = [] row = [] for i in range(len(true_vars)): row.append(str(int(true_vars[i]) % 10)) if (i + 1) % 9 == 0: s.append(row) row = [] correct = True for i in range(len(s)): for j in range(len(s[0])): for x in range(len(s)): if i != x and s[i][j] == s[x][j]: correct = False print("Repeated value in column:", j) for y in range(len(s[0])): if j != y and s[i][j] == s[i][y]: correct = False print("Repeated value in row:", i) top_left_x = int(i-i%m.sqrt(len(s))) top_left_y = int(j-j%m.sqrt(len(s))) for x in range(top_left_x, top_left_x + int(m.sqrt(len(s)))): for y in range(top_left_y, top_left_y + int(m.sqrt(len(s)))): if i != x and j != y and s[i][j] == s[x][y]: correct = False print("Repeated value in cell:", (top_left_x, top_left_y)) return correct
def truncated_discrete_set(value, values): """ Provides a validator function that returns the value if it is in the discrete set. Otherwise, it returns the smallest value that is larger than the value. :param value: A value to test :param values: A set of values that are valid """ # Force the values to be sorted values = list(values) values.sort() for v in values: if value <= v: return v return values[-1]
def deduplicate_targets(ander_json): """ deduplicate callsite targets, add pruned_num(for address_taken pruned targets of a callsite), ty_num(for type_based pruned targets of a calliste), and num(total targets of a callsite) """ for caller in ander_json.keys(): callsites = ander_json[caller] callsites_num = len(callsites) for i in range(callsites_num): callees = callsites[i]["targets"] if not callees: continue callees_set = set(callees) callsites[i]["targets"] = list(callees_set) callsites[i]["at_num"] = 0 callsites[i]["ty_num"] = 0 callsites[i]["num"] = len(callees_set) return ander_json
def get_catalog_record_access_type(cr): """ Get the type of access_type of a catalog record. :param cr: :return: """ return cr.get('research_dataset', {}).get('access_rights', {}).get('access_type', {}).get('identifier', '')
def min_max(mi, ma, val): """Returns the value inside a min and max range >>> min_max(0, 100, 50) 50 >>> min_max(0, 100, -1) 0 >>> min_max(0, 100, 150) 100 >>> min_max(0, 0, 0) 0 >>> min_max(0, 1, 0) 0 >>> min_max(0, 0, 1) 0 """ return max(mi, min(ma, val))
def mac_normalize(mac): """Retuns the MAC address with only the address, and no special characters. Args: mac (str): A MAC address in string format that matches one of the defined regex patterns. Returns: str: The MAC address with no special characters. Example: >>> from netutils.mac import mac_normalize >>> mac_normalize("aa.bb.cc.dd.ee.ff") 'aabbccddeeff' >>> """ chars = ":-." for char in chars: if char in mac: mac = mac.replace(char, "") return mac
def dapver(versions): """Return DAP version.""" __, dapver = versions return dapver
def parse_tensor_name_with_slicing(in_str): """Parse tensor name, potentially suffixed by slicing string. Args: in_str: (str) Input name of the tensor, potentially followed by a slicing string. E.g.: Without slicing string: "hidden/weights/Variable:0", with slicing string: "hidden/weights/Varaible:0[1, :]" Returns: (str) name of the tensor (str) sliciing string, if any. If no slicing string is present, return "". """ if in_str.count("[") == 1 and in_str.endswith("]"): tensor_name = in_str[:in_str.index("[")] tensor_slicing = in_str[in_str.index("["):] else: tensor_name = in_str tensor_slicing = "" return tensor_name, tensor_slicing
def extract_shelves(reviews): """Sort review data into shelves dictionary. :param reviews: A list of book reviews. """ shelves = {} for book in reviews: for shelf in book['bookshelves']: if shelf not in shelves: shelves[shelf] = [] shelves[shelf].append(book) return shelves
def get_file_name(path: str) -> str: """return the file name without extension given a path Args: path (str): absolute path to the file Returns: (str): file name """ return path.split("/")[-1].split(".")[0]
def flatten_unmatched(rules): """ Converts all nested objects from the provided backup rules into non-nested `field->field-value` dicts. :param rules: rules to flatten :return: the flattened rules """ return list( map( lambda entry: { 'line': entry[0]['line_number'], 'rule': entry[0]['line'].split('#')[0].strip(), 'failure': entry[1], }, rules['unmatched'] ) )
def parse_origin(origin, individual=None): """ The center of the sphere can be given as an Atom, or directly as a list of three floats (x,y,z). If it's an Atom, find it and return the xyz coords. If not, just turn the list into a tuple. Parameters ---------- origin : 3-item list of coordinates, or chimera.Atom genes : gaudi.parse.Settings.genes List of gene-dicts to look for molecules that may contain the referred atom in `origin` Returns ------- Tuple of float The x,y,z coordinates """ if individual and isinstance(origin, tuple) and len(origin) == 2: mol, serial = origin return individual.find_molecule(mol).find_atom(serial).coord().data() elif isinstance(origin, list) and len(origin) == 3: return tuple(origin) else: raise ValueError('Origin {} cannot be parsed'.format(origin))
def alert_data_results(provides, all_app_runs, context): """Setup the view for alert results.""" context['results'] = results = [] for summary, action_results in all_app_runs: for result in action_results: # formatted = format_alert_result(result, True) formatted = { 'param': result.get_param(), 'data': result.get_data() } if not formatted: continue results.append(formatted) return 'alert_data_results.html'
def gcd(m, n): """Compute the GCD of m & n.""" while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n
def get_block_lines(b, mdata): """ Return the number of lines based on the block index in the RAW file. """ line_counts = [1, 1, 1, 1, 1, 4, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0] if b == 5: # for transformer if mdata[0][2] == 0: # two-winding transformer return 4 else: # three-winding transformer return 5 return line_counts[b]
def validate_yes(response=""): """Validates 'yes' user input. Returns `True` if a 'yes' input is detected.""" response = response.replace(" ", "") if response.lower() == "y" or response.lower() == "yes": return True return False
def _is_complex_type(data): """If data is a list or dict return True.""" return isinstance(data, list) or isinstance(data, dict)
def newtonraphson(f, f_, x0, TOL=0.001, NMAX=100): """ Takes a function f, its derivative f_, initial value x0, tolerance value(optional) TOL and max number of iterations(optional) NMAX and returns the root of the equation using the newton-raphson method. """ n=1 while n<=NMAX: x1 = x0 - (f(x0)/f_(x0)) if x1 - x0 < TOL: return x1 else: x0 = x1 return False
def anyfalse(bools): """Returns True iff any elements of iterable `bools` are False >>> anyfalse([True, True]) False >>> anyfalse([True, False, True]) True >>> anyfalse(None) False """ if bools is None: return False for b in bools: if not b: return True return False
def etcd_unpack(obj): """Take a JSON response object (as a dict) from etcd, and transform into a dict without the associated etcd cruft. >>> etcd_unpack({}) {} >>> etcd_unpack({'node': { 'key': 'a', 'value': 'AA'}}) {'a': 'AA'} >>> etcd_unpack({'node': {'nodes': [{'value': 'a', 'key': 'A'}, {'value': 'B', 'key': 'b'}], 'dir': True, 'key': 'pa'}}) {'pa': {'A': 'a', 'b': 'B'}} >>> etcd_unpack( {'node': {'nodes': [{'nodes': [{'value': 'a', 'key': 'A'}], 'dir': True, 'key': 'pa'}], 'dir': True, 'key': 'paa'}} ) {'paa': {'pa': {'A': 'a'}}} >>> etcd_unpack({'node': {'dir': True, 'key': '/resource/flow'}}) {'/resource/flow': {}} """ def _unpack_lst(n): rv = {} for v in n: if 'dir' not in v: rv[v['key']] = v['value'] elif 'nodes' in v: rv[v['key']] = _unpack_lst(v['nodes']) else: rv[v['key']] = {} return rv if 'node' not in obj: return {} cn = obj['node'] # current node pn = None if 'prevNode' in obj: pn = obj['prevNode'] # previous node retVal = {} for n in [cn, pn]: pc = '' if n is cn: pc = 'node' if n is pn: pc = 'prevNode' if n: if not n['key'] in retVal: retVal[n['key']] = {} if 'dir' not in n and 'value' in n: retVal[n['key']][pc] = n['value'] elif not 'dir' and 'value' not in n: retVal[n['key']][pc] = '{}' elif 'nodes' in n: retVal[n['key']][pc] = _unpack_lst(n['nodes']) else: retVal[n['key']][pc] = '{}' return retVal
def _format_compile_plugin_options(options): """Format options into id:value for cmd line.""" return ["%s:%s" % (o.id, o.value) for o in options]
def is_uuid(value): """Check if the passed value is formatted like a UUID.""" sizes = tuple([len(_) for _ in value.split('-')]) return sizes == (8, 4, 4, 4, 12)
def send_keytroke_to_process(process, command): """ Sends a simple command to the process's standard input. Parameters ---------- process : Process The process to control. Returns ------- True if the keystroke was sent successfully, false in case the process handler is invalid. """ if process is None: return False process.stdin.write(command.encode()) process.stdin.flush() return True
def add_css_tag(token, modification): """Returns a token wrapped with the corresponding css tag.""" if modification == 'replace': token = '<span class=\"delta-replace\">' + token + '</span>' elif modification == 'delete': token = '<span class=\"delta-delete\">' + token + '</span>' elif modification == 'append': token = '<span class=\"delta-insert\">' + token + '</span>' elif modification == 'punctuation': token = token[:-1] + '<span class=\"delta-insert\">' + token[-1] + '</span>' elif modification == 'input_delete': token = '<span class=\"delta-input-delete\">' + token + '</span>' elif modification == 'input_replace': token = '<span class=\"delta-input-replace\">' + token + '</span>' return token
def create_name_behavior_id(name: str, team_id: int) -> str: """ Reconstructs fully qualified behavior name from name and team_id :param name: brain name :param team_id: team ID :return: name_behavior_id """ return name + "?team=" + str(team_id)
def perigee(sma, ecc): """Calculate the perigee from SMA and eccentricity""" return sma * (1 - ecc)
def create_radar_template(actual_radar_file_name): """Create radar template file name from actual radar file name Parameters ---------- actual_radar_file_name : string Returns ------- radar_file_name_template : string or empty string """ # Search for the word "tile". If not found, return empty string. # Otherwise, replace with "%%d". # # For example: # radar.2d.tile1.20140531.0500.nc -> radar.2d.tile%d.20140531.0500.nc pos = actual_radar_file_name.find("tile") if pos == -1: return "" out_string = "%stile%%d%s" % (actual_radar_file_name[0:pos], actual_radar_file_name[pos+5:]) return out_string
def fix_angle(ang): """ Normalizes an angle between -180 and 180 degree. """ while ang > 360: ang -= 360 while ang < 0: ang += 360 return ang
def extract(str_value, start_='{', stop_='}'): """Extract a string between two symbols, e.g., parentheses.""" extraction = str_value[str_value.index(start_)+1:str_value.index(stop_)] return extraction
def orientation(p, q, r): """Return positive if p-q-r are clockwise, neg if ccw, zero if colinear.""" return (q[1] - p[1]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[1] - p[1])
def _build_constraint_str(constraint_l=None): """ builds the contraint string expression for different queries. Default is string 'true'. :param list constraint_l: list of constraints to be combined """ if constraint_l: constraint_str = " && ".join(constraint_l) else: constraint_str = "true" return constraint_str
def custom_sort(dictionary, sort_top_labels, sort_bottom_labels): """ Given a dictionary in the form of {'<a_label>': { 'label': '<a_label>' 'value': '<a_value>' }, ... } and two lists (for top and bottom) ['<a_label>', '<c_label>', '<b_label>', ...] return a list of the dictonaries values ordered <all top items found in dictionary, in the given order> <others> <all bottom items found in dictionary, in the given order> """ ret = [] for l in sort_top_labels: if l in dictionary: ret.append(dictionary[l]) for label, facet in dictionary.items(): if label not in sort_top_labels + sort_bottom_labels: ret.append(facet) for l in sort_bottom_labels: if l in dictionary: ret.append(dictionary[l]) return ret
def successors(instr): """Get the list of jump target labels for an instruction. Raises a ValueError if the instruction is not a terminator (jump, branch, or return). """ if instr['op'] == 'jmp': return instr['args'] # Just one destination. elif instr['op'] == 'br': return instr['args'][1:] # The first argument is the condition. elif instr['op'] == 'ret': return [] # No successors to an exit block. else: raise ValueError('{} is not a terminator'.format(instr['op']))
def get_schema_query(owner): """ Oracle query for getting schema information for all tables """ cols = ["TABLE_NAME", "COLUMN_NAME", "DATA_TYPE", "ORDINAL_POSITION"] cols = ",".join(cols) return f"""select {cols} from INFORMATION_SCHEMA.COLUMNS"""
def ndwi(swir, green): """ Compute Vegetation Index from SWIR and GREEN bands NDWI = \\frac { GREEN - SWIR } { GREEN + SWIR } :param swir: Swir band :param green: Green band :return: NDWI """ return (green-swir) / (green+swir)
def _split_inputs(orig_inputs): """Given an input specification containing one or more filesystem paths and URIs separated by '|', return a list of individual inputs. * Skips blank entries * Removes blank space around entries :param orig_inputs: One or more filesystem paths and/or URIs separated by '|' :type orig_inputs: str :return: List of the individual inputs specified in ``orig_inputs`` :rtype: list(str) :Example: >>> _split_inputs('foo|bar') ['foo', 'bar'] """ # (sat 2018-11-19): If we want to support direct list inputs, this is the # place to handle that. return [ii.strip() for ii in orig_inputs.split("|") if ii.strip()]
def to_string(val): """ Converts value to string, with possible additional formatting. """ return '' if val is None else str(val)
def sleep(time): """ Function that returns UR script for sleep() Args: time: float.in s Returns: script: UR script """ return "sleep({})\n".format(time)
def libc_version(AVR_LIBC_VERSION): """ Example: 10604 -> 1.6.4 """ s = str(AVR_LIBC_VERSION) ls = [s[0], s[1:3], s[3:5]] ls = map(int, ls) ls = map(str, ls) return '.'.join(ls)
def get_closest_elements(elems): """Return the two closest elements from a list sorted in ascending order""" e = elems.copy() if len(e) == 1: return e e.sort() diffs = [e[i+1] - e[i] for i in range(len(e)-1)] min_diff_index = diffs.index(min(diffs)) return e[min_diff_index:(min_diff_index+2)]
def model_type(discrete_vars=0, quad_nonzeros=0, quad_constrs=0): """Return the type of the optimization model. The model type is MIP, QCP, QP, or LP. """ mtype = "" if discrete_vars > 0: mtype += "MI" if quad_constrs > 0: mtype += "QC" elif quad_nonzeros > 0: mtype += "Q" if not mtype: return "LP" return mtype + "P"
def format_stat(x, is_neg_log10=False, na_val=0): """ Helper function to format & convert p-values as needed """ if x == 'NA': return float(na_val) else: if is_neg_log10: return 10 ** -float(x) else: return float(x)
def apply_bios_properties_filter(settings, filter_to_be_applied): """Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filtered BIOS settings. """ if not settings or not filter_to_be_applied: return settings return {k: settings[k] for k in filter_to_be_applied if k in settings}
def aviso_tll(tll): """Mensaje de tiempo de llegada.""" return 'El tiempo de llegada del siguiente cliente es: ' + str(tll)
def parse_snmp_return(ret): """Check the return value of snmp operations :param ret: a tuple of (errorIndication, errorStatus, errorIndex, data) returned by pysnmp :return: a tuple of (err, data) err: True if error found, or False if no error found data: a string of error description if error found, or the actual return data of the snmp operation """ err = True (errIndication, errStatus, errIdx, varBinds) = ret if errIndication: data = errIndication elif errStatus: data = "%s at %s" % (errStatus.prettyPrint(), errIdx and varBinds[int(errIdx) - 1] or "?") else: err = False data = varBinds return (err, data)
def kface_accessories_converter(accessories): """ ex) parameters : S1~3,5 return : [S001,S002,S003,S005] """ accessories = accessories.lower() assert 's' == accessories[0] alst = [] accessries = accessories[1:].split(',') for acs in accessries: acs = acs.split('~') if len(acs) == 1: acs = ['S' + acs[0].zfill(3)] else: acs = ['S' + str(a).zfill(3) for a in range(int(acs[0]), int(acs[1])+1)] alst.extend(acs) return alst
def hex_to_ascii(hex_data): """Characteristics values (hex) as input and convert to ascii""" values = [int(x, 16) for x in hex_data.split()] #convert to decimal return "".join(chr(x) for x in values)
def chromosoneCheck(sperm): """ chromosome_check == PEP8 (forced mixedCase by Codewars) Spelling mistake courtesy of Codewars as well """ return "Congratulations! You're going to have a {}.".format( 'son' if 'Y' in sperm else 'daughter' )
def encode_varint(number: int) -> bytes: """Converts `number` into a varint bytes representation. Inverse of `decode_next_varint`. >>> encode_varint(58301).hex().upper() 'BDC703' """ if number < 0: raise ValueError('Argument cannot be negative') if number == 0: return b'\x00' byte_segments = [] while number != 0: byte_segments.append(number & 0x7F) number >>= 7 *alpha, beta = byte_segments return bytes(byte | 0x80 for byte in alpha) + beta.to_bytes(1, 'big')
def getIdentifierScheme(identifier): """Uses string matching on the given identifier string to guess a scheme. """ if identifier is None or len(identifier) <= 0: return None if (identifier.startswith("doi:") | identifier.startswith("http://doi.org/") | identifier.startswith("https://doi.org/") | identifier.startswith("http://dx.doi.org/") | identifier.startswith("https://dx.doi.org/")): scheme = 'doi' elif (identifier.startswith("ark:")): scheme = 'ark' elif (identifier.startswith("http:")): scheme = 'uri' elif (identifier.startswith("https:")): scheme = 'uri' elif (identifier.startswith("urn:")): scheme = 'urn' else: scheme = 'local-resource-identifier-scheme' return scheme
def isValid(ip): """ Checks if ip address is valid or not :param ip: Takes ip as string :return: True if ip valid hence not """ # Check dots and null no_of_dots = ip.count(".") # Counts no of dots in string if ip == '' or no_of_dots != 3: # If ip is blank or dots!=3 returns False return False # Check alphabet for i in ip: if i.isalpha(): return False ip_separated = ip.split(".") # Splits string to list print(len(ip_separated)) # Check if the individual numbers of ip is in the range (0 < ip < 255) for i in range(len(ip_separated)): if int(ip_separated[i]) < 0 or int(ip_separated[i]) > 255: return False return True
def humanize_time(time): """Convert a time from the database's format to a human readable string. Args: time::Int - The time to convert. Returns: _::String - The converted time. """ time_str = '{:04d}'.format(time, ) if time_str[2:] == '25': return '{}:{}'.format(time_str[:2], 15) if time_str[2:] == '50': return '{}:{}'.format(time_str[:2], 30) if time_str[2:] == '75': return '{}:{}'.format(time_str[:2], 45) return '{}:{}'.format(time_str[:2], time_str[2:])
def OpenFileForRead(filename): """ Exception-safe file open for read Args: filename: local file name Returns: file: if open succeeded None: if open failed """ try: f = open(filename, 'r') return f except: return None
def format_simple_string(kv): """This function format a simple key-varlue pair. It also highlight some of the fields in intent. """ sorted_list = sorted(list(kv.items()), key=lambda a: a[0]) arr = [] for el in sorted_list: key = str(el[0]) if key in ['return_time', 'departure_time']: key = """<font style="color: #fff; background-color: red">""" + key + """</font>""" if key == 'airline_preference': key = """<font style="color: #fff; background-color: blue">""" + key + """</font>""" arr.append((key + ':' + str(el[1]))) return ', '.join(arr)
def swap_bytes(value, size): """ Swaps a set of bytes based on size :param value: value to swap :param size: width of value in bytes :return: swapped """ if size == 1: return value if size == 2: return ((value & 0xFF) << 8) | ((value & 0xFF00) >> 8) if size == 4: return ( ((value & 0xFF) << 24) | (((value & 0xFF00) >> 8) << 16) | (((value & 0xFF0000) >> 16) << 8) | ((value & 0xFF000000) >> 24) ) if size == 8: return ( ((value & 0xFF) << 56) | (((value & 0xFF00) >> 8) << 48) | (((value & 0xFF0000) >> 16) << 40) | (((value & 0xFF000000) >> 24) << 32) | (((value & 0xFF00000000) >> 32) << 24) | (((value & 0xFF0000000000) >> 40) << 16) | (((value & 0xFF000000000000) >> 48) << 8) | ((value & 0xFF00000000000000) >> 56) )
def count_disk(disks): """ Count disks with partition table; Return Nr of disks """ nr = 0 for disk in disks: if disks[disk]['partitions']: nr += 1 return nr
def binary(*args): """Converts a char or int to a string containing the equivalent binary notation.""" if isinstance(args[0], str): number = bin(ord(args[0]))[2:] else: number = bin(args[0])[2:] if len(args) == 1: return number st = len(number) - args[1] return number[st:]