content
stringlengths
42
6.51k
def split_long_token(token_string, max_output_token_length): """Splits a token losslessly to some maximum length per component. A long token is split into multiple tokens. For instance, `'bcd'` with `max_output_token_length=2` will become `['bc', 'd']`. No sentinel or other split mark is added at this stage. A token is assumed to be non-empty. Args: token_string: The token. max_output_token_length: Maximum length of an output token. Returns: List of split tokens. Raises: ValueError: if `token` is empty. """ if not token_string: raise ValueError('Expected %r to be non-empty' % token_string) whole_token_length = len(token_string) remainder_length = whole_token_length % max_output_token_length even_parts = list( map( # ...join together... ''.join, zip( # `max_output_token_length` copies of the iterator of # whole_token's characters. zip will draw from the same iterator # and return `max_output_token_length` tuples of characters from # `whole_token`. *[iter(token_string)] * max_output_token_length))) remainder_part = ([token_string[-remainder_length:]] if remainder_length else []) split_token = even_parts + remainder_part assert split_token, ('while wrapping >>%s<< into >%r<' % (token_string, split_token)) assert all([ len(t) <= max_output_token_length for t in split_token ]), ('Got split_token >>>%r<<<, which contains tokens longer than %d.' % (split_token, max_output_token_length)) return split_token
def rotate(string_one, string_two): """Determines if one string is a rotation of the other. Args: string_one: any string of characters. string_two: any string of characters. Returns: True: if string_one is a rotation of string_two False: if string_one is not a rotation of string_two """ if len(string_one) == len(string_two): string_two += string_two if string_one in string_two: return True return False
def to_iterable(var): """ convert things to list treat string as not iterable! """ try: if type(var) is str: raise Exception iter(var) except Exception: return [var] else: return var
def ip_to_mac(ip,pre='14:6E'): """ Generates a mac address from a prefix and and ipv4 address According to http://standards.ieee.org/regauth/oui/oui.txt, 14-6E-0A (hex) PRIVATE """ if not pre.endswith(':'): pre += ':' return pre+':'.join([ '%02X' % int(i) for i in ip.split('.') ])
def _is_on_ray_left(x1, y1, x2, y2, x3, y3, inclusive=False, epsilon=0): """ Return whether x3,y3 is on the left side of the ray x1,y1 -> x2,y2. If inclusive, then the answer is left or on the ray. If otherwise, then the answer is strictly left. """ val = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) if inclusive: return val >= epsilon return val > epsilon
def filenameValidator(text): """ TextEdit validator for filenames. """ return not text or len(set(text) & set('\\/:*?"<>|')) == 0
def space_chars(str) -> str: """Insert spaces between chars for correct pronounciation. """ return " ".join(str)
def get_courses_json_list(all_courses): """ Make json objects of the school's courses and add them to a list. :param all_courses: Course :return: """ courses = [] for course in all_courses: courses.append(course.json()) return courses
def gen_list_of_hp_dict(left_hparams, cur_list = []): """Transform {a: [], b: [], ...} into [{a: xxx, b: xxx}, ..., {}] """ if len(cur_list) == 0: # first level keys = list(left_hparams.keys()) first_key = keys[0] res_list = [] for each_v in left_hparams[first_key]: res_list.append({first_key: each_v}) else: keys = list(left_hparams.keys()) first_key = keys[0] res_list = [] for each_v in left_hparams[first_key]: for each_d in cur_list: each_d[first_key] = each_v res_list.append(each_d.copy()) del left_hparams[first_key] if len(keys) == 1: return res_list else: return gen_list_of_hp_dict(left_hparams, cur_list=res_list)
def create_column_selections(form_dict): """Returns a tag prefix dictionary from a form dictionary. Parameters ---------- form_dict: dict The dictionary returned from a form that contains a column prefix table Returns ------- dict A dictionary whose keys are column numbers (starting with 1) and values are tag prefixes to prepend. """ columns_selections = {} keys = form_dict.keys() for key in keys: if not key.startswith('column') or not key.endswith('use'): continue pieces = key.split('_') name_key = 'column_' + pieces[1] + '_name' if name_key not in form_dict: continue name = form_dict[name_key] if form_dict.get('column_' + pieces[1] + '_category', None) == 'on': columns_selections[name] = True else: columns_selections[name] = False return columns_selections
def get_key_value_list(lines): """ Split lines at the first space. :param lines: lines from trackhub file :return: [(name, value)] where name is before first space and value is after first space """ result = [] for line in lines: line = line.strip() if line: parts = line.split(" ", 1) name = parts[0] value = parts[1] result.append((name, value)) return result
def lookup_frequency(path_length, frequency_lookup): """ Lookup the maximum allowable operating frequency. """ if path_length < 10000: return frequency_lookup['under_10km'] elif 10000 <= path_length < 20000: return frequency_lookup['under_20km'] elif 20000 <= path_length < 45000: return frequency_lookup['under_45km'] else: print('Path_length outside dist range: {}'.format(path_length))
def lower_first(string): """Lower the first character of the string.""" return string[0].lower() + string[1:]
def make_name_valid(name): """"Make a string into a valid Python variable name. Return None if the name contains parentheses.""" if not name or '(' in name or ')' in name: return None import string valid_chars = "_%s%s" % (string.ascii_letters, string.digits) name = str().join([c for c in name if c in valid_chars]) if not name[0].isalpha(): name = 'a' + name return name
def ko_record_splitter(lines): """Splits KO lines into dict of groups keyed by type.""" result = {} curr_label = None curr = [] i = 0 for line in lines: i+= 1 if line[0] != ' ': if curr_label is not None: result[curr_label] = curr fields = line.split(None, 1) # Annoyingly, can have blank REFERENCE lines # Lacking PMID, these still have auth/title info, however... if len(fields) == 1: curr_label = fields[0] curr_line = '' else: curr_label, curr_line = fields curr = [line] else: curr.append(line) if curr: result[curr_label] = curr return result
def fragment_size(l1,l2,o1,o2,coords,g=0): """o1 and o2 indicate the orientations of the two contigs being used 0 means 5' to 3'; 1 means flipped""" x,y = coords[0],coords[1] if (o1,o2) == (0,0): # -------1-----> ----2------> return (y+l1-x+g) if (o1,o2) == (0,1): # -------1-----> <---2------- return (l2-y+l1-x+g) if (o1,o2) == (1,0): # <-------1----- ----2------> return (x+y+g) if (o1,o2) == (1,1): # <-------1-----> <----2------ return (l2-y+x+g)
def swap_and_flatten01(arr): """ swap and then flatten axes 0 and 1 """ if arr is None: return arr s = arr.shape return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
def help_description(s="", compact=False): """ Append and return a brief description of the Sage documentation builder. If 'compact' is ``False``, the function adds a final newline character. """ s += "Build or return information about Sage documentation. " s += "A DOCUMENT and either a FORMAT or a COMMAND are required." if not compact: s += "\n" return s
def is_in_string(line, s): """ Check to see if s appears in a quoted string in line. """ # Simple case, there is not a quoted string in line. if ('"' not in line): return False # There is a quoted string. Pull out all the quoted strings from the line. strs = [] in_str = False curr_str = None for c in line: # Entering string? if ((c == '"') and (not in_str)): curr_str = "" in_str = True continue # Leaving string? if ((c == '"') and in_str): strs.append(curr_str) in_str = False continue # Update current string if in string. if in_str: curr_str += c # We have all the quoted string values. See if s appears in any # of them. for curr_str in strs: if (s in curr_str): return True # s is not in any quoted string. return False
def str2num(s): """Convert string to int or float number. Parameters ---------- s : string String representing a number. Returns ------- Number (int or float) Raises ------ TypeError If `s` is not a string. ValueError If the string does not represent a (float or int) number. """ try: x = float(s) if x.is_integer(): return int(x) else: return x except ValueError: raise ValueError("'s' does not represent a number (int or float)")
def cipher(text, shift, encrypt=True): """ This is a function to encode and decode texts. Each letter is replaced by a letter some fixed number of positions down the alphabet. Parameters (Inputs) ---------- text : str A string of texts to encrypt or decrypt. shift : int An integer representing how many digits of position you want the texts to be shifted. encrypt : boolean A boolean stating the choice encrypt (if = True) or decrypt (if = False). Returns (Output) ------- str A string of the encrypt or decrypt result of the input text. Examples -------- >>> from cipher_rl3167 import cipher_rl3167 >>> text = "I love MDS" >>> shift = 1 >>> cipher_rl3167.cipher(text, shift, encrypt = True) 'J mpwf NET' >>> text = "J mpwf NET" >>> cipher_rl3167.cipher(text, shift, encrypt = False) 'I love MDS' """ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if index == -1: new_text += c else: new_index = index + shift if encrypt == True else index - shift new_index %= len(alphabet) new_text += alphabet[new_index:new_index+1] return new_text
def hash_string(key, bucket_size=1000): """ Generates a hash code given a string. The have is given by the `sum(ord([string])) mod bucket_size` Parameters ---------- key: str Input string to be hashed bucket_size: int Size of the hash table. """ return str(sum([ord(i) for i in (key)]) % bucket_size)
def make_text(rel_links): """ rel_links: list of str with the relevant links for a document. should be what is returned by DocSim.graph[label]. >> make_text(['../../a.md','../b.md']) "link: [a.md](a.md)\nlink: [b.md](b.md)\n" As I have a flat hierarchy, I don't need the full path. """ text = "" for link in rel_links: filename = link.split("/")[-1] text += f"link: [{filename}]({filename})\n" return text
def double_correction(b1, b2, g1, g2, r0): """ Calculates the correction to the double mass profile such that the Einstein radius maintains its original definition. """ def f(a, b, c): return (a ** (c - 1.0)) * (b ** (3.0 - c)) return (b1 ** 2) / (f(b1, r0, g1) + f(b2, b1, g2) - f(b2, r0, g2))
def _isseq(obj): """Return True if obj is a sequence, i.e., is iterable. Will be False if obj is a string or basic data type""" if isinstance(obj, str): return False else: try: iter(obj) except: return False return True
def missingKey(d1, d2): """ Returns a list of name value pairs for all the elements that are present in one dictionary and not the other """ l = [] l += [ {k:d1[k]} for k in d1 if k not in d2 ] l += [ {k:d2[k]} for k in d2 if k not in d1 ] return l
def build_target_list(targets, target_ids, target_file): """ Build a list of the targets to be processed. Parameters ---------- targets: str[] List of the component names of possible targets. target_ids: int[] List of the numerical ids of the subset of targets to be processed. target_file: str Name of the file listing the comonent names of the subset of targets to be processed. Returns ------- List of the numerical ids of the subset of targets to be processed. """ if target_ids: return target_ids if not target_file: return None target_list = [] with open(target_file, 'r') as tgt_file: for line in tgt_file: comp_name = line.strip() if len(comp_name) == 0 or comp_name.startswith('#'): continue found = False for idx, tgt in enumerate(targets): if tgt == comp_name: target_list.append(idx+1) found = True continue if not found: print ("Source {} is not known. Ignoring.".format(comp_name)) # Make sure we don't run everything if a list was supplied but nothing is found if len(target_list) == 0: msg = 'ERROR: None of the targets listed in {} were found.'.format(target_file) print (msg) raise Exception(msg) return target_list
def hex_to_bgr(hex_digits): """ Convert a hexadecimal color value to a 3-tuple of integers """ return tuple(int(s, 16) for s in ( hex_digits[:2], hex_digits[2:4], hex_digits[4:]))
def find_verb_statement(phrase, tense): """ find the verb in a statement Input=sentence, tense and the adverb bound to the verb Output=main verb """ #If phrase is empty if len(phrase) == 0: return [] elif tense == 'present simple' or tense == 'past simple': return [phrase[0]] elif tense == 'present perfect' or tense == 'past perfect' or tense == 'future simple': return [phrase[1]] elif tense == 'present progressive' or tense == 'past progressive': return [phrase[1]] elif tense == 'present passive' or tense == 'past passive': return [phrase[1]] elif tense == 'present conditional': return [phrase[1]] elif tense == 'past conditional' or 'passive conditional': return [phrase[2]] #Default case return []
def calculate_line_number(text): """Calculate line numbers in the text""" return len([line for line in text.split("\n") if line.strip()])
def shortname(name: str) -> str: """ Generate a short name from a full name """ sname = name.split(',') fam = sname[0] names = [] for token in sname[1:]: if '-' in token.strip(): tok = '-'.join([k.strip()[0] + '.' for k in token.split("-")]) else: tok = ' '.join([k.strip()[0] + '.' for k in token.split()]) names.append(tok) return fam + ', ' + ', '.join(names)
def _all_equal(iterable): """True if all values in `iterable` are equal, else False.""" iterator = iter(iterable) first = next(iterator) return all(first == rest for rest in iterator)
def run_add_metadata( input_path: str, output_path: str, meta: str ) -> str: """ Parameters ---------- input_path output_path meta Returns ------- """ cmd = 'biom add-metadata \\\n' cmd += ' -i %s \\\n' % input_path cmd += ' -o %s \\\n' % output_path cmd += ' --sample-metadata-fp %s\n' % meta return cmd
def starting_with(value, prefix): """ Filter to check if value starts with prefix :param value: Input source :type value: str :param prefix: :return: True if matches. False otherwise :rtype: bool """ return str(value).startswith(str(prefix))
def escape(s): """Escape HTML entities in `s`.""" return (s.replace('&', '&amp;'). replace('>', '&gt;'). replace('<', '&lt;'). replace("'", '&#39;'). replace('"', '&#34;'))
def list_numbers(num): """ >>> list_numbers(5) [0, 1, 2, 3, 4, 5] >>> list_numbers(0) [0] """ index = 0 lst = [] while index <= num: lst.append(index) index += 1 return lst
def adjust_learning_rate(optimizer, epoch, lr, schedule, gamma): """Sets the learning rate to the initial LR decayed by schedule""" if epoch in schedule: lr *= gamma print("adjust learning rate to: %.3e" % lr) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr
def _split(length, splits): """ :type length: int the content length of target :type splits: int slice num :rtype: list """ offset = length//splits slices = [[i*offset, i*offset+offset] for i in range(splits)] slices[-1][-1] = length - 1 return slices
def get_default_params(dim: int) -> dict: """ Returns the default parameters of the Self-adaptive Differential Evolution Algorithm (SaDE). :param dim: Size of the problem (or individual). :type dim: int :return: Dict with the default parameters of SaDe :rtype dict """ return {'max_evals': 10000 * dim, 'population_size': 60, 'callback': None, 'individual_size': dim, 'seed': None, 'opts': None, 'terminate_callback': None}
def flatten_list(data): """ Format and return a comma-separated string of list items. :param data: :return: """ return ', '.join(["{0}".format(x) for x in data])
def unpad(seq): """ Remove gap padding. """ return seq.translate(seq.maketrans('', '', '-'))
def is_check(fn): """Check whether a file contains a check.""" if not fn[-3:] == ".py": return False if fn[-11:] == "__init__.py": return False if "inprogress" in fn: return False return True
def insertion_sort(array): """ Sort an input array with insertion sort algorithm The insertion sort algorithm compares an element with the preceeding ordered element to determine whether the two should be swapped. This will continue until the preceeding element is no longer greater than the current element. Best case scenario: O(n) - Best case, if an array is already sorted, this algorithm will inspect every element of the list once to verify it is sorted, no swaps required. Worst case scenario: O(n^2) - Worst case, if an array is reversely sorted, each element must be compared and swapped with every element preceeding it until it reaches the beginning. """ for elem in range(len(array)): curr = elem while curr > 0 and array[curr - 1] > array[curr]: # swap values array[curr - 1], array[curr] = array[curr], array[curr - 1] curr -= 1 return array
def check_host(host): """ Returns SMTP host name and port """ if 'gmail' in host: return 'smtp.gmail.com', 587 elif 'yahoo' in host: return 'smtp.mail.yahoo.com', 465 elif 'hotmail' in host or 'outlook' in host: return 'smtp.live.com', 25
def check_segment_segment_intersection(x1, y1, x2, y2, x3, y3, x4, y4): """ Check if two segments overlap. If they do, return t, the time in the first line's 0 <= t <= 1parameterization at which they intersect """ denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if (denom == 0): return None t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denom if not (0 <= t <= 1): return None u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / denom if not (0 <= u <= 1): return None return t
def path_starts_with(path, prefix): """Test whether the path starts with another path. >>> path_starts_with([1], [1]) True >>> path_starts_with([1, 2], [1]) True >>> path_starts_with([2], [1]) False >>> path_starts_with([1,2,3], [1,2,3]) True >>> path_starts_with([1,2,3], [1,2]) True >>> path_starts_with( ... ('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01', ... '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03', ... '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02', ... '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01'), ... ('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01', ... '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03', ... '\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02')) True """ return path[:len(prefix)] == prefix
def bisection_solve(x, power, epsilon, low, high): """x, epsilon, low, high are floats epsilon > 0 low <= high and there is an ans between low and high s.t. ans**power is within epsilon of x returns ans s.t. ans**power within epsilon of x""" ans = (high + low)/2 while abs(ans**power - x) >= epsilon: if ans**power < x: low = ans else: high = ans ans = (high + low)/2 return ans
def _extract_name(tablename): """Convert a Cordis table name to it's Neo4j Node label""" return tablename.replace('cordis_', '')[:-1].title()
def getid(item): """Return an identifier for the given config item, takes 'id' if it exists or 'messageKey'""" return item['id'] if 'id' in item else item['messageKey']
def wei_to_ether(wei): """Convert wei to ether """ return 1.0 * wei / 10**18
def get_config_string(params, keys=None, units=None): """ return a compact string representation of a measurement """ def compact_number(v): if isinstance(v, float): return "{:.3f}".format(round(v, 3)) else: return str(v) compact_str_items = [] if not keys: keys = params.keys() # first make a list of compact strings for each parameter for k, v in params.items(): if k in keys: unit = "" if isinstance( units, dict ): # check if not None not enough, units could be mocked which causes errors unit = units.get(k, "") compact_str_items.append(k + "=" + compact_number(v) + unit) # and finally join them compact_str = ", ".join(compact_str_items) return compact_str
def select_single_mlvl(mlvl_tensors, batch_id, detach=True): """Extract a multi-scale single image tensor from a multi-scale batch tensor based on batch index. Note: The default value of detach is True, because the proposal gradient needs to be detached during the training of the two-stage model. E.g Cascade Mask R-CNN. Args: mlvl_tensors (list[Tensor]): Batch tensor for all scale levels, each is a 4D-tensor. batch_id (int): Batch index. detach (bool): Whether detach gradient. Default True. Returns: list[Tensor]: Multi-scale single image tensor. """ assert isinstance(mlvl_tensors, (list, tuple)) num_levels = len(mlvl_tensors) if detach: mlvl_tensor_list = [ mlvl_tensors[i][batch_id].detach() for i in range(num_levels) ] else: mlvl_tensor_list = [ mlvl_tensors[i][batch_id] for i in range(num_levels) ] return mlvl_tensor_list
def parsed_name_to_str(parsed_name, fmt_string): """Print dictionary using specified fmt string""" if not fmt_string: fmt_string = ("fullname: {fullname}\n" "version: {version}\n" "ci_id: {ci_id}\n" "art_type: {art_type}\n" "art_ext: {art_ext}\n" "art_id: {art_id}\n" "build_number: {build_number}\n" "timestamp: {timestamp}") return fmt_string.format(**parsed_name)
def get_timestamp(integer): """ Parses integer timestamp from csv into correctly formatted string for xml :param integer: input integer formatted hhmm :return: output string formatted to hh:mm:ss """ string = str(integer) if len(string) == 1: return '00:0{}:00'.format(string) elif len(string) == 2: return '00:{}:00'.format(string) else: minutes = string[-2:] hours = string[:-2] if len(hours) == 1: hours = '0' + hours return '{}:{}:00'.format(hours, minutes)
def is_member_of_group(status: str): """check, whether a given status indicates group-association Args: status (str): status to check Returns: bool: is a person with status in this group? """ possibleStati = ['creator', 'administrator', 'member', 'restricted'] return status in possibleStati
def new_len(s): """ This is our personal length function. s: It is should be iterable and I will tell the length. """ l=0 for i in s: l+=1 return l
def local_maximum(i_list: list)-> list: """ Compute the local maximum of a given list, extreme excluded [5,4,7,2,3,6,1,2] -> [7,6] :param i_list: The source list :return: the list of local maxima """ i=1 _shallow_list = [] while i<len(i_list)-1: if i_list[i-1] <= i_list[i] >= i_list[i+1]: _shallow_list.append(i_list[i]) i+=1 return _shallow_list
def getDegree(relation, start, end, target_bool=True): """ Update the residual in the path given in input Parameters: relation(dict): as key the year and as a value a dict that have as a value the type of relation and as a key the list of all relation start (int): timestamp end (int): timestamp target_bool(boolean): if True out_relation otherwise in_relation Returns: out(int): the degree of the node taken in input node(set): the neighbor of the source """ out = 0 nodes = set() for year in relation: for rel in relation[year]: for edge in relation[year][rel]: if(start <= edge.time <= end): out += edge.weight if target_bool: nodes.add(edge.target) else: nodes.add(edge.source) return out, nodes
def escape_for_bash(str_to_escape): """ This function takes any string and escapes it in a way that bash will interpret it as a single string. Explanation: At the end, in the return statement, the string is put within single quotes. Therefore, the only thing that I have to escape in bash is the single quote character. To do this, I substitute every single quote ' with '"'"' which means: First single quote: exit from the enclosing single quotes Second, third and fourth character: "'" is a single quote character, escaped by double quotes Last single quote: reopen the single quote to continue the string Finally, note that for python I have to enclose the string '"'"' within triple quotes to make it work, getting finally: the complicated string found below. """ escaped_quotes = str_to_escape.replace("'", """'"'"'""") return f"'{escaped_quotes}'"
def qualified(name): """ Test if a name is qualified or not """ return name.startswith("{http") and "}" in name
def get_intel_doc_item(intel_doc: dict) -> dict: """ Gets the relevant fields from a given intel doc. :type intel_doc: ``dict`` :param intel_doc: The intel doc obtained from api call :return: a dictionary containing only the relevant fields. :rtype: ``dict`` """ return { 'ID': intel_doc.get('id'), 'Name': intel_doc.get('name'), 'Type': intel_doc.get('type'), 'Description': intel_doc.get('description'), 'AlertCount': intel_doc.get('alertCount'), 'UnresolvedAlertCount': intel_doc.get('unresolvedAlertCount'), 'CreatedAt': intel_doc.get('createdAt'), 'UpdatedAt': intel_doc.get('updatedAt'), 'LabelIds': intel_doc.get('labelIds')}
def select_extinction(extinction, way="min"): """ For each star sort and select only one extinction value. Parameters ---------- extinction : list of tuples A list returned by the extinction function. way : string A method to select only one extinction value. - "min" - "max" Default value "min". """ stars_indexes = set([star[0] for star in extinction]) extinction_values = [] for star_id in stars_indexes: star_extinction = [] for ext in extinction: if star_id == ext[0]: star_extinction += [ext] if way == "min": extinction_values += [min(star_extinction, key=lambda x: x[-1])] else: extinction_values += [max(star_extinction, key=lambda x: x[-1])] return extinction_values
def utm_getZone(longitude): """docstring for utm_getZone""" return (int(1 + (longitude + 180.0) / 6.0))
def extract_querie_relevance(qrel, query_strings): """Create output file with query id, query string and relevant doc""" print("Extracting {0} queries...".format(len(qrel))) query_relevance = {} for qid in qrel.keys(): relevant_documents = ",".join([docid for docid in qrel[qid]]) query_relevance[qid] = (query_strings[qid], relevant_documents) return query_relevance
def bytes_to_msg(seq, standard="utf-8"): """Decode bytes to text.""" return seq.decode(standard)
def depth_breaks(increment_mm, max_mm): """Return a list of tuples representing depth ranges from a given depth increament (mm) and the maximum depth required""" dd, dmax = increment_mm, max_mm a = [i for i in range(0, dmax, dd)] b = [(a[n], a[n+1]) for n, i in enumerate(a) if i != max(a)] return(b)
def peak_element(arr, n): """ peak element means it is greater than it's neighbour elements corner elements can be also peak elements e.g.1 2 3 --->peak is 3 :param arr: :param n: :return: one line solution return arr.index(max(arr)) """ left_ptr = 1 right_ptr = n - 1 if n >= 2: if arr[0] > arr[left_ptr]: return 0 elif arr[right_ptr] > arr[right_ptr - 1]: return right_ptr else: return 0 right_ptr = n - 2 while left_ptr <= right_ptr: mid = (left_ptr + right_ptr) // 2 if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]: return mid elif arr[mid - 1] > arr[mid]: right_ptr = right_ptr - 1 pass else: left_ptr = left_ptr + 1 pass return -1
def partition(pred, iterable): """Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple of lists with the first list containing the elements on which the predicate indicated False and the second list containing the elements on which the predicate indicated True. Note that, unlike the recipe which returns generators, this version returns lists. """ pos, neg = [], [] pos_append, neg_append = pos.append, neg.append for elem in iterable: if pred(elem): pos_append(elem) else: neg_append(elem) return neg, pos
def _str_eval_indent(eval, act, ctxt) : """Passes through [indent] so that the writer can handle the formatting code.""" return ["[indent]"]
def time_average(a, C, emin, emax, eref=1): """ Average output of events with energies in the range [emin, emax] for a power-law of the form f = C*e**-a to the flare energy distribution, where f is the cumulative frequency of flares with energies greater than e. If the power law is for flare equivalent durations, this amounts to the ratio of energy output in flares versus quiesence. If the power law is for flare energies, it is the time-averaged energy output of flares (units of power). """ return a * C / (1 - a) * eref * ((emax/eref) ** (1 - a) - (emin/eref) ** (1 - a))
def make_hvite_xword_config(model, config_file, target_kind): """ Make a xword config file for hvite """ fh = open(config_file, 'w') fh.write('HPARM: TARGETKIND = %s\n' %target_kind) fh.write('FORCECXTEXP = T\n') fh.write('ALLOWXWRDEXP = T\n') fh.close() return config_file
def get_pr(api, urn, pr_num): """ helper for fetching a pr. necessary because the "mergeable" field does not exist on prs that come back from paginated endpoints, so we must fetch the pr directly """ path = "/repos/{urn}/pulls/{pr}".format(urn=urn, pr=pr_num) pr = api("get", path) return pr
def has_multi_stage_heating(heat_stage): """Determines if the heating stage has multi-stage capability Parameters ---------- cool_stage : str The name of the cooling stage Returns ------- boolean """ if heat_stage == "variable_speed" or heat_stage == "modulating": return True return False
def input_to_list(input_data): """ Helper function for handling input list or str from the user. Args: input_data (list or str): input from the user to handle. Returns: list: returns the original list or list that was split by comma. """ input_data = input_data if input_data else [] return input_data if isinstance(input_data, list) else [s for s in input_data.split(',') if s]
def clean_stockchosen(row): """ INtended for use with DataFrame.apply() Composes a boolean 'stockchosen' column from atomic indicators: - Whether the stock was on the left or right side of the screen - Which button was pressed at selection (left or right) """ if int(row['study']) >= 3: if row['selection'] == 1: # chose option left if row['stockfractallocationtype'] == 'L': # stock was on left # row['stockchosen'] = 1 return 1 elif row['stockfractallocationtype'] == 'R': # stock was on right # row['stockchosen'] = 0 return 0 elif row['selection'] == 0: # chose option right if row['stockfractallocationtype'] == 'R': # stock was on right # row['stockchosen'] = 1 return 1 elif row['stockfractallocationtype'] == 'L': # stock was on left # row['stockchosen'] = 0 return 0 else: if row['stockchosen'] == 'stock': return 1 elif row['stockchosen'] == 'bond': return 0
def cs_gn(A): """Cross section for A(g,n)X averaged over E[.3, 1.] GeV Returns cross section of photoneutron production averaged over the energy range [.3, 1.] GeV, in milibarn units. Arguments: A {int} -- Nucleon number of the target nucleus """ return 0.104 * A**0.81
def add32(buf, value): """Add a littleendian 32bit value to buffer""" buf.append(value & 0xff) value >>= 8 buf.append(value & 0xff) value >>= 8 buf.append(value & 0xff) value >>= 8 buf.append(value & 0xff) return buf
def validate_read_preference_tags(name, value): """Parse readPreferenceTags if passed as a client kwarg. """ if not isinstance(value, list): value = [value] tag_sets = [] for tag_set in value: if tag_set == '': tag_sets.append({}) continue try: tag_sets.append(dict([tag.split(":") for tag in tag_set.split(",")])) except Exception: raise ValueError("%r not a valid " "value for %s" % (tag_set, name)) return tag_sets
def SendWildcardPolicyFile(env, start_response): """Helper function for WSGI applications to send the flash policy-file.""" # The Content-Type doesn't matter, it won't be sent. start_response('200 OK', [('Content-Type', 'text/plain')]) return ('<?xml version="1.0"?>\n' '<!DOCTYPE cross-domain-policy SYSTEM ' '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">\n' '<cross-domain-policy>\n' '<allow-access-from domain="*" to-ports="%s"/>\n' '</cross-domain-policy>\n' % env['SERVER_PORT'],)
def simulate(job): """Run the minimization, equilibration, and production simulations""" command = ( "gmx_d grompp -f em.mdp -c system.gro -p system.top -o em && " "gmx_d mdrun -v -deffnm em -ntmpi 1 -ntomp 1 && " "gmx_d grompp -f eq.mdp -c em.gro -p system.top -o eq && " "gmx_d mdrun -v -deffnm eq -ntmpi 1 -ntomp 1 && " "gmx_d grompp -f prod.mdp -c eq.gro -p system.top -o prod && " "gmx_d mdrun -v -deffnm prod -ntmpi 1 -ntomp 1" ) return command
def _to_bool(string_value): """Convert string to boolean value. Args: string_value: A string. Returns: Boolean. True if string_value is "true", False if string_value is "false". This is case-insensitive. Raises: ValueError: string_value not "true" or "false". """ string_value_low = string_value.lower() if string_value_low not in ('false', 'true'): raise ValueError( 'invalid literal for boolean: %s (must be "true" or "false")' % string_value) return string_value_low == 'true'
def flat(*nums): # Credit to # https://snipnyet.com/adierebel/5b45b79b77da154922550e9a/crop-and-resize-image-with-aspect-ratio-using-pillow/ """Build a tuple of ints from float or integer arguments. Useful because PIL crop and resize require integer points.""" return tuple(int(round(n)) for n in nums)
def snip(content): """ This is a special modifier, that will look for a marker in ``content`` and if found, it will truncate the content at that point. This way the editor can decide where he wants content to be truncated, for use in the various list views. The marker we will look for in the content is {{{snip}}} """ return content[:content.find('{{{snip}}}')] + "..."
def get_amplicon_id(amplicon, column=1, delimiter='_'): """ Get the amplicon ID from an amplicon BED entry """ if len(amplicon) > 0: amplicon_id = amplicon.split(delimiter) return amplicon_id[column] else: return None
def extract_phone_number(num, replacement): """Takes in the phone number as string and replace_with arg as replacement, returns processed phone num or None""" phone_num = "".join(i for i in num if i.isdigit()) if len(phone_num) != 10: phone_num = replacement if replacement == "--blank--" else num return phone_num
def _get_quote_indices(line, escaped): """ Provides the indices of the next two quotes in the given content. :param str line: content to be parsed :param bool escaped: unescapes the string :returns: **tuple** of two ints, indices being -1 if a quote doesn't exist """ indices, quote_index = [], -1 for _ in range(2): quote_index = line.find('"', quote_index + 1) # if we have escapes then we need to skip any r'\"' entries if escaped: # skip check if index is -1 (no match) or 0 (first character) while quote_index >= 1 and line[quote_index - 1] == '\\': quote_index = line.find('"', quote_index + 1) indices.append(quote_index) return tuple(indices)
def html_escape( s ): """ """ s = s.replace( '&', '&amp' ) s = s.replace( '<', '&lt' ) s = s.replace( '>', '&gt' ) return s
def gen_unemployment_rate_change(shortened_dv_list): """Create variables for the change in the unemployment rate for the current and previous months.""" unemployment_rate_change = round(shortened_dv_list[23] - shortened_dv_list[22], 1) prev_unemployment_rate_change = round(shortened_dv_list[22] - shortened_dv_list[21], 1) return unemployment_rate_change, prev_unemployment_rate_change
def gcd(a: int, b: int) -> int: """ Calculates the greatest common divisor of a and b :param a: :param b: :return: """ while True: quotient, remains = divmod(a, b) if remains == 0: return b # updating remains a = b b = remains
def pretty_size_print(num_bytes): """ Output number of bytes in a human readable format Parameters ---------- num_bytes: int number of bytes to convert returns ------- output: str string representation of the size with appropriate unit scale """ if num_bytes is None: return KiB = 1024 MiB = KiB * KiB GiB = KiB * MiB TiB = KiB * GiB PiB = KiB * TiB EiB = KiB * PiB ZiB = KiB * EiB YiB = KiB * ZiB if num_bytes > YiB: output = "%.3g YB" % (num_bytes / YiB) elif num_bytes > ZiB: output = "%.3g ZB" % (num_bytes / ZiB) elif num_bytes > EiB: output = "%.3g EB" % (num_bytes / EiB) elif num_bytes > PiB: output = "%.3g PB" % (num_bytes / PiB) elif num_bytes > TiB: output = "%.3g TB" % (num_bytes / TiB) elif num_bytes > GiB: output = "%.3g GB" % (num_bytes / GiB) elif num_bytes > MiB: output = "%.3g MB" % (num_bytes / MiB) elif num_bytes > KiB: output = "%.3g KB" % (num_bytes / KiB) else: output = "%.3g Bytes" % (num_bytes) return output
def format_for_null(value): """If a Python value is None, we want it to convert to null in json.""" if value is None: return value else: return "{}".format(value)
def split_data(data, ratio: float): """Split the data into two data sets according to the input ratio. This function splits one-dimensional numerical list into two data sets according to the split ratio. The first data set is the data length of the split ratio, and the second data set is the data length of the split ratio. Parameters ------------------ data: list ,ndarray, pandas.Series and pandas.DataFrame. One-dimensional numerical list. ratio: float. Limitation factor: 0 < ratio <1. The split ratio is a floating point number used to determine the respective lengths of the two data sets after splitting. Returns ------------------ Two one-dimensional data sets. The first data set is the data length of the split ratio, and the second data set is the data length of the split ratio. Error ------------------ | TypeError: 'data' of type 'NoneType'. | Solution: 'data' must be one-dimensional numerical list. | ValueError: 'ratio' must be between 0 and 1, excluding 0 and 1. | Solution: Enter a floating point number greater than 0 and less than 1. | ValueError: There are less than two numerical data in the list. | Solution: There are at least two numerical data in the list. """ try: if(ratio <= 0 or ratio >= 1 ): raise ValueError("'ratio' must be between 0 and 1, excluding 0 and 1.") else: if(len(data) > 2): num = int(len(data)*ratio) train_data = data[:num] test_data = data[-(len(data) - num):] return train_data, test_data else: raise ValueError("There are at least two numerical data in the list.") except TypeError as err: raise TypeError(err)
def supported_marshaller_api_versions(): """ Get the Marshaller API versions that are supported. Gets the different Marshaller API versions that this version of ``hdf5storage`` supports. .. versionadded:: 0.3 Returns ------- versions : tuple The different versions of marshallers that are supported. Each element is a version that is supported. The versions are specified in standard major, minor, etc. format as ``str`` (e.g. ``'1.0'``). They are in descending order (highest version first, lowest version last). """ return ('1.0', )
def normalize_measurement(measure): """ Transform a measurement's value, which could be a string, into a real value - like a boolean or int or float :param measure: a raw measurement's value :return: a value that has been corrected into the right type """ try: return eval(measure, {}, {}) except: if measure in ['true', 'True']: return True elif measure in ['false', 'False']: return False else: return measure
def _create_state_for_plot(plotname): """Creates the state associated with a particular plot.""" return { # Data to show on x-axis (data type, data source) f"{plotname}.xaxis.data": ("Date", "AAPL"), # Transformation applied to x-axis (transform type, transform param) f"{plotname}.xaxis.transform": ("None", 30), f"{plotname}.yaxis.data": ("Close", "AAPL"), f"{plotname}.yaxis.transform": ("None", 30), # Plot type (line or scatter) and plot color f"{plotname}.type": "line", f"{plotname}.color": "peru", }
def driving_filter(exclude_public_service_vehicle_paths=True): """ Driving filters for different tags (almost) as in OSMnx for 'drive+service'. Filter out un-drivable roads, private ways, and anything specifying motor=no. also filter out any non-service roads that are tagged as providing parking, private, or emergency-access services. If 'exclude_public_service_vehicle_paths' == False, also paths that are only accessible for public transport vehicles are included. Applied filters: '["area"!~"yes"]["highway"!~"cycleway|footway|path|pedestrian|steps|track|corridor|' 'elevator|escalator|proposed|construction|bridleway|abandoned|platform|raceway"]' '["motor_vehicle"!~"no"]["motorcar"!~"no"]{}' '["service"!~"parking|parking_aisle|private|emergency_access"]' """ drive_filter = dict( area=["yes"], highway=[ "cycleway", "footway", "path", "pedestrian", "steps", "track", "corridor", "elevator", "escalator", "proposed", "construction", "bridleway", "abandoned", "platform", "raceway", ], motor_vehicle=["no"], motorcar=["no"], service=["parking", "parking_aisle", "private", "emergency_access"], ) if exclude_public_service_vehicle_paths: drive_filter["psv"] = ["yes"] return drive_filter
def ip6_str_from16bytes(s: bytes) -> str: """ Convert bytestring to string representation of IPv6 address Args: s: source bytestring Returns: IPv6 address in traditional notation """ m = [f"{b:02x}" for b in s] r = "" for i in range(16): r = r + ":" + m[i] if (i % 2 == 0 and i != 0) else r + m[i] return r.replace("0000", "").replace("::", ":")
def pickFirstLast(current, total, firstEvent, lastEvent, middleEvent): """ A helper function to select the correct event classification as a shorthand. - Pick `firstEvent` if current = 0 - Pick `lastEvent` if current = total - 1 - Pick `middleEvent` on any other case """ if current == total - 1: return lastEvent elif current == 0: return firstEvent else: return middleEvent
def remove_spades(hand): """Returns a hand with the Spades removed.""" spadeless_hand = hand[:] for card in hand: if "Spades" in card: spadeless_hand.remove(card) return spadeless_hand
def rgb(rgb_colors): """ Return a tuple of integers, as used in AWT/Java plots. Parameters ---------- rgb_colors : list Represents a list with three positions that correspond to the percentage red, green and blue colors. Returns ------- tuple Represents a tuple of integers that correspond the colors values. Examples -------- >>> from pymove.visualization.visualization import rgb >>> rgb([0.6,0.2,0.2]) (51, 51, 153) """ blue = rgb_colors[0] red = rgb_colors[1] green = rgb_colors[2] return int(red * 255), int(green * 255), int(blue * 255)