content
stringlengths
42
6.51k
def _cast_safe(self, value, cast_type = str, default_value = None): """ Casts the given value to the given type. The cast is made in safe mode, if an exception occurs the default value is returned. :type value: Object :param value: The value to be casted. :type cast_type: Type ...
def _contains_atom(example, atoms, get_atoms_fn): """Returns True if example contains any atom in atoms.""" example_atoms = get_atoms_fn(example) for example_atom in example_atoms: if example_atom in atoms: return True return False
def stringToList(data): """ Return a list from the given string. Example: print listToString('apple, pear, cherry') # ['apple', 'pear', 'cherry'] :type data: str :rtype: list """ data = '["' + str(data) + '"]' data = data.replace(' ', '') data =...
def snap_to_widest(to_snap, widests): """ Snaps the width of each column of the table to the width of the largest element in the respective column. """ new_table = list() for row in to_snap: new_row = list() for i in range(0, len(widests)): new_row.append(f'{str(row[i...
def prepare_query(site_id: str, condition: str) -> str: """ Creates GraphQL query :type site_id: ``str`` :param site_id: Site ID entered by user :type condition: ``str`` :param condition: filter conditions :rtype: ``str`` :return: GraphQL query """ query = """query getAssetRes...
def get_utf8_bytes(char): """Get the UTF-8 bytes encoding an unicode character Parameters: char: unicode character Returns: integer array of the UTF-8 encoding """ # Get the codepoint (integer between 0 and 0x1fffff) c = ord(char) assert c < 0x20000 if c < 0x80: # 0..7F...
def get_cr_lum(lum1: float, lum2: float) -> float: """Compute contrast ratio of two luminance values.""" val = (lum1 + 0.05) / (lum2 + 0.05) return val if val >= 1 else 1 / val
def chomp(string): """ Simple callable method to remove additional newline characters at the end of a given string. """ if string.endswith("\r\n"): return string[:-2] if string.endswith("\n"): return string[:-1] return string
def ard_map(value, in_min, in_max, out_min, out_max): """ Arduino's map function :return: """ return out_min + (out_max - out_min) * ((value - in_min) / (in_max - in_min))
def find_last_dig(num_str): """Find index in string of number (possibly) with error bars immediately before the decimal point. Parameters ---------- num_str : str String representation of a float, possibly with error bars in parens. Returns ------- pos : int String inde...
def ns(s): """remove namespace, but only it there is a namespace to begin with""" if '}' in s: return '}'.join(s.split('}')[1:]) else: return s
def compute_acc_bin(conf_thresh_lower, conf_thresh_upper, conf, pred, true): """ Computes accuracy and average confidence for bin Args: conf_thresh_lower (float): Lower Threshold of confidence interval conf_thresh_upper (float): Upper Threshold of confidence interval conf (numpy.nda...
def getItemsFromDefaults(defaults, params): """Converts defaults to specific items for this view. Args: defaults: the defaults to instantiate params: a dict with params for this View """ result = [] for url, menu_text, access_type in defaults: url = url % params['url_name'].lower() item = (...
def probability_of_ij_given_k(i, j, k, category_membership_list, stimuli, m): """ Function that calculates the mean of the posterior probability density for non-informative priors. More specifically, it is the probability that the stimulus displays value j on dimension i given that it comes from categor...
def all_list_element_combinations_as_pairs(l): """Returns a list of tuples that contains element pairs from `l` in all possible combinations without repeats irrespective of order. :param list l: list to parse into pairs :return: element_pairs, list of tuples for each pair :rtype: list """ e...
def step_function(x: float, step_coordinate: float = 0, value_1: float = 0, value_2: float = 1) -> float: """Simple step function. Parameters ---------- x : float Coordinate. step_coordinate: float Step coordiante. value_1 : float Function returns value_1 if x < step_coo...
def connection_string_to_dictionary(str): """ parse a connection string and return a dictionary of values """ cn = {} for pair in str.split(";"): suffix = "" if pair.endswith("="): # base64 keys end in "=". Remove this before splitting, then put it back. pair...
def max(*numbers): """ Returns largest number """ if len(numbers) == 0: return None else: maxnum = numbers[0] for n in numbers[1:]: if n > maxnum: maxnum = n return maxnum
def require_dict_kwargs(kwargs, msg=None): """ Ensure arguments passed kwargs are either None or a dict. If arguments are neither a dict nor None a RuntimeError is thrown Args: kwargs (object): possible dict or None msg (None, optional): Error msg Returns: dict: kwarg...
def alpha_weight(epoch, T1, T2, af): """ calculate value of alpha used in loss based on the epoch params: - epoch: your current epoch - T1: threshold for training with only labeled data - T2: threshold for training with only unlabeled data - af: max alpha value """ if...
def transform_entity_synonyms(synonyms, known_synonyms=None): """Transforms the entity synonyms into a text->value dictionary""" entity_synonyms = known_synonyms if known_synonyms else {} for s in synonyms: if "value" in s and "synonyms" in s: for synonym in s["synonyms"]: ...
def path_exists(filename: str) -> bool: """ Checks for the given file path exists. """ from pathlib import Path return Path(filename).exists()
def new_database_connection_message(payload): """ Build a Slack notification about a new database connection. """ connection_url = payload['connection']['url'] connection_name = payload['connection']['name'] connection_vendor = payload['connection']['vendor'] connection_provider = payload['...
def __walk_chain(rel_dict, src_id): """ given a dict of pointing relations and a start node, this function will return a list of paths (each path is represented as a list of node IDs -- from the first node of the path to the last). Parameters ---------- rel_dict : dict a dictionary ...
def _is_match_one(sub_string_list, src_string): """ Whether the sub-string in the list can match the source string. Args: sub_string_list (list): The sub-string list. src_string (str): The source string. Returns: bool, if matched return True, else return False. """ for ...
def get_frequency_GC_str(string): """ get the ratio of GC pairs to the total number of pairs from a DNA strings """ GC = [] total = len(string) for i in string: if i == 'C' or i == 'G': GC.append(1) return float(sum(GC)/total)
def is_int(s): """ Returns True if string 's' is integer and False if not. 's' MUST be a string. :param s: string with number :type s: str :rtype: bool """ try: int(s) return True except ValueError: return False
def bio2ot_absa(absa_tag_sequence): """ bio2ot function for absa task """ new_absa_sequence = [] n_tags = len(absa_tag_sequence) for i in range(n_tags): absa_tag = absa_tag_sequence[i] #assert absa_tag != 'EQ' if absa_tag == 'O' or absa_tag == 'EQ': new_absa...
def points_in_window(points): """Checks whether these points lie within the window of interest Points is a list of one start, one end coordinate (ints) """ if None in points or points[0] < -5 or points[1] < -5 or points[0] > 5 or points[1] > 5: return False return True
def formatFloat(number, decimals=0): """ Formats value as a floating point number with decimals digits in the mantissa and returns the resulting string. """ if decimals <= 0: return "%f" % number else: return ("%." + str(decimals) + "f") % number
def get_color_list_css(color_list): """Convert color list to ipycytoscape css format.""" return [f"rgb({r},{g},{b})" for r, g, b in color_list]
def index_keyword(lst, keyword): """Index of all list members that include keyword """ return [i for i, x in enumerate(lst) if keyword in x]
def nWaveAmplitude(M, bulletDiam, bulletLen, xmiss, patm=101e3): """ Calculate N-wave overpressure amplitude Parameters ---------- M -- Mach number bulletDiam -- bullet diameter in m bulletLen -- bullet length in m xmiss -- miss distance in m patm -- atmosperic pressure in Pa R...
def emitter_injection_efficiency(i_en=0,i_e=1): """ The emitter injection efficiency measures the fraction of the emitter current carried by the desired electrons or holes in a NPN or PNP device. The default is for a NPN device. Parameters ---------- i_en : float, required Elect...
def xml_match(xml, match): """ Finds the first subelement matching match and verifies that its text attribute is 'true' :param xml: xml as ET instance :param match: pattern to lookup by find :return: boolean """ if xml is not None: return xml.find(match).text == 'true' return Fa...
def all_checks_passed(linter_stdout): """Helper function to check if all checks have passed. Args: linter_stdout: list(str). List of output messages from pre_commit_linter. Returns: bool. Whether all checks have passed or not. """ return 'All Checks Passed.' in linter_s...
def initialiser_array(evaluator, ast, state): """Evaluates initial values "= { ... }".""" vals = list(map(lambda var: evaluator.eval_ast(var, state), ast["vals"])) return vals
def isSchema2Id(id): """ return true if this is a v2 id """ # v1 ids are in the standard UUID format: 8-4-4-4-12 # v2 ids are in the non-standard: 8-8-4-6-6 parts = id.split('-') if len(parts) != 6: raise ValueError(f"Unexpected id formation for uuid: {id}") if len(parts[2]) == 8: ...
def run_length(result): """ Calculates the number of repeatd values in a row. """ max_run = 0 current_run = 0 for i in range(1, len(result)): if result[i] == result[i - 1]: current_run += 1 if current_run > max_run: max_run = current_run else: ...
def flipall_angles(angles): """ Horizontally flips all angles in the `angles` array. """ return [360 - a for a in angles]
def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit """ return r...
def _where_location(record: dict, item: str, last_section_title: str, last_subsection_title: str) -> dict: """Get information where a parsed item should be stored in the resulting JSON.""" where = record[item] if last_section_title: if last_section_title not in where: where['@sections']...
def get_choice(meta_ext, meta_file, key): """ tries to get meta_ext[key], then try meta_file[key] :param dict meta_ext: :param dict meta_file: :param str key: :return ret: """ assert meta_file is not None if meta_ext is not None: ret = meta_ext.get(key, None) if ret is N...
def get_file_path_from_url(url: str) -> str: """ All pages on the site are served as static files. This function converts a URL into a filepath from the dist folder. """ if '.' not in url: url = f'{url}/index.html' return url
def ret(error_message=None, **kwargs): """ Make return JSON object :param error_message: sets "error" field to given message string :param kwargs: fields to set on the return JSON """ r = {} if error_message is not None: r["error"] = error_message r.update(kwargs) return r
def modpos(pos,L,move): """very similar to modcoord, but only for a LxL. takes as input walk[i][0] or walk[i][1] returns the pos modified with the move, accounting for PBCs.""" pos += move # if pos == L: #moved off right or bottom # return(0) # if pos == -1:#moved off top or left # ...
def get_cf_specs_encoding(ds): """Get the ``cf_specs`` encoding value Parameters ---------- ds: xarray.DataArray, xarray.Dataset Return ------ str or None See also -------- get_cf_specs_from_encoding """ if ds is not None and not isinstance(ds, str): for source...
def calc_reduction_layers(num_cells, num_reduction_layers): """Figure out what layers should have reductions.""" reduction_layers = [] for pool_num in range(1, num_reduction_layers + 1): layer_num = (float(pool_num) / (num_reduction_layers + 1)) * num_cells layer_num = int(layer_num) reduction_layers....
def make_it_big(prefix): """Mirrors the macro ``MAKE_IT_BIG`` in ``absurdly_long_names.hpp``.""" big = [ prefix, "that", "is", "longer", "than", "two", "hundred", "and", "fifty", "five", "characters", "long", "which", "is", "an", "absolutely", "and", "completely", "ridiculous", "thing", ...
def no_high(list_name): """ list_name is a list of strings representing cards. Return TRUE if there are no high cards in list_name, False otherwise. """ if "jack" in list_name: return False if "queen" in list_name: return False if "king" in list_name: return False ...
def join_keys(key1, key2, sep="/"): """ Args: key1 (str): The first key in unix-style file system path. key1 (str): The second key in unix-style file system path. sep (str): The separator to be used. .. code-block:: python :caption: Example >>> join_keys('/agent...
def bold(text: str) -> str: """Wrap input string in HTML bold tag.""" return f'<b>{text}</b>'
def get_living_neighbors(i, j, generation): """ returns living neighbors around the cell """ living_neighbors = 0 # count for living neighbors neighbors = [(i-1, j), (i+1, j), (i, j-1), (i, j+1), (i-1, j+1), (i-1, j-1), (i+1, j+1), (i+1, j-1)] for k, l in neighbors: ...
def test_jpeg(h, f): """JPEG data in JFIF or Exif format""" if h[6:10] in (b'JFIF', b'Exif'): return 'jpeg'
def change_variable_name(text): """ doc :param text: :return: """ lst = [] for index, char in enumerate(text): if char.isupper() and index != 0: lst.append("_") lst.append(char) return "".join(lst).lower()
def isPalindromic(n): """ A palindromic number reads the same both ways. such as 9009 """ s = str(n) r = s[::-1] if s == r: return True else: return False
def getMovesFromString(string): """Returns a list of moves from a move string (e.g. '1. e4 e5 2. Nf3 Nc6 *')""" moves = [] for i in string.split(" "): if i in ["*", "1-0", "0-1", "1/2-1/2"]: break if i[0].isnumeric(): continue moves.append(i) return moves
def firesim_tags_to_description(buildtriplet, deploytriplet, commit): """ Serialize the tags we want to set for storage in the AGFI description """ return """firesim-buildtriplet:{},firesim-deploytriplet:{},firesim-commit:{}""".format(buildtriplet,deploytriplet,commit)
def score_sort_cmp(es_hit): """comparator for sorting by sentiment""" return es_hit['vader_score']['compound']
def get_parameters(current, puzzle_input, opcode): """extracts the parameters from the input and updates the current location """ if opcode == '03' or opcode == '04': params = [puzzle_input[current]] current += 1 else: params = [puzzle_input[current], puzzle_in...
def icoalesce(iterable, default=None): """Returns the first non-null element of the iterable. If there is no non-null elements in the iterable--or the iterable is empty--the default value is returned. If the value to be returned is an exception object, it is raised instead. """ result = next((...
def getitem(obj, key=0, default=None): """Get first element of list or return default""" try: return obj[key] except: return default
def spin(pgms, move): """Spin the last move program to the front. >>> spin(['a', 'b', 'c', 'd', 'e'], 1) ['e', 'a', 'b', 'c', 'd'] >>> spin(['a', 'b', 'c', 'd', 'e'], 3) ['c', 'd', 'e', 'a', 'b'] """ return pgms[-move:] + pgms[:-move]
def make_divisible(v, divisor, min_value=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: ...
def compatible_shape(shape1,shape2): """Find the smallest shape larger than shape1 that can be broadcast to shape2""" shape = [] n = min(len(shape1),len(shape2)) for i in range(0,n): if shape1[-1-i] == 1: shape = [1]+shape else: shape = [shape2[-1-i]]+shape return tuple(shape)
def ContinuedLine(level3, towns): """Return true if this seems continued line.""" for town in towns: if level3.startswith(town): return False return True
def ToUnixLineEnding(s): """Changes all Windows/Mac line endings in s to UNIX line endings.""" return s.replace('\r\n', '\n').replace('\r', '\n')
def deg2dms(val, delim=':'): """ Convert degrees into hex coordinates """ if val < 0: sign = -1 else: sign = 1 d = int( sign * val ) m = int( (sign * val - d) * 60. ) s = (( sign * val - d) * 60. - m) * 60. return '{}{}{}{}{}'.format( sign * d, delim, m, delim, s)
def decode_labels(labels): """Validate labels.""" labels_decode = [] for label in labels: if not isinstance(label, str): if isinstance(label, int): label = str(label) else: label = label.decode('utf-8').replace('"', '') labels_decode...
def pairless_grads(ch_names): """Returns indexes of channels for which the first three numbers of the name are present only once. This means that if ['MEG 1232', 'MEG 1332', 'MEG 1333'] is given, then [0] should be returned. Parameters ---------- ch_names : list List of channel na...
def remove_extra_spaces(s): """ Remove unnecessary spaces :param s: :return: """ return " ".join(s.split())
def run_in_frontend(src): """ Check if source snippet can be run in the REPL thread, as opposed to GUI mainloop (to prevent unnecessary hanging of mainloop). """ if src.startswith('_ip.system(') and not '\n' in src: return True return False
def forward_path_parser(_input): """Parsing plain dict to nested.""" def create_keys_recursively(key, current_tree): """Update current tree by key(s).""" if key not in current_tree: last = keys.pop() # pylint: disable=undefined-loop-variable # this value def...
def jiffer_status_string(pybert) -> str: """Return the jitter portion of the statusbar string.""" try: jit_str = " | Jitter (ps): ISI=%6.3f DCD=%6.3f Pj=%6.3f Rj=%6.3f" % ( pybert.isi_dfe * 1.0e12, pybert.dcd_dfe * 1.0e12, pybert.pj_dfe * 1.0e12, ...
def indices(a, func): """ Get indices of elements in an array which satisfies func >>> indices([1, 2, 3, 4], lambda x: x>2) [2, 3] >>> indices([1, 2, 3, 4], lambda x: x==2.5) [] >>> indices([1, 2, 3, 4], lambda x: x>1 and x<=3) [1, 2] >>> indices([1, 2, 3, 4], lambda x: x in [2, 4]) ...
def chop_duplicate_ends(word): """Remove duplicate letters on either end, if the are adjacent. Args: words (list): The list of words Returns: list: An updated word list with duplicate ends removed for each word. """ if word[0] == word[1]: word = word[1:] if word[-2:-1] ...
def le_dtuple(d1, d2): """Return if d1_i <= d2_i as sparse vectors.""" d2_dict = dict(d2) return all(gen in d2_dict and exp <= d2_dict[gen] for gen, exp in d1)
def getCheckedCArgs(argument_list): """ Convert the compilation arguments (include folder and #defines) to checked C format. :param argument_list: list of compiler argument. :return: argument string """ clang_x_args = [] for curr_arg in argument_list: if curr_arg.startswith("-D") or curr_arg.sta...
def associate(first_list, second_list,offset,max_difference): """ Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim to find the closest match for every input tuple. Input: first_list -- first dictionary of (stamp,data) tuples second_list -- second dictio...
def dtype_reducer(the_dtype, wanted_cols): """Remove extraneous columns from the dtype definition. In cases where a data file includes some columns of data that are not of particular interest or relevance, this function can remove those columns that are not needed (or more accurately, retain only t...
def _format_text(text): """Format text.""" text = text.replace("-", "--") text = text.replace("_", "__") text = text.replace(" ", "_") return text
def get_all_exported_url_names(json_urlpatterns): """ Get all names and namespaces in some URLconf JSON. :param json_urlpatterns: list of JSON URLconf dicts :return: list of strings; url_names and namespaces """ url_names = set() for url in json_urlpatterns: included_urls = url.get(...
def covered(string='covered'): """ prints a string Parameters ---------- string : int the string to be printed Returns ------- exit code : int 0 """ print(string) return 0
def dot(v, w): """v_1 * w_1 + ... + v_n * w_n""" return sum(v_i * w_i for v_i, w_i in zip(v, w))
def extract_pairs(raw): """Return a list of tuple pairs from a string of comma-separated pairs""" try: pairs = list(set([(p.split("-")[0].strip().upper(), p.split("-")[1].strip().upper()) for p in raw.split(",")])) except IndexError as e: raise IndexError("Invalid pair") for x, y in pai...
def internalNodeIP(node_id): """Return IP address of radio node on internal network""" return '10.10.10.{:d}'.format(node_id)
def get_number_of_stimuli(stimuli_dir): """Note that for the natural images, it makes sense to think of the batch size as the number of bins""" # for pure conditions (natural or optimized): if "pure" in stimuli_dir: n_reference_images = 9 batch_size_natural = ( n_reference_im...
def is_valid(id_str, id_len=16): """ Simple check for a valid zerotier network_id Args: id_str (str): Zerotier network id or address Returns: bool: True if the id_str is valid, False otherwise """ if len(id_str) != id_len: return False try: # expected to be val...
def processedcount(file_list): """Counts to how many files SSP has already been added to.""" n = 0 for item in file_list: if item[-7:-4] == 'ssp': n = n+1 return n
def underscore_to_camelcase(name): """ Convert new-style method names with underscores to old style camel-case names. :: >>> underscore_to_camelcase('assert_equal') ... 'assertEqual' >>> underscore_to_camelcase('assert_not_equal') ... 'assertNotEqual' >>> unders...
def get_qa_Z_range(): """ Returns qa Z range """ return (0.0, 130.0) # in mm
def bellman_ford(nodes, edges, source): """ Bellman ford shortest path algorithm Parameters ---------- nodes : set names of all nodes in the graph edges : list list of dependencies between nodes in the graph [(node1, node2, weight), ...] source : str ...
def listify(x): """ Returns a list """ if not hasattr(x, '__len__'): return [x] else: return x
def params_get(path, params): """Read a key/path from loaded params. Parameters ---------- path : str The .-delimited path to the value to return. Currently supports dict keys but not numeric array indices. params : dict Params as read using read_params(). """ r = params ...
def price_range(prices): """ Set price limits """ min_range, max_range = prices if not min_range: min_range = 0 if not max_range: # How to make infinite? max_range = 999999999 return min_range, max_range
def klucb(x, d, div, upperbound, lowerbound=-float("inf"), precision=1e-6): """The generic klUCB index computation. Input args.: x, d, div: KL divergence to be used. upperbound, lowerbound=-float('inf'), precision=1e-6, """ l = max(x, lowerbound) u = upperbound while...
def is_strictly_legal_content(content): """ Filter out things that would violate strict mode. Illegal content includes: - A content section that starts or ends with a newline - A content section that contains blank lines """ if content.strip("\r\n") != content: return False eli...
def asjson(obj): """Return a string: The JSON representation of the object "obj". This is a peasant's version, not intentended to be fully JSON general.""" return repr(obj).replace("'", '"')
def inversions(constants, variables): """Number of swaps""" if variables: pow2 = pow(2, variables - 1, 1_000_000_007) return pow2 * (constants * 2 + variables) return constants
def is_valid(isbn): """Varify if given number is a valid ISBN 10 number""" # Setup for validity check digits = [int(n) for n in isbn if n.isnumeric()] if len(digits) == 9 and isbn[-1].upper() == "X": digits.append(10) # length check to weed out obvious wrong answers if len(digits) != 1...