content
stringlengths
42
6.51k
def parse_time(src): """ convert time-like string into a float number in second. return the number. """ if src.find(".") > 0: s_hms, s_dec = src.split(".") n_dec = float(f".{s_dec.ljust(6,'0')}") else: s_hms = src n_dec = 0. s = s_hms.replace(":","").rjust(6,"...
def go_down_left(x: int, y: int) -> tuple: """ Go 1 unit in both negative x and y directions :param x: x-coordinate of the node :param y: y-coordinate of the node :return: new coordinates of the node after moving diagonally down-left """ return x - 1, y - 1
def get_num_signs(gt): """count number of signs. Args: gt: list of framewise labels/ predictions. Returns: number of signs """ item_old = gt[0] count = 0 for ix, item in enumerate(gt): if item_old == 0 and item == 1: count += 1 if ix == len(gt)-1...
def is_number(s): """ Test if a string is an int or float. :param s: input string (word) :type s: str :return: bool """ try: float(s) if "." in s else int(s) return True except ValueError: return False
def get_right_of_equals(line): """ Returns the text to the right of an equals. DESCRIPTION: Get the text to the right of an equals sign. KEYWORD ARGUMENTS: line (str): the line to search. RETURNS: str: the text to the right of an equals sign. """ tmpline = line.split(...
def add_decoy_tag(peptides): """ Adds a '_decoy' tag to a list of peptides """ return [peptide + "_decoy" for peptide in peptides]
def length_belong_to(weights1, weights2): """ Determine whether weights1 are totally included by weights2 weights are the list [weight, weight, ...] of one node """ if len(weights1) > len(weights2): return False i = 0 weights_1 = weights1[:] weights_2 = weights2[:] while i < ...
def stringify_measurement(measurement: dict) -> str: """Returns a string describing the measurement type that is compatible with the NIHL portal format. eg. An air conduction threshold for the right ear with no masking would yield the string `AIR_UNMASKED_RIGHT`. Parameters ---------- meas...
def first(iter): """Helper function that takes an iterable and returns the first element. No big deal, but it makes the code readable in some cases. It is typically useful when `iter` is (or can be) a generator expression as you can use the indexing operator for ordinary lists and tuples.""" fo...
def map_nested(function, data_struct, dict_only=False): """Apply a function recursivelly to each element of a nested data struct.""" # Could add support for more exotic data_struct, like OrderedDict if isinstance(data_struct, dict): return { k: map_nested(function, v, dict_only) for k, v in data_stru...
def sentence_position(i, size): """different sentence positions indicate different probability of being an important sentence""" normalized = i*1.0 / size if 0 < normalized <= 0.1: return 0.17 elif 0.1 < normalized <= 0.2: return 0.23 elif 0.2 < normalized <= 0.3: return...
def factR(n): """Assumes that n is an int > 0 Returns n!""" if n == 1: return n else: return n*factR(n - 1)
def replace_by(value, VR, action, default_name="John Doe", default_date="18000101", default_datetime="180001010000.000000", default_time="0000.000000", default_text="anon", default_code="ANON", default_age="000M", ...
def lookup_delimiter(delimiter_name): """ Maps a delimiter name (e.g. "tab") to a delimter value (e.g. "\t") This is mostly useful for tabs since Windows commandline makes it nearly impossible to specify a tab without an alias name. """ delimiter = delimiter_name if delimiter_name ...
def deleteLastRow(array): """Deletes the last row of a 2D array. It returns a copy of the new array""" array = array[:len(array)-1:] return array
def convert_to_unix_line_endings(source): """Converts all line endings in source to be unix line endings.""" return source.replace('\r\n', '\n').replace('\r', '\n')
def equals(a, b): """Equality comparison of json serializable data. Tests for equality of data according to JSON format. Notably, ``bool`` values are not considered equal to numeric values in any case. This is different from default equality comparison, which considers `False` equal to `0` and `0.0...
def N_prime(u, dfs_data): """The N'(u) function used in the paper.""" return dfs_data['N_prime_u_lookup'][u]
def drop_duplicates(seq): """Function that given an array or array of arrays *seq*, returns an array without any duplicate entries. There is no guarantee of which duplicate entry is dropped. """ noDupes = [] seq2 = sum(seq, []) [noDupes.append(i) for i in seq2 if not noDupes.count(i)] r...
def mirror_lines(string): """Given a multiline string, return its reflection along a vertical axis. Can be useful for the visualization of text version of trees.""" return '\n'.join(line[::-1] for line in string.split('\n'))
def piwpow(base, power): """Caoution! This is fucking recursion!""" if power == 0: return 1 else: return base if power == 1 else base * piwpow(base, power - 1)
def map_value(value, min_, max_): """ Map a value from 0-1 range to min_-max_ range. """ return value * (max_ - min_) + min_
def get_vectors_for_collation(i, vectors): """ Collate vectors to be used in rows of the output dataframe (see 'collate_for_4gram_model') """ v1 = vectors[i] v2 = vectors[i+1] v3 = vectors[i+2] v4 = vectors[i+3] return v1, v2, v3, v4
def is_tar_gz_archive(file_name): """test for tar.gz file archive""" if file_name.lower().endswith('.tar.gz') or file_name.lower().endswith('.tar.gzip'): return True else: return False
def selection_sort(lst): """Sorts a given list by selectioon sort pre: lst is a list of elements that can be ordered post: returns new_lst with elements of lst sorted in increasing order """ lst_size = len(lst) # swap the current item being looped over with the smallest item in lst ...
def lower_bound(prefixes, w): """ Return the "lower bound" of a set of prefixes. This is, the minimal subset wrt. inclusion such that every element of prefixes has a suffix in the lower bound set """ n_pref = set(prefixes.copy()) for e in prefixes: for e2 in prefixes: if e != e2 ...
def SHA1_f2(b, c, d): """ Second ternary bitwise operation.""" return (b ^ c ^ d) & 0xFFFFFFFF
def get_position(cont, ch): """ get the position of a character in a string content :param cont: string, input string :param ch: string, a character or a word :return: 2d list, consists of elements of position """ assert isinstance(cont, str) assert isinstance(ch, str) begin = 0 ...
def parse_replay(replay): """ Read replay (turn by turn) and compute stats for a match. :param replay: Decoded replay data :return: Interesting stats to put into database """ if replay is None: return None stats = replay["game_statistics"] return stats
def expand_delegate_list(raw_input): """ Given a string raw_input, that looks like "1-3,7" return a sorted list of integers [1, 2, 3, 7] """ if raw_input is None: return None intermediate_list = [] for item in raw_input.split(','): t = item.split('-') try: ...
def split_key_val_pairs(context, parameter, args): # pylint: disable=unused-argument """Split key-value pairs into a dictionary""" return dict(arg.split("=") for arg in args)
def get_score_class_and_letter(score): """Gets score class (CSS) and score letter from numeric score provided by caller. Take a look at irahorecka/static/css/dist/style.css to view these classes. This function assumes a score will range from -100 to 100.""" if score >= 60: if score > 86.6: ...
def default_printer(read, hit): """ return the read and all the hit strings separated by tabs """ if isinstance(hit, list): hit_string = "" for h in sorted(hit): hit_string = "%s\t%s" % (hit_string, h) else: hit_string = "\t%s" % (hit) return "%s%s\n" % (read,...
def get_susceptibility_matrix_index(age): """ The age matrix is 16x16 and it's split in groups of 4, We can use whole division to quickly get the index """ if age >= 75: return 15 else: return age // 5
def is_none_type(to_check): """ :param to_check: the type to check. :return: ``True`` if ``to_check`` is either ``NoneType`` or ``None`` (acceptable alias of ``NoneType``). """ if to_check is None: return True if to_check is type(None): return True return False
def modularsqrt(x, p): """ -------------- Modular Square Root of (x) with prime (p) -------------- """ return pow(x, (p+1)//4, p)
def strip_quotes(data:str) -> str: """ Removes escape quotes from the data """ return data[1:-1].replace("\"\"", "\"") if data.startswith("\"") and data.endswith("\"") else data
def model_field_in_all_available_languages(languages, model_instance, field_name): """Returns a list of dict""" l = [] for lang in languages: lang_code = lang[0] localized_field_name = '{field_name}_{lang_code}'.format(field_name=field_name, lang_code=lang_code) field_value = getatt...
def size_pt(altitude, min_alt, max_alt): """ Gives point size depending on its altitude. Higher(Lower) altitude = smaller(bigger) point """ coefa = (50/( min_alt - max_alt)) coefb = 60 - (coefa * min_alt) return coefa * altitude + coefb
def array_pair_sum_sort(arr, k): """ first sort the array and then use binary search to find pairs. complexity: O(nlogn) """ result = [] arr.sort() for i in range(len(arr)): if k - arr[i] in arr[i+1:]: result.append([arr[i], k - arr[i]]) return result
def _get_consecutive_sublists(list_): """ Groups list into sublists of consecutive numbers :param list_: input list to group :return cons_lists: list of lists with consecutive numbers """ # get upper bounds of consecutive sublists ubs = [x for x,y in zip(list_, list_[1:]) if y-x != 1] ...
def _ratsum(vals): """Reciprocal of the sum or the reciprocal. Suitable for composing speedups, etc. """ total = 0.0 num = 0 for v in vals: if v: total += v ** -1.0 num += 1 if num: return (total - (num - 1)) ** -1.0 else: return 0.0
def _cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ return (x > y) - (x < y)
def train_test_roll(array, tr_samples, te_samples, roll=None): """ Split arrays or matrices into rolling train and test subsets Parameters ---------- array : indexable Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas dataframes. tr_samples : int Number of ...
def pack_bits(bits): """converts bits to a byte-string""" num_bytes = len(bits) bits += [0] * (-num_bytes % 8) result = 0 for bit in bits: result <<= 1 if bit: result |= 1 return result.to_bytes(len(bits) // 8, "big")
def group_metrics(metrics): """Given signleton MetricData points, group them by metric name. Args: metrics (list of MetricData or None): each element is has a single point. Returns: dict: a mapping of metric names to the list of correspoinding MetricData. Skip entries that are None, but otherwise don...
def clean_dicts(dicts): """Removes tags from dict keys. The tags were necessary to identify uniquely a property if there is another one with the same name. Args: dicts (list of objs): List of dictionaries. Returns: list of obj: Cleaned list of dictionaries. """ for d in dicts:...
def get_loaded_default_monthly_consumption(consumption_dict, domain, product_id, location_type, case_id): """ Recreates the couch view logic to access the most specific consumption value available for the passed options """ keys = [ tuple([domain, product_id, None, case_id]), tuple([...
def circle_test_nah( p1,p2,p3,p4):#x1, y1, x2, y2, x3, y3, x4, y4): """ use Cramer's rule to solve the system of eqns to figure out vars, check out the Wikipedia entry on Cramer's rule """ x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] x3 = p3[0] y3 = p3[1] x4 ...
def is_downloadable(url: str) -> bool: """ Does the url is valid and contain a downloadable resource """ try: import requests h = requests.head(url, allow_redirects=True) header = h.headers content_type = header.get('content-type') if content_type and 'html' in co...
def shop(request): """ Add shop to context """ return {'shop': getattr(request, 'shop', None)}
def is_direct_image_link(url): """Return whether the url is a direct link to an image.""" image_extensions = ('jpg', 'jpeg', 'png', 'gif', 'apng', 'tiff', 'bmp') return url.rpartition('.')[-1].lower() in image_extensions
def is_successful_pass(event, next_event): """ check if a successuful pass """ if 'Not accurate' not in event['taglist'] and event['team'] == next_event['team']: return True return False
def convert_to_float(value): """Attempts to convert a string or a number < value > to a float. If unsuccessful or an exception is encountered returns the < value > unchanged. Note that this function will return True for boolean values, faux string boolean values (e.g., "true"), "NaN", exponential notati...
def commandify(module_path: str) -> str: """Transform an input string into a command name usable in a CLI.""" # foo.bar.this_key => this-key return module_path.split(".", 1)[-1].replace("_", "-").lower()
def argmin(y, x=None): """ Find the indices of minimal element in `y` given domain `x`. Example: ---------- >>> argmin([0, 2, 1, 4, 2], [1, 3, 4]) [1, 4] """ if x is None: x = range(len(y)) if len(x) <= 0: return [] m = min([y[i] for i in x]) return [i for i in x if y[i]...
def permutations(N): """Computes all the permutations of [0 ... n-1]""" def aux(elements): if len(elements) == 1: return [[elements.pop()]] perms = [] for x in elements: for perm in aux(elements - {x}): perms.append([x] + perm) return p...
def count_bits_set(field): """Count the number of bits set in an integer Discovered independently by: - Brian W. Kernighan (C Programming Language 2nd Ed.) - Peter Wegner (CACM 3 (1960), 322) - Derrick Lehmer (published in 1964 in a book edited by Beckenbach) Source: http://www-graphics...
def part_b(f, x, h): """Backward difference""" return (f(x) - f(x-h)) / h
def check_word(word): """ Returns True if word is correct and False if word is not correct """ if not word.isalpha(): print("Must enter a valid string containing only alphabetical characters!") return False elif word == '.': return False else: return True
def sum_of_squares(*nums: int) -> int: """Sum of the squares of `nums`.""" return sum(n * n for n in nums)
def escape_jboss_attribute_expression(text): """ Escapes text to make it safe for usage as value of JBoss configuration attribute which supports expression (https://docs.jboss.org/author/display/WFLY10/Expressions) """ if text is None: return text s = str(text) # https://github.com/...
def parser_IBP_Descriptor(data,i,length,end): """\ parser_IBP_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "IBP", "contents" : unparsed_descriptor_contents } (Defined in ISO 13818-1 specif...
def isEven(x): """ Returns True if number x is even :param x: :return: """ if x % 2 == 0: return True else: return False
def rotate90_augment(is_training=True, **kwargs): """Applies rotation by 90 degree.""" del kwargs if is_training: return [('rotate90', {})] return []
def num_corr(n): """ Returns how many cross spectra there are if there are n total maps. Arguments --------- n : int Number of maps. Returns ------- nxspec : int Number of cross spectra. """ return n * (n + 1) // 2
def jsonify(records): """ Parse asyncpg record response into JSON format """ return [dict(r.items()) for r in records]
def calculate_primes(limit): """ Calculates all primes <= limit. >>> calculate_primes(10) [2, 3, 5, 7] >>> calculate_primes(3) [2, 3] """ limit += 1 is_prime = [True]*limit is_prime[0] = False is_prime[1] = False primes = [] for i in range(2, limit): if n...
def threesumzero(a): """ Find triplets that sum to zero :param a: an array of integers to analyze :return: return unique triplets out of input array that sum to zero, an item in triplet may repeat at most twice """ result = set() # set to eliminate deuplicates! a.sort() # sort it n = le...
def multiply(value, amount): """ Converts to float and multiplies value. """ try: return float(value) * amount except ValueError: # If value can't be converted to float return value
def lists_differs(a: list, b: list) -> bool: """ Checks if a and b differs :param a: :param b: :return: """ a.sort() b.sort() return a != b
def perm_inverse(perm): """ Inverse permutation (raised to the power of -1) :param perm: Permutation in one-line notation :type perm: list :return: Returns inverse permutation :rtype: list """ inversed = [] for i in range(1, len(perm) + 1): inversed.append(perm.index(i) + 1...
def get_exact_right(slot_true, slot_pred): """Extract Ground Truth.""" import json for s, v in slot_true.items(): if s not in slot_pred: return False v = json.dumps(v) vp = json.dumps(slot_pred[s]) if v != vp: return False return True
def to_python(b): """Convert an AppleScript boolean string value into a Python Boolean""" return b.lower() in ("true", "yes", "1")
def prepare_payload_for_detail_commands(args): """ Prepares body (raw-json) for post API request. Use in 'risksense-get-host-detail", "risksense-get-app-detail" and "risksense-get-host-finding-detail" commands. :param args: Demisto argument provided by user :return: data in json format :rtype `...
def winning_combinations(player_state, current_winners): """ Returns a list of numbers that can be played which will give the player with player_state a certain winning combination. A certain winning combination is a combination wich has an intersection with at least two sets from cu...
def step(v, direction, step_size): """ move step-size in the direction from v """ return [v_i + step_size * direction_i for v_i, direction_i in zip(v,direction)]
def getEffectiveTimeOfScheduledJob(scheduledJobSid): """ parse out the effective time from the sid of a scheduled job if no effective time specified, then return None scheduledJobSid is of form: scheduler__<owner>__<namespace>_<hash>_at_<epoch seconds>_<mS> """ scheduledJobSidParts = scheduledJo...
def get_max_id(corpus): """ Return the highest feature id that appears in the corpus. For empty corpora (no features at all), return -1. """ maxid = -1 for document in corpus: maxid = max(maxid, max([-1] + [fieldid for fieldid, _ in document])) # [-1] to avoid exceptions from max(empt...
def _get_percent(text): """If text is formatted like '33.2%', remove the percent and convert to a float. Otherwise, just convert to a float. """ if not text: return None if text.endswith('%'): text = text[:-1] return float(text.strip())
def must_replace_suffix(str, suffix, replacement): """ Replaces the given suffix in the string. If the string does not have the suffix, a runtime error will be raised. """ splits = str.rsplit(suffix, maxsplit=1) if len(splits) != 2 or splits[1]: raise RuntimeError(str + " does not contai...
def want_bytes(s, charset='utf-8'): """ Returns *s* if it is a byte string specific to Python versions, else encodes it with the given *charset*. """ if isinstance(s, bytes): return s return s.encode(charset)
def cast_bytes(v, nbytes): """Cast byte(s) from v. Parameters ---------- v : int Value to be casted. nbytes : int Number of bytes will be casted. Returns ------- int Casted value. """ assert nbytes >= 1 and nbytes <= 8, \ "Invalid nbytes : {}".f...
def get_folder(folder_id, data): """Get data for a particular folder in parsed data.""" data_type = data.get('type') if data_type == 'folder': if data.get('uri', '').endswith(folder_id): return data for child in data.get('children', []): folder = get_folder(folder_id,...
def _string_to_int(s): """Converts the given `str` into `int`.""" return int(str(s), 0) if s else None
def cmpChrPosList(a,b): """ +1 if a > b -1 if a < b 0 if a == b """ chrA = a[0] chrB = b[0] posA = int(a[1]) posB = int(b[1]) if (chrA == chrB): if (posA == posB): return 0 if (posA < posB): return -1 if (posA > posB): return 1 if (chrA < chrB): ...
def _natural_int(value): """ Returns: int: Natural number, or None if value is zero. """ natint = int(value) if natint == 0: natint = None elif natint < 0: raise ValueError('invalid literal for natural int: {0}'.format(value)) return natint
def xml_type(val): """Return a type string for writing to an XML file. Parameters ---------- val : any type The value Returns ------- type : str The type of the value to insert in the XML file """ try: return {str: 'string', int: 'int', ...
def prompt(question, aid="", default=""): """Constructs question prompt.""" if aid: return f"{question.rstrip('?')}? ({aid}) [{default}] " return f"{question.rstrip('?')}? [{default}] "
def convert_none_to_null_in_tuples(data): """data is an array of tuples""" modified_data = [] for t in data: new_t = t for idx in range(len(new_t)): if t[idx] == None: new_t = new_t[0:idx] + ("NULL",) + new_t[idx+1:] modified_data.append(new_t) return ...
def _call_member(obj, name, args=None, failfast=True): """ Calls the specified method, property or attribute of the given object Parameters ---------- obj : object The object that will be used name : str Name of method, property or attribute args : dict, optional, default=None ...
def capitalize(word): """Capitalize the first character in the word (without lowercasing the rest).""" return word[0].capitalize() + word[1:]
def formatSize(size_bytes): """ Get human readable size from number of bytes. Args: size_bytes (str): Size in number of bytes. Can be string or int. """ readable_size = int(size_bytes) if readable_size < 1024: return '%d Bytes' % (readable_size) for prefix in ['', 'Ki', 'Mi',...
def dict_from_items_with_values(*dictionaries, **items): """Creates a dict with the inputted items; pruning any that are `None`. Args: *dictionaries(dict): Dictionaries of items to be pruned and included. **items: Items to be pruned and included. Returns: dict: A dictionary contain...
def parse_alignment(alignment): """ Parses an alignment string. Alignment strings are composed of space separated graphemes, with optional parentheses for suppressed or non-mandatory material. The material between parentheses is kept. Parameters ---------- alignment : str The a...
def blurb(bio): """ Returns champion blurb which cuts off around 250 characters """ if " " not in bio: return bio bio = bio[0:254] bio = ' '.join(bio.split(' ')[:-1]) try: if bio[-1] == ",": bio = bio[:-1] except Exception: print(bio) return bio + ...
def combine_aggregations(data_object): """ data_object must return a list of dicts or must be a iterable object (for example a generator) with the name of the the type of data for example "Session" or "Visitors" and a dict with the url data for example [{ "type": "Session" "data": { "/ajaja": 13 ...
def parse_into_action(up, left, right): """Parse into all the possible actions that the user can make""" return 0 if up and left and not right else \ 1 if up and not left and right else \ 2 if up and not left and not right else \ 3 if not up and left and not right else \ ...
def aic(llf, nobs, df_modelwc): """ Akaike information criterion Parameters ---------- llf : {float, array_like} value of the loglikelihood nobs : int number of observations df_modelwc : int number of parameters including constant Returns ------- aic : f...
def cm2pt(*tupl): """Convert values from cm to pt. Args: *Args: A tuple with values to convert Returns: A tuple with values converted """ if isinstance(tupl[0], tuple): return tuple(i*28.346 for i in tupl[0]) else: return tuple(i*28.346 for i in tupl)