content
stringlengths
42
6.51k
def createPolygonPolyline(type, coords): """Create WKT POLYGON or LINESTRING string. Args: type (str): ``POLYGON`` to create polygon, else will create ``LINESTRING``. coords (list): Two item list representing single point coordinate. Returns: str: WKT POLYGON or LINESTRING string. ...
def _GetArgUsageSortKey(name): """Arg name usage string key function for sorted.""" if not name: return 0, '' # paranoid fail safe check -- should not happen elif name.startswith('--no-'): return 3, name[5:], 'x' # --abc --no-abc elif name.startswith('--'): return 3, name[2:] elif name.startswit...
def addcr(text): """Adds a cr if it needs one. >>> addcr("foo") 'foo\\n' >>> addcr("foo\\n") 'foo\\n' :returns: string with \\n at the end """ if not text.endswith("\n"): return text + "\n" return text
def get_run_data_from_cmd(line): """Parser input data from a command line that looks like `command: python3 batch_runner.py -t benders -k cache -i s6.xml -v y -r 0` and put it into a dict. """ words = line.split(" ")[3:] word_dict = {} for (i, word) in enumerate(words): if word.sta...
def get_dictionary_input(corpus): """get a format where each doc is a list of words. This is simply to conform to gensim.corpora.getDictionary API. :param corpus: a dictionary with items the result of running tex trank algorithm, for example, {12345: [("foo", 1.2), ("bar",1.1)...]} :return:...
def wrap_nicely(string, max_chars): """Wrap nicely function A helper that will return a list of lines with word-break wrapping Parameters ---------- string : str The text to be wrapped max_chars: int The maximum number of characters on a line before wrapping Returns ---...
def SortDict(Dict, sortidx=0): """Sort dictionary USAGE: SortDict(Dict,sortidx): DESCRIPTION: Sort dictionary of lists according field number 'sortidx' """ sortlist = [] keylist = list(Dict.keys()) for key in keylist: rec = Dict[key] if not isinstance(rec, (list, tuple)): rec = [...
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number < 0: return None # can't handle complex numbers # if number == 0: # return number # ...
def flatten_entrypoints(ep): """Flatten nested entrypoints dicts. Entry points group names can include dots. But dots in TOML make nested dictionaries: [entrypoints.a.b] # {'entrypoints': {'a': {'b': {}}}} The proper way to avoid this is: [entrypoints."a.b"] # {'entrypoints': {'a.b': {}}...
def secondsToTime(seconds): """Convert seconds to time""" minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) weeks, days = divmod(days, 7) return "%d Weeks %d Days %d Hours %d Minutes %d Seconds" % (weeks, days, hours, minutes, seconds)
def _get_id(param): """Returns a parameter ID. If param is a Parameter object, then we get the ID from it. Otherwise, we assume param is an integer. """ try: # If this is a Parameter object, then return its _id attr. return param._id except AttributeError: # Otherwise, w...
def first_lower(s): """Return the index of the first lowercase character in string s.""" for idx, c in enumerate(s): if c.islower(): return idx return -1
def get_shard_range(dataset_size: int, rank: int, world_size: int): """ In case dataset_size is not evenly divided by world_size, we need to pad one extra example in each shard shard_len = dataset_size // world_size + 1 Case 1 rank < remainder: each shard start position is rank * shard_len Cas...
def breadth_first_search(node, adj_list): """ This function has been obtained from https://github.com/CGATOxford/UMI-tools The logic behind the algorithm to cluster UMIs using an adjacent distance matrix is described in http://genome.cshlp.org/content/early/2017/01/18/gr.209601.116.abstract ...
def get_nested(d: dict, *keys): """ Gets nested dict values, returning None if any in the chain don't exist or are None. """ if len(keys) == 1: return d[keys[0]] else: nested = d.get(keys[0], None) if nested is not None: return get_nested(nested, *keys[1:]) else...
def construct_num_check(token_list): """Construct num_check list to classify each item in token_list. At matching indices of token_list, elements of num_check are given either True(numeric value), False(string) or one of shorthand_keys. shorthand_keys: - R: Repetition. Ex) '2 4R' = '2 2 2 2 2' ...
def get_column(matrix, index): """ :param matrix: a list of iterables of the same length :param index: zero-indexed column to select :returns: column as string """ column = "".join([x[index] for x in matrix]) return column
def truncate_or_pad(sequence, block_size, pad_token_id): """ Adapt the source and target sequences' lengths to the block size. If the sequence is shorter we append padding token to the right of the sequence. """ if len(sequence) > block_size: return sequence[:block_size] else: sequen...
def _load_dotted(name): """ Load a dotted name (Stolen from wtf-server) The dotted name can be anything, which is passively resolvable (i.e. without the invocation of a class to get their attributes or the like). Parameters: name (str): The dotted name to load Returns: ...
def week_day_on_first_auroran(dek_year: int) -> int: """Returns the Gregorian week day for the first Auroran of a given year Args: dek_year (int): Year. Return: int: The week day. Example: 1 = Sunday; 2 = Monday; 3 = Tuesday ... 7 = Saturday. """ week_day = ( (1 + 5...
def _implements_state(obj): """Helper method to check if foreign object supports setting/getting state.""" return hasattr(obj, 'state') and callable(getattr(obj, 'state')) and \ hasattr(obj, 'set_state') and callable(getattr(obj, 'set_state'))
def getname(child: str) -> str: """ Sometimes the xml-parser puts an extra attribute in the tag of an Element (also named namespace). This methods removes this unnessessary string. """ try: return child[child.index("}") + 1 :] except ValueError: return child
def filters_from_args(request_args): """ Helper to centralize reading filters from url params """ timespans_id = request_args['timespanId'] if 'timespanId' in request_args else None snapshots_id = request_args['snapshotId'] if 'snapshotId' in request_args else None foci_id = request_args['focusI...
def unpack_grouped_choices(choices): """ Unpack a grouped choices hierarchy into a flat list of two-tuples. For example: choices = ( ('Foo', ( (1, 'A'), (2, 'B') )), ('Bar', ( (3, 'C'), (4, 'D') )) ) becomes: choi...
def _reduceletters(lttrs): """ Takes: 'studios' Returns: {'s':2, 't':1, 'u':1, 'd':1, 'i':1, 'o':1} """ key = {} for t in lttrs: key.setdefault(t, 0) key[t] += 1 return key
def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ ...
def crossv3(a,b): """cross product of 3-vectors a and b""" return (a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0])
def is_close(value_a: float, value_b: float, tolerance: float = 0.000001) -> bool: """Tests whether or not value_a and value_b are "close" (i.e. within the `tolerance` after subtracting) Args: value_a: numeric value to test value_b: numeric value to test toleranc...
def VAVL(pa,pb): """ Van Albada & Van Leer averaging function """ if(pa*pb > 0.0): e = 1.0e-8 num = ( pa*pa + e*e )*pb + ( pb*pb + e*e )*pa den = ( pa*pa + pb*pb + 2.0*e*e ) vv = num/den else: vv = 0.0 return vv
def apply_gain_x(x, AdB): """Applies A dB gain to x """ return x*10**(AdB/20)
def _is_positive_answer(answer): """ Used to check if an answer is positive from a user. """ if answer in ["yes", "y"]: return True return False
def check_move(proposed_move, user_piece, board_state): """Check if a proposed move is legal and return a bool""" # Check that user correctly formatted their move if len(proposed_move) != 2: print("Invalid move! Try again.") return False # Check that user used the correct piece for...
def _starts_with_space(line, return_on_blank=True): """ returns true if line starts with space :line: the line to be examined :return_on_blank: what to return if line == "" :returns: True if starts with space, False else """ try: return line[0] == ' ' ...
def valid_metric(metric_name, value): """Validates that a metric is within reasonable, reportable parameters. Returns True if valid (default) and false if any validity constraints are violated. A very hacky, first effort, implementation""" # by default, all metrics less than 0 are considered invalid va...
def get_encoding_for_char(char, encoding_table): """Get the encrypted version of the char""" return encoding_table.get(char) if char in encoding_table else char
def rgb2bgr(tpl): """ Convert RGB color tuple to BGR """ return (tpl[2], tpl[1], tpl[0])
def findReqAttributes(nvim_raw): """ Get all supported keys for functions """ attri_set = set() for f in nvim_raw['functions']: attri_set |= set(list(f.keys())) return attri_set
def get_types_from_params(q, advanced_args): """ Adds "types" filters to `q` for each type specified in `advanced_args`, or returns `q` unmodified if `types` was not present or empty. """ types = [] try: if advanced_args['types'] != '': types = advanced_args['types'].split(';...
def valid_transfer_value(transfer_value): """Returns True if transfer_value is valid Returns False if transfer_value is not valid """ try: int(transfer_value) except: return False return True
def _normalize(feature_vector, word_count): """ Normalizes the given feature vector's values by word_count. """ for feature, score in feature_vector.items(): feature_vector[feature] = score/float(word_count) return feature_vector
def convert_sections(defaults): """ Drop parameters that are missing section_1. """ filtered_pol_params = {} for k, v in defaults.items(): if k == "schema" or v.get("section_1", False): filtered_pol_params[k] = v return filtered_pol_params
def map_agent_to_domains(agent_label, lambda_tmp): """ Returns the domain(s) that an agent is allowed to explore. :param agent_label: agent label :param lambda_tmp: lambda value :return: domain label """ assert agent_label in [1, 2, 3, 4], f'ERROR: Check agent label: {agent_label}' asse...
def ignore_args(function_args, args2ignore, ignore_value = None): """ Remove argument values to be ignored. Args: function_args: list of function arguments. args2ignore: list of integers representing index in argument list. ignore_value: value to substitute in ignored arguments. """...
def CountOccurrences(pattern, bwt, starts, occ_counts_before): """ Compute the number of occurrences of string pattern in the text given only Burrows-Wheeler Transform bwt of the text and additional information we get from the preprocessing stage - starts and occ_counts_before. """ # Implement this fu...
def get_update_components(options): """ Same as get_insert_components but for update queries. Returns a tuple in the form (placeholders, values) to be used as follows: c.execute('UPDATE Table SET {placeholders}', values)""" placeholders = ','.join( '{}=?'.format(opt[0]) for opt in options ) values = tuple(opt...
def yields_from_leung_nomoto_2018_table6(feh): """ Supernova data source: Leung & Nomoto, 2018, ApJ, Volume 861, Issue 2, Id 143, Table 6/7 The seven datasets are provided for Z/Zsun values of 0, 0.1, 0.5, 1, 2, 3 and 5. Using Zsun = 0.0169 the corresponding FeH values are -1, -0.301, 0.0, 0.301, 0.4771...
def removeprefix(string: str, prefix: str) -> str: """Remove a prefix from a string Add support for :meth:`str.removeprefix` for Python < 3.9. :param string: String to remove prefix from :param prefix: Prefix to remove """ # return string.removeprefix(prefix) if string.startswith(prefix): ...
def permutations(arr): """permutations of 5 choose 2""" if len(arr) == 2: return [arr, [arr[1], arr[0]]] else: result = [] for i in range(len(arr)): for j in permutations(arr[:i] + arr[i+1:]): result.append([arr[i]] + j) return result
def optional(run, deco): """This is a decorator which applies another decorator only if the condition is true.""" if run: return deco else: def do_nothing(func): return func return do_nothing
def parse_params_bool(params, p): """ Get and parse a boolean value from request params. """ val = params.pop(p, None) if not val: return False return val.lower() in ("yes", "1", "true")
def numbers_by_recursion(n): """ Print numbers from 1 to the largest number with N digits by recursion. :param n: given number :type n: int :return: numbers from 1 to the largest number with N digits :rtype: list[int] """ result = [] if n > 0: result = numbers_by_recursion(n...
def isAllDigits( str_arg ): """ Is the given string composed entirely of digits? (convenience function for python isdigit)""" return str_arg.isdigit()
def clz_(x): """ https://en.wikipedia.org/wiki/Find_first_set """ n = 0 ; if x == 0: return 32 while (x & 0x80000000) == 0: n += 1 x <<= 1 pass return n
def apStar_url(telescope, location_id, field, file_, url_header=None): """ apStar url generator which in principle is able to generate file path Parameters ---------- telescope: string TELESCOPE, {"apo1m', 'apo25m'} location_id: int for 'apo1m', it's 1 for...
def _is_descriptor(obj): """Returns True if obj is a descriptor, False otherwise. From cpython Enum""" return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
def collect(batch): """Collect the data for one batch. """ imgs = [] targets = [] filenames = [] for sample in batch: imgs.append(sample[0]) targets.append(sample[1]) filenames.append(sample[2]) return imgs, targets, filenames
def searchFunction(func, haystack, invalid=None): """ an almost useless wrapper around a function """ return func(haystack) or invalid
def isStringLike(s): """ Returns True if s acts "like" a string, i.e. is str or unicode. Args: s (string): instance to inspect Returns: True if s acts like a string """ try: s + '' except: return False else: return True
def _get_suggestions_index(name): """Returns suggestions index name for a regular index name.""" return f'df_suggestions_{name}'
def findBuildDirs(testList): """ given the list of test objects, find the set of UNIQUE build directories. Note if we have the useExtraBuildDir flag set """ buildDirs = [] reClean = [] for obj in testList: # be sneaky here. We'll add a "+" to any of the tests that ...
def simple_table(row, col, cell_factory): """ Create and return a simple table, like: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] """ return [ [cell_factory(i, j) for j in range(col)] for i in range(row) ]
def fmt_option_val(option): """Format a single option (just a value , no key).""" if option is None: return "" return str(option)
def gen_list_of_lists(original_list, new_structure): """Generates a list of lists with a given structure from a given list.""" assert len(original_list) == sum( new_structure ), "The number of elements in the original list and desired structure don't match." return [ [original_list[i + ...
def calc_reward(curr_state, action): """ Compute the reward for the next state & action. @curr_state The next state in the transition @action The action taken @return reward Computed reward """ return curr_state*(-1) + action * (-2)
def determine_result(winning_piece, user_piece): """Return result of game depending on what piece the user is""" if user_piece == winning_piece: return "won" else: return "lost"
def sorted_by_attr(vals, attr, reverse=False): """Sort sequence <vals> by using attribute/key <attr> for each item in the sequence.""" return sorted(vals, key=lambda x: x[attr], reverse=reverse)
def distance(a, b): """Compute the distance between a and b. This is based on Damerau-Levenshtein distance, but we modify the cost of some edits, like insertion or removal of '_', or capitalisation changes. """ d = {} la = len(a) lb = len(b) for i in range(la + 1): d[i, 0] = i ...
def ev_strip(short): """Strip zeros, taking into account E / V codes. """ if short.startswith("E") or short.startswith("V"): return short[0] + short[1:].lstrip("0") else: return short.lstrip("0")
def get_defaults(schema): """ Gets default values from the schema Args: schema: jsonschema Returns: dict: dict with default values """ result = "" try: _type = schema['type'] except KeyError: return result except TypeError: raise SyntaxError(...
def parse_log_history(log_history): """ Parse the `log_history` of a Trainer to get the intermediate and final evaluation results. """ idx = 0 while idx < len(log_history) and "train_runtime" not in log_history[idx]: idx += 1 # If there are no training logs if idx == len(log_history...
def get_excluded_params(schema): """ Get all params excluded in this schema, if "only" is provided in schema instance, consider all not included params as excluded. :param schema: instance or cls schema :return: set of excluded params """ if isinstance(schema, type): return set()...
def _nub(items): """Return new list containing unique elements of items, retaining order.""" seen = set() result = [] for item in items: if item not in seen: result.append(item) seen.add(item) return result
def generate_latex_eq(obj, eqn, label): """Generate LaTeX code for equations. Parameters ---------- obj : object Object equation is applied for. eqn : str LaTeX code of the equation core. label : str LaTeX label for the equation. Returns ------- latex : st...
def remove_matching_braces(latex): """ If `latex` is surrounded by matching braces, remove them. They are not necessary. Parameters ---------- latex : string Returns ------- string Examples -------- >>> remove_matching_braces('{2+2}') '2+2' >>> remove_matching_...
def time_seconds_to_ns(time_seconds): """Converts a time value in seconds to a time value in nanoseconds. `time_seconds` is a `float` as returned by `time.time()` which represents the number of seconds since the epoch. The returned value is an `int` representing the number of nanoseconds since the...
def prepareNameSuffix(results): """Parse and prepare name_suffix based on results.""" counts = {'country_code': [], 'city': [], 'name': []} # Separate different country codes for row in results: for field in counts.keys(): if field not in row: continue if...
def format_env_export(**d): """Converts env var values into variable string, ie 'export var1="val1" && export var2="val2" '""" args_ = [f'export {key}="{d[key]}" ' for key in d] return ' && '.join(args_)
def cal_ap_voc2012(recall, precision): """ cal_ap_voc2012 """ ap_val = 0.0 eps = 1e-6 assert len(recall) == len(precision) length = len(recall) cur_prec = precision[length - 1] cur_rec = recall[length - 1] for i in range(0, length - 1)[::-1]: cur_prec = max(precision...
def handle(req): """handle a request to the function Args: req (str): request body """ return "I am " + req + " from alauda.io"
def selectNGramModel(models, sentence): """ Requires: models is a list of NGramModel objects sorted by descending priority: tri-, then bi-, then unigrams. starting from the beginning of the models list, returns the first possible model that can be used for the current sentence based on...
def url2featid(url,product_type): """ url2pid(url): convert url to feature id Arguments: - url: url to convert Keyword Arguments: None Returns: - feature id for url """ return url.replace(product_type,'features').replace('features__','features_'+product_type+'...
def default_value(feature): """Decides a default value for the given feature, to replace missing or null values. Parameters ---------- feature (str): Name of feature. Returns ---------- (int or bool): Default value for given feature. """ if feature == 'rqst_timespan': ...
def reverseWords(s): """ :type s: str :rtype: str """ lst=s.split() return " ".join(i[::-1] for i in lst)
def generate_template(template, **vars): """ Replaces variables inside a template. :param template: Text with variables between brackets {}. :type src: str """ return template.format(**vars)
def replace_password(d : dict) -> dict: """ Recursively replace passwords in a dictionary. """ _d = d.copy() for k, v in d.items(): if isinstance(v, dict): _d[k] = replace_password(v) elif 'password' in str(k).lower(): _d[k] = ''.join(['*' for char in str(v)])...
def get_validations(validation_id): """ Stub to return validations """ if validation_id == '43': return { 'id': '43', 'action_id': '59bb330a-9e64-49be-a586-d253bb67d443', 'validation_name': 'It has shiny goodness', 'details': 'This was not very shi...
def parse_chain(chain): """Parse a filter chain into a sequence of filters. """ parts = [] for p in chain.split(","): p = p.strip() if p.lower() == "none": continue if len(p) > 0: parts.append(p) return parts
def replace_guide_name_with_bnd_name(guide_jnt_name): """ replaces the guide joint name with the bound name. :param guide_jnt_name: <str> joint name. """ if "__" in guide_jnt_name: return guide_jnt_name.rpartition("__")[0] + '_bnd_jnt' return True
def spherical(h, r, sill, nugget=0): """ Spherical variogram model function. Calculates the dependent variable for a given lag (h). The nugget (b) defaults to be 0. Parameters ---------- h : float The lag at which the dependent variable is calculated at. r : float Effect...
def generate_cart_id(build, cartseries, cartidx): """Generate CART ID""" return 'CART{}{}{}'.format(build, cartseries, cartidx)
def palindrome(input): """ Checking for palindrome """ input = str(input) return input[::-1] == input
def hamming(word1, word2): """ Caculate hamming distances between words. >>> hamming('todd', 'john') 3 >>> hamming('geek', 'wire') 4 """ c = 0 for i in range(len(word1)): if word1[i] != word2[i]: c += 1 return c
def df(n): """Gives the double factorial of *n*""" return 1.0 if n <= 0 else 1.0 * n * df(n - 2)
def isolate_rsync_opts(options): """ pop the misc RSYNC related options littered in make.conf, returning a base rsync dict """ base = {} opts = [] extra_opts = [] opts.extend(options.pop('PORTAGE_RSYNC_OPTS', '').split()) extra_opts.extend(options.pop('PORTAGE_RSYNC_EXTRA_OPTS', '')...
def to_cl_args(args_dict): """ Create a list of cl args from a dictionary """ args_list = [] for k, v in args_dict.items(): args_list.append(f"--{k}") args_list.append(v) return args_list
def get_extension(s, delimiter='.'): """Returns what belongs after delimiter""" ext = "" point = False for c in s: if c == delimiter: ext = "" point = True if point: ext += c return ext
def is_action(key: object) -> bool: """ Check whether key is an action. """ return hasattr(key, 'type')
def get_tags_gtf(tagline): """Extract tags from given tagline""" tags = dict() for t in tagline.strip(';').split(';'): tt = t.strip(' ').split(' ') tags[tt[0]] = tt[1].strip('"') return tags
def index_by_modifier_as_list(sequence, modifier, target_index=None): """ Create an index of objects in a sequence. The index's key will be provider by the modifier. Values are lists, so keys are not expected to be unique. The modifier is called for each object with that object as an argument and is su...
def scaleto100(value): """Scale the input value from 0-255 to 0-100.""" # Make sure a low but non-zero value is not rounded down to zero if 0 < value < 3: return 1 return int(max(0, min(100, ((value * 100.0) / 255.0))))