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 ad...
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 ...
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 ...
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]: ...
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 ...
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...
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...
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 ...
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 = ...
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): # -...
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 ...
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 ...
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 ...
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 i...
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)...
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. """...
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(...
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: ...
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. ...
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': ...
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 = ' '.j...
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' % outp...
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 ...
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'...
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 cu...
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 =...
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])...
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...
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: ...
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 ...
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" ...
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) eli...
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...
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] >=...
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 relatio...
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 th...
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`` """ ...
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" ...
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_r...
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)] retu...
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 ...
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 ...
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 equi...
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": ...
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 ...
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: ...
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: ...
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 S...
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...
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 = stri...
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 i...
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 t...
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 ...
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 fo...
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] - short...
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 ...
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 o...
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 t...
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, {}, {}...
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...
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, p...
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...
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: re...
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 ...