content
stringlengths
42
6.51k
def concat_name_county(name): """ This function is used to concat a string of words by putting underscore between words example: "new york steuben" --> "new_york_steuben" @param name: string of raw name @return concat_name: concated words of string by underscore """ try: assert name ...
def clear_bit_k(int_val, k): """Clears the bit at offset k""" return int_val & ~(1 << k)
def constant_time_compare(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-...
def parse_vars(variables): """Parse variables passed as args to list of tuples If variable has required value then it'll be appended in format (key, value). If variable has no variable (it should just exist) then it'll be appended as (key,) :param variables: string of variables in args format '...
def safety_check_first_line(first_line: str) -> None: """Inspects first line of lineage_notes.txt to perform safety check. We pull all of our Pango lineages from a human-edited .txt file. The format has been stable so far, but if things ever change significantly, the planned loading process will probab...
def is_big(label: str) -> bool: """Returns whether or not a cave is large based on its label""" return label.isupper()
def snapshot_expval_counts(shots): """SnapshotExpectationValue test circuits reference counts.""" targets = [] # State |+1> targets.append({'0x1': shots / 2, '0x3': shots / 2}) # State |00> + |11> targets.append({'0x0': shots / 2, '0x3': shots / 2}) # State |01> -i|01> targets.append({'0...
def addUnits(metric_name): """Add units according to the input metric PARAMETERS ---------- metric_name : string name of the metric to plot RETURNS ------- label : string name of the metric to plot with the units that were added to it """ if "energy" ...
def constraint(n, j, d): """ This function returns the DoF of a system according to the Constraint Formulation. @Input: n - Number of links j - List: len(j) = number of joints ith element of j = DoF of the ith joint d - 3 dimensional or 2 dimension...
def pad_list(orig_list, pad_length): """ Pads a list with empty items Copied from http://stackoverflow.com/a/3438818/3710392 :param orig_list: the original list :param pad_length: the length of the list :return: the resulting, padded list """ return orig_list + [''] * (pad_length - len(o...
def fstr(value): """Canonical xml float value output""" int_value = int(value) if int_value == value: return str(int_value) return str(value)
def flax_cond(pred, true_operand, true_fun, false_operand, false_fun): # pragma: no cover """ for debugging purposes, use this instead of jax.lax.cond """ if pred: return true_fun(true_operand) else: return false_fun(false_operand)
def pipe_hoop_stress(P, D, t): """Calculate the hoop (circumferential) stress in a pipe using Barlow's formula. Refs: https://en.wikipedia.org/wiki/Barlow%27s_formula https://en.wikipedia.org/wiki/Cylinder_stress :param P: the internal pressure in the pipe. :type P: float :param D: the ou...
def truncate(number, decimals=0): """ truncate a given number to the chosen decimal place """ multiplier = 10**decimals return int(number * multiplier) / multiplier
def percent_flicker(v_max:float, v_pp:float) -> float: """Computes the flicker percentage of the waveform Parameters ---------- v_max : float The max voltage v_pp : float The peak-to-peak voltage Returns ------- float The flicker percentage """ retu...
def validate_calendar(calendar): """Validate calendar string for CF Conventions. Parameters ---------- calendar : str Returns ------- out : str same as input if the calendar is valid Notes ----- 1. The 'none' value for the calendar attribute is not supported anywhere ...
def a2z(a): """ converts from scale factor to redshift """ return 1.0/a - 1.0
def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" try: if str(arg) in value: return value[str(arg)] except: if hasattr(value,str(arg)): return getattr(value,str(arg)) return ''
def af_subtraction(ch1, ch2, m, c): """ Subtract ch2 from ch1 ch2 is first adjusted to m * ch2 + c :param ch1: :param ch2: :param m: :param c: :return: """ af = m * ch2 + c signal = ch1 - af return signal
def _remove_script_from_dependencies(executed_script, script_dependencies): """ Builds new dependencies dict skipping the executed script """ new_dependencies = dict() for script_path, dependencies in script_dependencies.items(): if script_path != executed_script: new_dependencies[script...
def evaluated_profile_li(profileli): """ Return a list of synapses which were parsed and evaluated w/o errors so far """ return [pro for pro in profileli if not pro.errflag]
def str_to_tup(lonlat_str): """ '123.45,-144.41' -> (123.45, -144.41) """ try: tup = tuple(float(s) for s in lonlat_str.split(',')) return tup except: raise Exception((f'Could not parse lon lat string: {lonlat_str}' ' Ensure lon, lat are in correct order and no s...
def _ReorderMapByTypTags(result_map): """Rearranges|result_map| to use typ tags as the top level keys. Args: result_map: Aggregated query results from results.AggregateResults Returns: A dict containing the same contents as |result_map|, but in the following format: { typ_tags (tuple of st...
def get_file_name(path): """Converts file path to file name""" file_name = path.split("\\") file_name = file_name[len(file_name) - 1] file_name = file_name[:-len(".txt")] file_name = file_name.title() file_name += " file" return file_name
def wall_long_mono_to_string(mono, latex=False): """ Alternate string representation of element of Wall's basis. This is used by the _repr_ and _latex_ methods. INPUT: - ``mono`` - tuple of pairs of non-negative integers (m,k) with `m >= k` - ``latex`` - boolean (optional, default Fals...
def divisible_by(numbers: list, divisor: int) -> list: """This function returns all numbers which are divisible by the given divisor.""" if numbers is None: return [] res = [] for item in numbers: if item % divisor == 0: res.append(item) return res
def get_full_version(package_data): """ Given a mapping of package_data that contains a version and may an epoch and release, return a complete version. For example:: >>> get_full_version(dict(version='1.2.3')) '1.2.3' >>> get_full_version(dict(version='1.2.3', epoch='2')) '2~1.2.3' ...
def link_handler(tag, post_html): """ This function switches from a specific {tag} to a specific markdown link syntax Example: <a href=URL>CAPTION</a> => [CAPTION](URL) """ old_tag = tag close_tag = "</{0}>".format(tag) tag = "<{0}".format(tag) start = post_html.find(tag) e...
def timefmt(thenumber): """ Parameters ---------- thenumber Returns ------- """ return "{:10.2f}".format(thenumber)
def _kwargs(kwargs): """ Used to forward common arguments for postgres module """ return {k: v for k, v in kwargs.items() if k in ( 'user', 'host', 'port', 'maintenance_db', 'password', 'runas')}
def jaccard_index(a, b): """ Jaccard similarity of sets a and b """ intsize = len(set.intersection(a, b)) unionsize = len(set.union(a, b)) if unionsize == 0: return 1 else: return float(intsize) / float(unionsize)
def get_dict_season(): """Return dictionary for conversion (to integers) of season strings.""" dict_season = {'DJF': 1, 'MAM': 2, 'JJA': 3, 'SON': 4, } return dict_season
def get_start_and_end(clips): """Get start and end time of a clip list in seconds.""" if len(clips) == 0: return (0, 0) else: return ( min(clip.start for clip in clips), max(clip.start + clip.length for clip in clips), )
def ParseDeviceBlocked(blocked, enable_device): """Returns the correct enabled state enum based on args.""" if enable_device is None and blocked is None: return None elif enable_device is None or blocked is None: # In this case there are no default arguments so we should use or. return blocked is True...
def mpath(path): """Converts a POSIX path to an equivalent Macintosh path. Works for ./x ../x /x and bare pathnames. Won't work for '../../style/paths'. Also will expand environment variables and Cshell tilde notation if running on a POSIX platform. """ import os if os.name == 'mac' : ...
def _hex(x): """Formatting integer as two digit hex value.""" return '0x{:02X}'.format(x)
def get_genome_dir(infra_id, genver=None, annver=None, key=None): """Return the genome directory name from infra_id and optional arguments.""" dirname = f"{infra_id}" if genver is not None: dirname += f".gnm{genver}" if annver is not None: dirname += f".ann{annver}" if key is not Non...
def remove_blanks(letters: list): """Given a list of letters, remove any empty strings. >>> remove_blanks(['a', '', 'b', '', 'c']) ['a', 'b', 'c'] """ cleaned = [] for letter in letters: if letter != "": cleaned.append(letter) return cleaned
def strip_trailing_whitespace(lines): """Removes trailing whitespace from the given lines.""" return [line.rstrip() + '\n' for line in lines]
def _adjust_lines(lines): """Adjust linebreaks to match ';', strip leading/trailing whitespace. list_of_commandlines=_adjust_lines(input_text) Lines are adjusted so that no linebreaks occur within a commandline (except matrix command line) """ formatted_lines = [] for l in lines: # ...
def combValue(comb, value): """ Bir kombinasyonun sahip oldugu value degerini dondurur """ total = 0 for i in comb: total = total + value[i] return total
def kelvin_to_celsius(kelvin): """Convert kelvin to celsius.""" celsius = kelvin - 273.15 return celsius
def is_nested(value): """Returns true if the input is one of: ``list``, ``unnamedtuple``, ``dict``, or ``namedtuple``. Note that this definition is different from tf's is_nested where all types that are ``collections.abc.Sequence`` are defined to be nested. """ return isinstance(value, (list, tuple,...
def insertion_sort(lst: list) -> list: """Sort a list in ascending order. The original list is mutated and returned. The sort is stable. Design idea: Iterate over the list. After i iterations, the first i elements of the list should be sorted. Insert the i+1'th element in the appropriate spot in th...
def clean_str(string): """ Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\...
def _int_conv(string): """ Convenience tool to convert from string to integer. If empty string return None rather than an error. >>> _int_conv('12') 12 >>> _int_conv('') """ try: intstring = int(string) except Exception: intstring = None return intstring
def validate_nag_function_name(name): """ Check wether a NAG function name is valid """ if ( name is not None and isinstance(name, str) and len(name) > 1 and name[1:].isdigit() and ( name[0:1] in ['i','n','o'] or ...
def _digit_to_hex(string_of_digit): """Convert string of digits to string of hex.""" return "".join( [ hex(int(i))[2:] for i in [ string_of_digit[i : i + 2] for i in range(0, len(string_of_digit), 2) ] ] )
def handleSentenceChild(child, tokenList): """Recursively walk the given DOM object to extract all tokens in it """ if child == None: return tokenList elif child.localName == u'cons': tokenList = handleSentenceChild(child.firstChild, tokenList) return handleSentenceChild(child.ne...
def mean(data: list): """ :param data: a list of int :return: the average of integers in data """ res = sum(data) / len(data) return res
def t_gid_parse(gid): """ Parse the GID given and return a tuple with the following values: - The real GID without bitwise flags. - Whether or not the tile is horizontally flipped. - Whether or not the tile is vertically flipped. - Whether or not the tile is "diagonally" flipped. This is a...
def pwvalid(minCount, maxCount, char, pw): """ Password Validation >>> pwvalid(1, 3, "a", "abcde") True >>> pwvalid(1, 3, "b", "cdefg") False >>> pwvalid(2, 9, "c", "ccccccccc") True """ return int(minCount) <= pw.count(char) <= int(maxCount)
def find_furthest_room(distances): """Find furthest room from the distances grid.""" return max(max(row) for row in distances)
def normalize_raw(raw_line): """Replace hard tabs with 4 spaces. """ return raw_line.replace('\t', ' ')
def prettify_logger_message(msg): """Prettifies logger messages by breaking them up into multi lines""" from textwrap import wrap linewidth = 75 - 13 indent = "\n" + " " * 13 temp = wrap(msg, width=linewidth) return indent.join(temp)
def coast(state): """ Ignore the state, go right. """ print("COAST :::: " ) action = {"command": 1} return action
def string(s): """ Convert a string to a escaped ASCII representation including quotation marks :param s: a string :return: ASCII escaped string """ ret = ['"'] for c in s: if ' ' <= c < '\x7f': if c == "'" or c == '"' or c == '\\': ret.append('\\') ...
def AND(*expressions): """ Evaluates one or more expressions and returns true if all of the expressions are true. See https://docs.mongodb.com/manual/reference/operator/aggregation/and/ for more details :param expressions: An array of expressions :return: Aggregation operator """ return ...
def calculate_area(chart, n_var, m_var): """Calculates the area under graph""" area = 0 # boolean list to check whether we have seen the graph in a col or not: seen_graph = [False] * m_var # iterate over chart: for row in range(n_var): for col in range(m_var): point = char...
def argmin(list, score_func=None): """ If a score function is provided, the element with the lowest score AND the score is returned. If not, the index of lowest element in the list is returned. If the list is empty, None is returned. """ if len(list) == 0: return None scores = list i...
def is_iterable(obj): # QualityCheckTags: DOCS,INPUTCHECK,RETURNVALUEDOCS,OVERALL """Check if given object is iterable. Arguments: - obj: object to check Return: True if given object is iterable, else False. """ if '__iter__' in dir(obj): return True else: return False
def example(foo, bar, baz): """An example entry point for testing. The rest of the function __doc__ is ignored by the entrypoint library. foo -> a foo value. bar -> a bar value. baz -> a baz value. Returns a string indicating what was passed in.""" return f'foo={foo}, bar={bar}, baz={baz}'
def _format_author(url, full_name): """ Helper function to make author link """ return u"<a class='more-info' href='%s'>%s</a>" % (url, full_name)
def create_list_attr_operation(var_attribute_list_name): """Return request string for a single operation to create an attribute of type array/list.""" return '{"op":"CreateAttributeValueList","attributeName":"' + var_attribute_list_name + '"},'
def series(n, bool=False): """ :param bool: If bool=True, then the function will return the boolean list of the prime numbers. If bool=False, then the function will return the list of prime number less than n+1. :param n: Prime Number less than n. :return: returns None if n is 0 or 1 ot...
def make_biplot_scores_output(taxa): """Create convenient output format of taxon biplot coordinates taxa is a dict containing 'lineages' and a coord matrix 'coord' output is a list of lines, each containing coords for one taxon """ output = [] ndims = len(taxa['coord'][1]) header = '...
def levenshtein(string1, string2): """ Measures the amount of difference between two strings. The return value is the number of operations (insert, delete, replace) required to transform string a into string b. """ # http://hetland.org/coding/python/levenshtein.py n, m = len(string1), le...
def first(word, k=1): """Returns FIRST_k(word). The implied grammar is taken to be empty and all symbols are treated as terminals. See <http://www.jambe.co.nz/UNI/FirstAndFollowSets.html> for more information. >>> first('hello, world', k=7) 'hello, ' >>> first(('list', 'item', 'item', ...
def general(x, n): """Represent a float in general form. This function is merely a wrapper around the 'g' type flag in the formatting specification. """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") return ''.join(('{:#.', str(n), 'g}')).format(x)
def node_spec(): """Used in tests that have recursive $refs """ return { 'type': 'object', 'properties': { 'name': { 'type': 'string' }, 'child': { '$ref': '#/definitions/Node', }, }, 'required': ...
def validation_simple(value, obj=None): """ Validates that at least one character has been entered. Not change is made to the value. """ if len(value) >= 1: return True, value else: return False, value
def reduce_lists(ids, metric, verbose=False): """ This function reduces nearby basis functions of the same sign to a single representative basis function for that feature. """ ids = list(ids) temp = ids.copy() for j in temp: if (j-1) in ids and metric[j] > metric[j-1]: ...
def get_dimensions(corners): """ Gets the dimension of a position based on the 4 corners of a position :param corners: list with 4 elements containg pairs of xy coordinates :return: (x_length, y_length) """ x0, y0 = corners[0] x1, y1 = corners[1] x2, y2 = corners[2] x3, y3 = corners[...
def firstPartOfGlyphName(name): """Returns the glyph name until the first dot.""" dotPosition = name.find(".") if dotPosition != -1: # found a dot return name[:dotPosition] else: # no dot found return name
def _compute_split_boundaries(split_probs, n_items): """Computes boundary indices for each of the splits in split_probs. Args: split_probs: List of (split_name, prob), e.g. [('train', 0.6), ('dev', 0.2), ('test', 0.2)] n_items: Number of items we want to split. Returns: The item in...
def is_sorted(a): """Evaluates if a is sorted or not.""" a_sorted = sorted(a) if a_sorted == a: return True else: return False
def calculate_average_since(hrs_after_time): """ Calculate average heart rate after specified date This function first sums all of the heart rates after the specified date. It then divides the summed heart rates by the total number of heart rate entries. The result is the sum of the heart rates after t...
def abort(transactionid): """STOMP abort transaction command. Rollback whatever actions in this transaction. transactionid: This is the id that all actions in this transaction. """ return "ABORT\ntransaction: %s\n\n\x00\n" % transactionid
def validity_of_currencytype(ctype, ftype): """This function checks if the user input of Cryptocurrency type or Fiat Money type are truly the latter. Returns 1 if found an error in the input, else returns 0.""" available_cryptocurrencies = ['ADA', 'BTC', 'BSV', 'ETH', 'ETC', 'B...
def convert_bot_name_to_environmental_name(bot_name): """ Coverts the given bot name to environmental variable name. Parameters ---------- bot_name : `str` The bot name to convert. Return ------ environmental_name : `str` """ return bot_name.lower()
def fib(n): # return Fibonacci series up to n ... """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below ... a, b = b, a+b return result
def load_grid(input_grid): """ Convert the text form of the grid into an array form. For now this input is always the same. If this changes then this code would need to be replaced. """ grid = [".#.", "..#", "###"] return grid
def QueryTupleListToList(var): """ Take the result of a SQL fetchall single variable query tuple list and make a regular python list """ list = [] for i in var: list.append(i[0]) return list
def format_time(seconds: float) -> str: """Formats time into mm:ss:xx""" minutes, seconds = divmod(seconds, 60) centi = "{:.2f}".format(seconds % 1)[1:] return "{:02d}:{:02d}{}".format(int(minutes), int(seconds), centi)
def countRun(s, c, maxRun, count): """parameter s: a string parameter c: what we're counting parameter maxRun: maximum length of run returns: the number of times that string occurs in a row This is the first step in the run sequence""" """ trial: def countRunHelp(s,c,maxRun, count):...
def _parse_gateway(gw_data): """ compute the amount of ressource unit use by a gateway service :return: dict containing the number of ressource unit used :rtype: [type] """ return {"hru": 0, "sru": 0, "mru": 0.1, "cru": 0.1}
def option_set(fp): """set of all the options in a fingerprint""" return set(fp.split(','))
def __is_picture(file): """ It returns whether the processed file is a jpg picture or not. All arguments must be of equal length. :param file: longitude of first place :return: A boolean indicating whether the file is a jpg image or not """ if file.lower().endswith("jpg") or file.lower().end...
def get_pixel_brightness_matrix(pixel_matrix): """ Convert each RGB tuple of a pixel matrix into a brightness number matrix. Parameters: pixel_matrix (list): A 2D matrix of RGB tuples Returns: pixel_brightness_matrix (list): A 2D matrix of brightness values There are numer...
def find_matches(list_of_fragments, anchor_fragment, fixed_length , verify_left=True, verify_right=True): """ Description: Using an anchor fragment find the best matches from the list of fragments to the right, left or left&right of the anchor fragment. :param list_of_fragments: lis...
def _replace_refs_in_field(fld, shelf): """ Replace refs in fields""" if "ref" in fld: ref = fld["ref"] if ref in shelf: # FIXME: what to do if you can't find the ref fld = shelf[ref]["field"] else: # Replace conditions and operators within the field i...
def h_f(v): """"humanize float""" return "{:.1f}".format(v)
def coding_problem_02(l): """ Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. Solve it without using division and in O(n). Example: >>> coding_problem_02([1, 2, 3, 4, 5...
def between(s, start, end): """ Extracts contents between 2 bookend strings, non-inclusive. >>> s = 'from numpy import my_array, my_matrix' >>> start,end = 'from','import' >>> between(s,start,end) 'numpy' @param: s <str> the string to be extracted from @param: start <str> o...
def fix_expense_report(list_of_expenses): """ brute force solution and expecting an ideal dataset i.e. one and only one pair is exists """ for i in range(len(list_of_expenses)): for j in range(i, len(list_of_expenses)): summ = list_of_expenses[i] + list_of_expenses[j] ...
def custom_formatwarning(msg, *a): """Given a warning object, return only the warning message.""" return str(msg) + '\n'
def time_from_midnight(update_time: str) -> int: """[The time from midnight to the specified time passed to the function, used to repeat events effectively] Args: update_time (str): [The time the event is scheduled] Returns: int: [The number of seconds it would take from midnig...
def disable() -> dict: """Disables database tracking, prevents database events from being sent to the client.""" return {"method": "Database.disable", "params": {}}
def toFloat(val): """Converts the given value (0-255) into its hexadecimal representation""" hex = "0123456789abcdef" return float(hex.find(val[0]) * 16 + hex.find(val[1]))
def where(flag_list): """ takes flags returns indexes of True values """ return [index for index, flag in enumerate(flag_list) if flag]