content
stringlengths
42
6.51k
def swa_lr_decay(step: int, cycle_len: int, start_lr: float, end_lr: float) -> float: """ Linearly decrease the learning rate over the cycle. """ return start_lr + ((end_lr - start_lr) / cycle_len) * (step % cycle_len)
def cons_list_to_dict(cons): """ Allows us to access constraints py type, instead of using a list index""" new_dict = {} for c in cons: new_dict[c["type"]] = c return new_dict
def knot2ms(ws_knot): """ Convert unit of wind speed from knots to meter per seconds. Examples --------- >>> ws_ms = kkpy.util.knot2ms(ws_knot) Parameters ---------- ws_knot : array_like Array containing wind speed in **knots**. Returns --------- ws...
def _parse_reference_conditions(ref_line): """reads the reference quantities line""" sref = float(ref_line[0:10].strip()) cref = float(ref_line[10:20].strip()) bref = float(ref_line[20:30].strip()) xcg = float(ref_line[30:40].strip()) ycg = float(ref_line[40:50].strip()) zcg = float(ref_line...
def _calculate_interconnected_value(vij, vik, vil, vkj, vkk, vkl, vlj, vlk, vll): """Calculate an interconnected S-parameter value Note: The interconnect algorithm is based on equation 6 in the paper below:: Filipsson, Gunnar. "A new general computer algorithm for S-matrix calculation ...
def find_tps(ckt, a): """ Return all of the gates that are a have a fan-out not in this partition. """ return set([x for x in a if ckt[x].fots.isdisjoint(set(a))])
def drop(n, xs): """``drop :: Int -> [a] -> [a]`` Returns the suffix of list `xs` after the first `n` elements, or `[]` if ``n > length xs``. """ return xs[n:]
def _check_option(parameter, value, allowed_values, extra=''): """Check the value of a parameter against a list of valid options. Raises a ValueError with a readable error message if the value was invalid. Parameters ---------- parameter : str The name of the parameter to check. This is used...
def merge_bbox(bboxes): """ Merge bounding boxes. Arguments: bboxes: iterator of bbox tuples. Returns: An encompassing bbox. """ minx, miny = [], [] maxx, maxy = [], [] for a, b, c, d in bboxes: minx.append(a) miny.append(b) maxx.append(c) ...
def is_iterable(x) -> bool: """ Iterable is an object capable of returning iterator. """ return hasattr(x, "__iter__")
def clean_sequence(wtSeq): """Remove parentheses from user input wt sequence""" return wtSeq.translate({ord(i): None for i in "()"})
def _process_number_format(raw_format): """Process the user define formatter. Reduces cases for number format in apply_number_format. """ if isinstance(raw_format, str): processed_format = [raw_format] elif isinstance(raw_format, int): processed_format = f"{{0:.{raw_format}f}}" ...
def get_faces(lst): """Compute all the possible faces by iteratively deleting vertices""" return [lst[:i] + lst[i+1:] for i in range(len(lst))]
def Lower(v): """Transform a string to lower case. >>> s = Schema(Lower) >>> s('HI') 'hi' """ return str(v).lower()
def dedup_and_title_case_names(names): """Should return a list of names, each name appears only once""" return [name.title() for name in set(names)]
def add_0x(string): """Add 0x to string at start. """ if isinstance(string, bytes): string = string.decode('utf-8') return '0x' + str(string)
def first_word(title): """Find the first word in a title that isn't an article or preposition.""" split_title = title.split() articles = ['a', 'an', 'the', 'some'] prepositions = ['aboard','about','above','across','after','against','along','amid','among','anti','around','as','at','before','behind','belo...
def next_power_of_two(num): """Returns the next power of two >= num. Args: num: A positive integer. Returns: The next power of two >= num. """ val = 1 while val < num: val *= 2 return val
def frame_number(frame, speed, particles): """ Creates the text for the animation, called every frame to get the text to be displayed. Can have your own text the function must have the same input and output variables as this one. The first line to be run is pos = frame*speed to get th...
def FirstNItems(iterable, n): """ Generator yielding the first n items of a stream. FirstNItems(iterable, n) -> iterator iterable -- a sequence, iterator, or some object which supports iteration, yielding items of any type. n -- an integer or None Example: # Read an...
def calculate_address(address): """ Gives the relative address once the bank is loaded. This is not the same as the calculate_pointer in the pokemontools.crystal.pointers module. """ return (address % 0x4000) + 0x4000
def to_number(digits): """ Returning number containing digits """ number = 0 digits.reverse() for digit_index in range(0, len(digits)): number += digits[digit_index] * 10 ** digit_index return number
def _force_lower(value): """Force a string to be lowercase. :param value: arbitrary text :type value: str or unicode """ try: return value.lower() except AttributeError: return None
def og_salience(x_1: float, x_2: float, theta: float = 0.1) -> float: # check what theta is really supposed to do; Is it only supposed to prevent Div by zero? --> Doesn't say in the text. It is simply a degree of freedom to fit data """ basic salience function proposed as more tractable parametrization in origi...
def toBase(n, base): """ Utility function, converts certain number to another base """ convertString = "0123456789ABCDEF" if n < base: return convertString[n] else: return toBase(n // base, base) + convertString[n % base]
def create_object(size): """Just create and return an object containing `size` bytes.""" mem_use = b'a' * size return mem_use
def createanimerelated(a, retrieve_links = False): """ Here I create a list of unique related anime. If retrieve_links = True the function saves the link of the related anime If retrieve_links = False the function saves the names of the related anime """ if a is None: return (a) ...
def strip_token(token) -> str: """ Strip off suffix substring :param token: token string :return: stripped token if a suffix found, the same token otherwise """ if token.startswith("["): return token pos = token.find("[") # If "[" is not found if pos < 0: ...
def fleiss_kappa(m): """ Returns the reliability of agreement as a number between -1.0 and +1.0, for a number of votes per category per task. The given m is a list in which each row represents a task. Each task is a list with the number of votes per category. Each column represents a...
def remove_unspecified_items(attrs): """Remove the items that don't have any values.""" for key, value in list(attrs.items()): if not value: del attrs[key] return attrs
def calc_cbar(c_0, c_curr): """ Calculate the co2 concentration average between the historical co2 and current co2 concentrations Parameters ---------- c_0 : float Historical co2 concentration, in ppm c_curr : float Current co2 concentration, in ppm Return ...
def local_magnetization(N, result: dict, shots: int, qub: int): """Compute average magnetization from results of qk.execution. Args: - N: number of spins - result (dict): a dictionary with the counts for each qubit, see qk.result.result module - shots (int): number of trials Return: - averag...
def _validate_fixed_params(fixed_params, spec_param_names): """ Check that keys in fixed_params are a subset of spec.param_names except "sigma2" Parameters ---------- fixed_params : dict spec_param_names : list of string SARIMAXSpecification.param_names """ if fixed_params i...
def func_name(freq=None, isic=False): """ Get key for imaging condition/linearized source function """ if freq is None: return 'isic' if isic else 'corr' else: return 'isic_freq' if isic else 'corr_freq'
def get_insert_query(table_name: str) -> str: """Build a SQL query to insert a RDF triple into a PostgreSQL table. Argument: Name of the SQL table in which the triple will be inserted. Returns: A prepared SQL query that can be executed with a tuple (subject, predicate, object). """ return f"INSERT...
def verified_blacklisted_tag(x, tag): """ check for '<' + blacklisted_tag + ' ' or '>' as in: <head> or <head ...> (should not match <header if checking for <head) """ initial = x[0:len(tag) + 1 + 1] blacklisted_head = "<{0}".format(tag) return initial == (blacklisted_head + " ") or initial...
def compute_calendar_date(jd_integer, julian_before=None): """Convert Julian day ``jd_integer`` into a calendar (year, month, day). Uses the proleptic Gregorian calendar unless ``julian_before`` is set to a specific Julian day, in which case the Julian calendar is used for dates older than that. "...
def reverseList(head): """ :type head: ListNode :rtype: ListNode """ # Check base case: if head == None: return None elif head.next == None: return head else: node = head.next # node = 2 -> 3 prev_node = head prev_node.next = None node_cop...
def helper(x): """old version of date format helper, run in py2 and old pandas """ splited_list = list(map(int, x.strip('[').strip(']').split(','))) d = {} for counter, value in enumerate(splited_list): k = str(len(list(splited_list)))+"-"+str(counter) d[k] = int(value) retur...
def gen_Anomaly(location, id_): """Generate an anomaly object.""" anomaly = { "@type": "Anomaly", "Location": location, "DroneID": id_, "Status": "To be Confirmed", "AnomalyID": "-1" } return anomaly
def set_urlsafe_b64(val: str, urlsafe: bool = True) -> str: """Set URL safety in base64 encoding.""" if urlsafe: return val.replace("+", "-").replace("/", "_") return val.replace("-", "+").replace("_", "/")
def time_taken(elapsed): """To format time taken in hh:mm:ss. Use with time.monotic() or Timer class""" m, s = divmod(elapsed, 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s)
def flatten(text): """ Flatten the text: * make sure each record is on one line. * remove parenthesis """ lines = text.split("\n") # tokens: sequence of non-whitespace separated by '' where a newline was tokens = [] for l in lines: if len(l) == 0: continue ...
def asymmetric_extend(q1, q2, extend_fn, backward=False): """directional extend_fn """ if backward: return reversed(list(extend_fn(q2, q1))) return extend_fn(q1, q2)
def decodeMsg(aStr): """Decode a message received from the hub such that multiple lines are restored. """ return aStr.replace("\v", "\n")
def normalise(test, ref, strict=False): """ Routine to normalise contents of test by contents of ref. :param dict test: Dictionary of test metrics :param dict ref: Dictionary of reference metrics :param bool strict: if True then test and ref must have same metrics :returns: Dictionary of normal...
def remove_first(lst, elem): """ This function removes the first appearance of elem in list lst. >>> remove_first([3, 4] , 3) [4] >>> remove_first([3, 4, 3] , 3) [4, 3] >>> remove_first([2, 4] , 3) [2, 4] >>> remove_first([] , 0) [] """ "*** YOUR CODE HERE ***" if lst ==...
def final_strategy(score, opponent_score): """Write a brief description of your final strategy. *** YOUR DESCRIPTION HERE *** """ "*** YOUR CODE HERE ***" return 5
def fibonacci_py(v): """ Computes the Fibonacci sequence at point v. """ if v == 0: return 0 if v == 1: return 1 return fibonacci_py(v - 1) + fibonacci_py(v - 2)
def get_symbols(formula): """ get all symbols in formula """ return set([abs(lit) for clause in formula for lit in clause])
def get_dataset_and_split_names(dist_shift): """Gets dataset and split names.""" dataset_names = {} split_names = {} if dist_shift == 'aptos': dataset_names['in_domain_dataset'] = 'ub_diabetic_retinopathy_detection' dataset_names['ood_dataset'] = 'aptos' split_names['train_split'] = 'train' spl...
def guess_decode(text): """Decode *text* with guessed encoding. First try UTF-8; this should fail for non-UTF-8 encodings. Then try the preferred locale encoding. Fall back to latin-1, which always works. """ try: text = text.decode('utf-8') return text, 'utf-8' except Unico...
def _sign(x): """Returns True if x is positive, False otherwise.""" return x and x/abs(x)
def to_json_type ( v ): # log.debug( '.begin' ) # from "https://github.com/SublimeText/Modelines/blob/master/sublime_modelines.py" """"Convert string value to proper JSON type. """ if v.lower() in ('true', 'false'): v = v[0].upper() + v[1:].lower() try: return eval(v, {}, {}) except: raise ValueError("Coul...
def parsemsg(s): """ Breaks a message from an IRC server into its prefix, command, and arguments. """ prefix = '' trailing = [] if s[0] == ':': prefix, s = s[1:].split(' ', 1) if s.find(' :') != -1: s, trailing = s.split(' :', 1) args = s.split() args.append(t...
def _update_globals(task_file_to_run, globals_dict): """Updates globals dictionary with default data path for provided task if Inputs/Outputs directories are equal to None. Args: task_file_to_run (str): path to the task that will be run. globals_dict (dict): contains global variables for f...
def is_port_range(port): """ If ports are specified and as a port range, then validate whether the ranges are the same length. This is only used when creating destination NAT rules. """ if isinstance(port, str) and '-' in port: start_port, end_port = map(int, port.split('-')) ret...
def get_all_rotated_notes(notes): """ Get all rotated notes get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]] :type notes: list[str] :rtype: list[list[str]] """ notes_list = [] for x in range(len(notes)): notes_list.append(notes[x:] + notes[:x]) return notes_list
def merge(l_arr, r_arr): """ :param l_arr: :param r_arr: :return: """ l_idx = r_idx = 0 res = [] while len(l_arr) > l_idx and len(r_arr) > r_idx: if l_arr[l_idx] < r_arr[r_idx]: res.append(l_arr[l_idx]) l_idx += 1 else: res.append(r_ar...
def este_corect(expresie): """ Returns true or false if the expression is valid :param expresie: an expression formed out of parenthesis :return: read the doc """ if len(expresie) % 2 != 0: return False opening_parenthesis = set('([') parenthesis = ([('(', ')'), ('[', ']')]) ...
def do_remove_real_time_spent(text): """If the line has a RealTimeSpent content then remove this """ #if text.find('RealTimeSpent') != -1: offset = text.find('RealTimeSpent'); if offset != -1: text_length = len(text) # RealTimeSpent=0.000211 if (text_length - offset) == 22: ...
def convert_hsl_to_rgb(hue: float, sat: float, lum: float, max_input=255.0, max_output=255.0): """Converts HSI or HSL colors into RGB. Accepts hue, sat, and lum as floats or ints, defaulting to 0.0-255.0 range. Returns RGB as a list of three floats, defaulting to 0.0-255.0 range. Change max_input and ...
def effective_power(n, gv_power): """ Calculate and return the value of effective power using given values of the params How to Use: Give arguments for efficiency and gv_power parameters *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE H...
def coordinate_of_sequence(sequence): """ ___0__1__2__3__4__ 4| 1 2 3 4 5 3| 6 7 8 9 10 2| 11 12 13 14 15 1| 16 17 18 19 20 0| 21 22 23 24 25 """ y = 4 - ((sequence - 1) // 5) x = (sequence - 1) % 5 return x, y
def fibonacci(n, start=0, accumulator=None): """Compute first n Fibonacci numbers. Args: start (int): Optional starting point. Default is 0. The end user should not use this argument. n (int): number of numbers to return in the list. accumulator (list): Optional argument to ...
def understand_data(data): """Parse the pytesseract data""" lines = data.split("\n") items = [] head = lines[0].split("\t") for k, line in enumerate(lines): if k == 0: continue item = {} attributes = line.split("\t") if len(head) != len(attributes): ...
def zot_keepArticle(zot_library): """ Removes entries that are attachments, notes, computerProgram and annotation from complete Zotero Library """ zot_articles = [] notKeep = ['attachment', 'note', 'computerProgram', 'annotation'] # Entry types to not keep for item in zot_library: if it...
def masseuse_memo(A, memo, ind=0): """ Return the max with memo :param A: :param memo: :param ind: :return: """ # Stop if if ind > len(A)-1: return 0 if ind not in memo: memo[ind] = max(masseuse_memo(A, memo, ind + 2) + A[ind], masseuse_memo(A, memo, ind + 1)) ...
def flatten(data_structure): """ The flatten function takes a nested data structure (list of lists of lists etc) and returns a flattened version of it (list of values) as well as a flatten pattern that stores the nesting information. >>> flatten([1,'abc',[0,[1,1,[5]],'def'],9,10,11]) ([1, 'abc', 0, 1, ...
def formulas_to_string(formulas): """Takes an iterable of compiler sentence objects and returns a string representing that iterable, which the compiler will parse into the original iterable. """ if formulas is None: return "None" return " ".join([str(formula) for formula in formulas])
def look_for_array_in_array(array1, array2): """ Find a subset of values in an array. Parameters ---------- array1 : iterable An array with values to be searched array2 : iterable A second array which potentially contains a subset of values also contained in ``array1`` ...
def generate_secret(yourname: str) -> str: """Generates very secret password based on your name Args: yourname (str): user name Returns: str: secret password """ return "secret" + yourname
def vlan_range_to_oc(value): """ Converts an industry standard vlan range into a list that can be interpreted by openconfig. For example: "1, 2, 3-10" -> ["1", "2", "3..10"] """ return [s.replace("-", "..") for s in value.split(",")]
def estimateitems(sent, prune, mode, dop): """Estimate number of chart items needed for a given sentence. The result is used to pre-allocate the chart; an over- or underestimate will only affect memory allocation efficiency. These constants were Based on a regression with Tiger parsing experiments.""" beta = 600 ...
def permute(elements): """ returns a list with the permuations. """ if len(elements) <= 1: return [elements] else: tmp = [] for perm in permute(elements[1:]): for i in range(len(elements)): tmp.append(perm[:i] + elements[0:1] + perm[i:]) ...
def shorten_path_for_print(path, maxlen=100): """helper to print pretty URLs""" if len(path) <= maxlen: return path from urllib.parse import urlparse url = urlparse(path) out = '' out += url.scheme + '://' if url.scheme != '' else '' out += url.netloc out += '/'.join(url.path...
def tap(f, v): """Runs the given function with the supplied object, then returns the object. Acts as a transducer if a transformer is given as second parameter""" f(v) return v
def create_db_strs(txt_tuple_iter): """ From an iterable containing DB info for records in DB or 'not in DB' when no records were found, return info formatted as string. :param txt_tuple_iter: an iterable of strings and tuples where the 0 element of the tuple is the gene/name...
def doi_parser(doi, start_url, useSSL=True): """Parse doi to url""" HTTP = 'https' if useSSL else 'http' url = HTTP + '://{}/{}'.format(start_url, doi) return url
def multiply(m, n): """Recursively multiply the number 'm' by 'n' times >>> multiply(5, 3) 15 """ """BEGIN PROBLEM 2.1""" return m if n == 1 else m + multiply(m, n - 1) """END PROBLEM 2.1"""
def util_key_new ( schema, keys ): """Returns list of keys not in schema""" new_keys = [] for i in keys: if i not in schema: new_keys.append(i) return new_keys
def restar_num(val1, val2): """restar_num :: Float x Float -> Float Resta los 2 valores solo si son Float""" if val1.__class__.__name__ == 'float' and val2.__class__.__name__ == 'float': res = val1 - val2 return res else: print(val1.__class__.__name__) print(val2.__class...
def no_auto_update(on=0): """Gerenciar Atualizacoes Automaticas do Windows DESCRIPTION Esta configuracao lhe permite desabilitar as atualizacoes automaticas do Windows. COMPATIBILITY Windows 2000/XP MODIFIED VALUES NoAutoUpdate : dword : 00000000 = Atual...
def comp_interp(xold, xnew, mix=1.0): """Interpolate between two compositions by mixing them. Mix controls how much of the new composition to add. A mix of 1.0 means to discard the old step completely and a mix of 0 means to discard the new step completely (note a mix of of 0 therefore means the compo...
def _gauss_jordan(m, eps = 1.0/(10**10)): """Puts given matrix (2D array) into the Reduced Row Echelon Form. Returns True if successful, False if 'm' is singular. NOTE: make sure all the matrix items support fractions! Int matrix will NOT work! Written by Jarno Elonen in April 2005, released into Publi...
def filter_BF_matches(matches: list, threshold=45) -> list: """ filter matches list and keep the best matches according to threshold :param matches: a list of matches :param threshold: threshold filtering :return: matches_tmp: list of the best matches """ matches_tmp = [] sorted_matches ...
def tclloader_prep(loaderfile, directory=False): """ Prepare directory name and OS version. :param loaderfile: Path to input file/folder. :type loaderfile: str :param directory: If the input file is a folder. Default is False. :type directory: bool """ loaderdir = loaderfile if directo...
def fmt_shell_cmd_log_file_prologue(cmd): """ Create the prologue for a log file which holds the result of the execution of `cmd` """ return """$ %s %s """ % (cmd, "-" * 50)
def isascii(s): """See if the string can be safely converted to unicode.""" try: s.encode('ascii') except UnicodeError: return False else: return True
def avg_sentiment(review): """ Get the overall sentiment of a paragraph by looking at the sentiment that is mostly reflected on the sentences. Input: response from alchemy with sentiment output. Output: augmented json object with overall sentiment. """ sentiments = [] if 'entities' i...
def mark(l, h, idx): """Produce markers based on argument positions :param l: sentence position of first word in argument :param h: sentence position of last word in argument :param idx: argument index (1 or 2) """ return [(l, "{}{}".format('~~[[', idx)), (h+1, "{}{}".format(idx, ']]~~'))]
def org_empty_payload(org_default_payload): """Provide an organization payload with no action.""" empty_payload = org_default_payload empty_payload["action"] = "" return empty_payload
def selection_to_string(selection): """Convert dictionary of coordinates to a string for labels. Parameters ---------- selection : dict[Any] -> Any Returns ------- str key1: value1, key2: value2, ... """ return ', '.join(['{}: {}'.format(k, v) for k, v in selection.items()]...
def tokenize(raw): """Produces list of tokens indicated by a raw expression string. For example the string '(43-(3*10))' results in the list ['(', '43', '-', '(', '3', '*', '10', ')', ')'] """ SYMBOLS = set('+-x*/() ') # allow for '*' or 'x' for multiplication mark = 0 tokens = [] n = len(raw) fo...
def factorial(num): """ find the factorial of the given number :param num: Number :return: Factorial of num :rtype: int """ cache = {} if num in cache: return cache[num] if num == 0: return 1 else: x = num * factorial(num - 1) cache[num] = x ...
def string_join(*ss): """ String joins with arbitrary lengthy parameters :param ss: strings to be joined :return: strings joined """ return "".join(ss)
def parse_q(s): """Parse the value of query string q (?q=) into a search sub-term.""" if '=' not in s: names = s.split() term = '/'.join(map(lambda x: 'n.name=' + x, names)) return term else: subterms = s.split() res = [] for subterm in subterms: i...
def lookup(my_dict, my_key, default_value=None): """ Given dictionary my_dict and key my_key, return my_dict[my_key] if my_key is in my_dict otherwise return default_value """ if my_key in my_dict: return my_dict[my_key] else: return default_value
def as_list(x): """Convert x to a list. It performs the following conversion: None => [] list => x tuple => list(x) other => [x] Args: x (any): the object to be converted Returns: a list. """ if x is None: return [] if isinstance(x, li...
def query_successful(api_response): """This function reviews the API response from the Community API to verify whether or not the call was successful. :param api_response: The response from the API in JSON format :type api_response: dict :returns: Boolean indicating whether or not the API call was succ...