content
stringlengths
42
6.51k
def unique_ordered_union(x, y): """ Returns a list containing the union of 'x' and 'y', preserving order and removing duplicates. """ return list(dict.fromkeys(list(x) + list(y)).keys())
def safe_int(str_value: str, base: int=10): """Always returns integer value from string/None argument. Returns 0 if argument is None. """ if str_value: return int(str_value, base) else: return 0
def epoch_to_timestamp(records): """ Convert epoch timestamps to ISO 8601 (2015-01-04T09:30:21Z) :param records: List (of dictionaries) :return: List (of dictionaries) """ from datetime import datetime for record in records: timestamp_keys = ["time_first", "time_last"] for...
def jsonize_phrase_dict(phrase_dict, val_string='frequency', term_to_str_fn=lambda tpl: ' '.join(tpl)): """Input: a dictionary of string tuples to values. Val: a dictionary of strings to values, where tuples have been separated by spaces""" return [{'term':term_to_str_fn(term), val_string:val} ...
def get_quote_style(str): """find which quote is the outer one, ' or ".""" quote_char = None at = None found = str.find("'") found2 = str.find('"') # If found == found2, both must be -1, so nothing was found. if found != found2: # If a quote was found if found >= 0 and found2 >= 0: # If bo...
def is_list_of_str_or_int(value): """ Check if an object is a string or an integer :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, (int, str)) for elem in value)
def extract_spreadsheet_id(string): """Extracts the sprreadsheet id from an url.""" if "/edit" in string: string = string.split("/edit")[0] if "/" in string: string = string.rstrip("/") string = string.split("/")[-1] string = string.split("&")[0] string = stri...
def LowerCamelCase(value): """Turns some_string or SOME_STRING into someString.""" split_value = value.lower().split('_') result = [split_value[0]] + [part.capitalize() for part in split_value[1:]] return ''.join(result)
def get_features_for_type(column_type): """ Get features to be generated for a type """ # First get the look up table lookup_table = dict() # Features for type str_eq_1w lookup_table['STR_EQ_1W'] = [('lev_dist'), ('lev_sim'), ('jaro'), ('jaro_winkler'), ...
def get_message(data): """ Method to extract message id from telegram request. """ message_text = data['message']['text'] return message_text
def int_or_none(s): """ >>> int_or_none('') None >>> int_or_none('10') 10 """ return None if not s else int(s)
def space_newline_fix(text): """Replace "space-newline" with "newline". Args: text (str): The string to work with Returns: The text with the appropriate fix. """ space_newline = ' \n' fix = '\n' while space_newline in text: text = text.replace(space_newline, fix) ...
def _extended_gcd(a, b): """ Division in integers modulus p means finding the inverse of the denominator modulo p and then multiplying the numerator by this inverse (Note: inverse of A is B such that A*B % p == 1) this can be computed via extended Euclidean algorithm http://en.wikipedia.or...
def CTAMARS_radii(camera_name): """Radii of the cameras as defined in CTA-MARS. These values are defined in the code of CTA-MARS. They correspond to the radius of an equivalent FOV covering the same solid angle. Parameters ---------- camera_name : str Name of the camera. Retur...
def find_dividend_by_unit(time): """Finds whether time best corresponds to a value in days, hours, minutes, or seconds. """ for dividend in [86400, 3600, 60]: div = time / dividend if round(div) == div: return dividend return 1
def is_valid_ssn(x): """Validates that the field is 3 digits, a hyphen, 2 digits, a hyphen, and 4 final digits only.""" return True # speed up testing valid_ssn=re.compile(r'^\d{3}-\d{2}-\d{4}$') if not bool(re.match(valid_ssn,x)): validation_error("Write the Social Security Number like thi...
def merge(line): """ Function that merges a single row or column in 2048. """ new_line = [x for x in line if x !=0] while len(new_line) < len(line): new_line.append(0) for ind in range(len(new_line)-1): if new_line[ind] == new_line[ind+1]: new_line[ind] *= 2 ...
def get_bigram_data(bigram_dict, combinations_list): """ Transforms a count dictionary in an ordered feature vector. Parameters: bigram_dict : dict with a combinations count combinations : list of tuples, where each tuple is a combination of two contact types (s...
def is_color_similar(color1, color2, overlap=0.05): """Checks if colors are similar. :param tuple[int, int, int] color1: original color. :param tuple[int, int, int] color2: color to check. :param float overlap: overlap parameter. If colors similarity > overlap then colors are similar. :rtype: bool...
def uniq(a): """ Removes duplicates from a list. Elements are ordered by the original order of their first occurrences. In terms of Python 2.4 and later, this is equivalent to list(set(a)). """ if len(a) == 0: return [] else: return [a[0]] + uniq([x for x in a if x != a[0]])
def is_valid_run_name(run_name): """ Checks the validity of the run_name. run_name cannot have spaces or colons. :param run_name: <class str> provided run_name. :return: <bool> True if valid False if not. """ return run_name and not (' ' in run_name or ':' in run_name)
def paginate(page): """ Render a pagination block with appropriate links, based on the given Django Page object. """ context = { 'page': page } return context
def min_ten_neg(x, thresh, fallback): """Returns 10**-x, or `fallback` if it doesn't meet the threshold. Note, if you want to turn a hyper "off" below, set it to "outside the threshold", rather than 0. """ x = 10**-x return x if (x and x > thresh) else fallback
def find_area(coords): """Find area of a box when given the box corners in a tuple""" return (coords[1] - coords[0]) * (coords[3] - coords[2])
def to_n_grams(message): """ Break the text into 5-character chunks.""" # Pad the message in case its length isn't a multiple of 5. message += " " # Create the 5-character chunks. result = "" for i in range(0, len(message) - 5, 5): result += message[i: i + 5] + " " # ...
def like(matchlist: list, array: list, andop=False): """Returns a list of matches in the given array by doing a comparison of each object with the values given to the matchlist parameter. Examples: >>> subdir_list = ['get_random.py', ... 'day6_15_payload-by-port.py', ... 'worksheet_ge...
def getminby2index(inputlist,index1,index2): """can get PIF calcs using flox data and crossvals note that cross ref of indexlist with Ti vs Te timestamps is needed for segregation of the data """ minbyindexlist=[min( inputlist[index1[i]:index2[i]] ) fo...
def get_transfer_dict_cmd(server_from_str, server_to_str, folders_str): """ Convert command line options to transfer dictionary Args: server_from_str (str): counter to iterate over environment variables server_to_str (str): Environment variables from os.environ folders_str (str) ...
def extractdate(id): """Pulls date in form YYYMMDD from id""" date = id[1:9] return int(date)
def running(demo_mode, step, max_step): """ Returns whether the demo should continue to run or not. If demo_mode is set to true, the demo should run indefinitely, so the function returns true. Otherwise, the function returns true only if step <= max_step :param demo_mode: true if running in demo mod...
def even(text) -> str: """ Get Even-numbered characters. :param str text: String to convert. :rtype: str :return: String combining even-numbered characters. """ return text[1::2]
def convert_default(*args, **kwargs): """ Handle converter type "default" :param args: :param kwargs: :return: return schema dict """ schema = {'type': 'string'} return schema
def rgb_to_rgba(rgb): """ Convert a tuple or list containing an rgb value to a tuple containing an rgba value. rgb : tuple or list of ints or floats ([r, g, b]) """ r = rgb[0] / 255 g = rgb[1] / 255 b = rgb[2] / 255 return r, g, b
def get_bits(n, start, end): """Return value of bits [<start>:<end>] of <n>""" return (int(n) & ((1 << end) - 1)) >> start
def subscribers(object_type: str) -> str: """Key for list of subscribers to specified object type.""" return 'events:{}:subscribers'.format(object_type)
def ipv4_mask_to_net_prefix(mask): """Convert an ipv4 netmask into a network prefix length. If the input is already an integer or a string representation of an integer, then int(mask) will be returned. "255.255.255.0" => 24 str(24) => 24 "24" => 24 """ if isi...
def commafy( number ): ############################################################ """commafy(number) - add commas to a number""" import re return re.sub(r'(\d{3})(?=\d)',r'\1,' ,str(number)[::-1])[::-1]
def chunkIt(seq, num): """ **Chunks a list into a partition of specified size.** + param **seq**: sequence to be chunked, dtype `list`. + param **num**: number of chunks, dtype `int`. + return **out**: chunked list, dtype `list`. """ out = [] last = 0.0 while last < len(seq): ...
def get_ages_at_death(employees): """ Calculate approximate age at death for employees Assumes that they have a birth year and death year filled """ return list(map(lambda x: x.age_at_death(), employees))
def make_experiment_dir_name(max_model_size, experiment_name): """Return name of directory for results of given settings (only depends on model size) and experiment name""" if experiment_name is not None: return f"Experiment={experiment_name}-max_model_size={max_model_size}" else: re...
def is_archived(filename, suffixes): """ """ return any(filename.endswith(s) for s in suffixes)
def _inters(orig, new): """Make the interaction of two sets. If the original is a None value, a new set will be created with elements from the new set. When both operands are None, the result is None. """ if orig is None: return new elif new is None: return orig else: ...
def calc_new_value(old_measure, new_measure, count): """ Factor the total count in to the difference of the new value. E.g. for a value of 100ms with 50 measurements, a new measure of 150ms would add 1 ms to the total """ return (old_measure + (old_measure + (new_measure - old_measure) * (1.0 / coun...
def join_models(model1, model2): """ Concatenate two SDD models. Assumes that both dictionaries do not share keys. """ model = model1.copy() model.update(model2) return model
def filter_out_black(list_of_pixels): """ Takes a 1-d list of pixels and filters out the very dark pixels. Returns the list of non-dark pixels """ return [pixel for pixel in list_of_pixels if max(pixel) > 0.1]
def _nd4j_datatype_from_np(np_datatype_name): """ :param np_datatype_name: a numpy data type name. 1 of: float64 float32 float16 :return: the equivalent nd4j data type name (double,float,half) """ if np_datatype_name == 'float64': return 'double' elif np_datatype_nam...
def lower_words(iterable): """ turn all words in `iterable` to lower """ return [w.lower() for w in iterable]
def call_aside(f, *args, **kwargs): """ Call a function for its side effect after initialization. >>> @call_aside ... def func(): print("called") called >>> func() called Use functools.partial to pass parameters to the initial call >>> @functools.partial(call_aside, name='bingo') ... def func(name): print(...
def distance(a, b): """ distance computes the Manhattan distance between a and b where a and b are either tuples (x,y) or dicts {'x':_, 'y':_} """ if not isinstance(a, tuple): a = (a['x'], a['y']) if not isinstance(b, tuple): b = (b['x'], b['y']) return abs(a[0] - b[0]) +...
def file_exists (filename): """ Determine if a file with the given name exists in the current directory and can be opened for reading. Returns: True iff it exists and can be opened, False otherwise. :param filename: Filename to check. :return True if file exists. """ try: ...
def remove_dup2(a): """ remove dup in sorted array without using another array """ n = len(a) j = 0 print("before removing -- ", a ) for i in range(0, n-1): if a[i] != a[i+1]: a[j] = a[i] j = j+ 1 a[j] = a[n-1] print("after removing -- ", a ) return a[0: j+1]
def detokenize(sent): """ Roughly detokenizes (mainly undoes wordpiece) """ new_sent = [] for i, tok in enumerate(sent): if tok.startswith("##"): new_sent[len(new_sent) - 1] = new_sent[len(new_sent) - 1] + tok[2:] else: new_sent.append(tok) return new_sent
def box_lengths(dimensions): """Return list of dimension ints""" return sorted([int(i) for i in dimensions.split('x')])
def get_snr(snr_min, emission_line, default=3): """Convenience function to get the minimum SNR for a certain emission line. If ``snr_min`` is a dictionary and ``emision_line`` is one of the keys, returns that value. If the emission line is not included in the dictionary, returns ``default``. If ``snr_m...
def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longe...
def _multihex (blob): """Prepare a hex dump of binary data, given in any common form including [[str]], [[list]], [[bytes]], or [[bytearray]].""" return ' '.join(['%02X' % b for b in bytearray(blob)])
def zeroOut(data): """ """ # Convert empty strings to zeros. cols = len(data[0]) data = [0 if col == '' else col for row in data for col in row] data = [data[y : y + cols] for y in range(0, len(data), cols)] return data
def capitalizeEachWord(original_str): """ ORIGINAL_STR of type string, will return each word of string with the first letter of each word capitalized """ result = "" # Split the string and get all words in a list list_of_words = original_str.split() # Iterate over all elements in list fo...
def getNameIndex(name): """For Cylinder.001 returns int 1""" try: location = len(name) - "".join(reversed(name)).index(".") index = int(name[location:]) except Exception: index = 0 return index
def get_r_list(area1, area2, max_area, tol=0.02): """ returns a list of r1 and r2 values that satisfies: r1/r2 = area2/area1 with the constraints: r1 <= Area_max/area1 and r2 <= Area_max/area2 r1 and r2 corresponds to the supercell sizes of the 2 interfaces that align them """ r_list = [...
def escape_birdiescript(s): """Escape a Birdiescript string.""" return s.replace('\\', '\\\\').replace('`', '\\`')
def takeInputAsList(molecule_name): """ This function converts the user given molecule names separated by semicolon into a list of string INPUT: molecule_name(Molecule names in semicolon separated format. Example: Methane;Methanol;Ethane) OUTPUT: molecule_names(Molecule names in list of string forma...
def serialize(obj): """JSON serializer for objects not serializable by default json code """ if getattr(obj, '__dict__', False): return obj.__dict__ return str(obj)
def get_edges_by_source_id(edges, source_id): """ Get the edges from the specified source. :param edges: Input edges. :param source_id: Id of the source. :return: List of edges """ res = [] for edge in edges: if edge.source == source_id: res.append(edge) return re...
def convert_repr_number (number): """ Helper function to convert a string representation back to a number. Assumptions: * It may have a thousand separator * It may have a decimal point * If it has a thousand separator then it will have a decimal point It will retur...
def least_significan_bit(n): """Least significant bit of a number num AND -num = LSB Args: n ([type]): [description] Raises: TypeError: [description] Returns: [type]: [description] """ if type(n) != int: raise TypeError("Number must be Integer.") if...
def toTableFormat(filteredStatDict): """ Format the filtered statistic dict into list that can be displayed into QT table arg : - filteredStatDict (dict): the dict to format return : list """ tableFormat = [] totalOccur = sum(occur for word, occur in filteredStatDict...
def are_islands_sorted(island_list): """ Check if sorted in ascending order. input is a list of BED with chrom, start, end and value. output: sorted =1 or 0 """ sorted = 1; for index in range(0, len(island_list)-1): if island_list[index].start> island_list[index+1].start: sorted = 0; return sorted;
def identify_significant_pairs(list_pairs): """Takes in a a list of lists, which include the pairs and the third element of each list is L.O.S. Args: list_pairs (list of lists): First element is crypto pair 1, second element crypto pair 2 and third element is L.O.S. """ return [x for x in list_...
def split(n): """Splits a positive integer into all but its last digit and its last digit.""" return n // 10, n % 10
def content_type(content_type="application/json"): """Construct header with content type declaration for the server API calls. Returned dict can be added to the 'request' object. """ return {'Content-type': content_type}
def decode_bytes(obj): """If the argument is bytes, decode it. :param Object obj: A string or byte object :return: A string representation of obj :rtype: str """ if isinstance(obj, bytes): return obj.decode('utf-8') elif isinstance(obj, str): return obj else: ra...
def value_to_HSL(value): """ Convert a value ranging from 0 to 100 into a color ranging from red to green using the HSL colorspace. Args: value (int): integer betwee 0-100 to be converted. Returns: Tuple[int]: hue, saturation and lightnes corresponding to the converted value. ...
def check_games(games): """Check that every player does not come in 1st and does not come in last at least once each.""" pc = dict() for game in games: max_rank = 0 max_user = None for user, rank in game.items(): if rank > 1: pc.setdefault(user, [1, 1]...
def fix_image_ids(data): """ LabelBox uses strings for image ids which don't work with the coco API (which is used inside of torchvision CocoDetection dataset class """ img_ids = dict() for i, img_data in enumerate(data['images']): id = img_data['id'] # Create lookup table ...
def _conv_year(s): """Interpret a two-digit year string.""" if isinstance(s, int): return s y = int(s) return y + (1900 if y >= 57 else 2000)
def multiple_split(source_string, separators, split_by = '\n'): """ This function allows the user to split a string by using different separators. Note: This version is faster than using the (s)re.split method (I tested it with timeit). Parameters: * source_string: string to be splitted * separators:...
def is_num_present(word): """ Check if any number present in Given String params: word - string returns: 0 or 1 """ check = any(letter.isdigit() for letter in word) return 1 if check else 0
def message(operation, type, resource, raw_resource, execution_time, status): """ :summary: Concats the supplied parameters and returns them in trace format :param operation: Operation (MySQL/ Mongo/ ES/ API/ etc) :param type: Type of the Operation (SELECT/ GET/ POST/ etc) :param resource: URL / Que...
def commonMember(a, b): """ Return True if two list have at least an element in common, False otherwise """ a_set = set(a) b_set = set(b) if (a_set & b_set): return True else: return False
def search_active_words(subject, active_words): """ This method looks for active_words in subject in a case-insensitive fashion Parameters ---------- subject: string, required email subject active_words: string, required active words represented in a comma delimited fashion ...
def test_for_long_cell(raw_python_source: str) -> bool: """ Returns True if the text "# Long" is in the first line of `raw_python_source`. False otherwise. """ first_element = raw_python_source.split("\n")[0] if "#" in first_element and "long" in first_element.lower(): return True re...
def qual_stat(qstr): """ Modified to calculate average quality score of a sequence """ q30_sum = 0 q30_seq = 0 # q30 = 0 for q in qstr: # qual = ord(q) - 33 qual = q - 33 q30_sum += qual # if qual >= 30: # q30 += 1 q30_seq = q30_sum/len(qstr) retur...
def guess_game_name_from_clone_arg(clone_arg: str) -> str: """Guess the name of the game from the --clone argument. :arg clone_arg: The str given by the user for the clone argument. Usually a git link as `https://github.com/ScienceGamez/world-3.git`.. """ if "/" in clone_arg: # If u...
def experience_boost_determination(ability_scores, prime_ability): """ This function determines any applicable experience boost. Assumes abilities is a list of tuples (ability as str, stat as int) Assumes prime_ability is a string. Returns a percentage as a str. """ abilities = ['Strength', ...
def clean_uid(uid): """ Return a uid with all unacceptable characters replaced with underscores """ if not hasattr(uid, 'replace'): return clean_uid(str(uid.astype('S'))) try: return uid.decode('utf-8').replace(u"/", u"_").replace(u":", u"_") except AttributeError: return...
def get_indent(line): """Helper function for getting length of indent for line. Args: line (str): The line to check. Returns: int: The length of the indent """ for idx, char in enumerate(line): if not char.isspace(): return idx return len(line)
def default_params(fun_kwargs, default_dict=None, **kwargs): """Add to kwargs and/or default_dict the values of fun_kwargs. This function allows the user to overwrite default values of some parameters. For example, in the next example the user cannot give a value to the param `a` because you will b...
def digit(decimal, digit, input_base=10): """ Find the value of an integer at a specific digit when represented in a particular base. Args: decimal(int): A number represented in base 10 (positive integer). digit(int): The digit to find where zero is the first, lowest, digit. ...
def dest_file(file_name): """ "Add.asm" -> "Add.hack" """ naked = file_name.rsplit('.', 1)[0] return naked + '.hack'
def flatten(seq): """ Returns a list of the contents of seq with sublists and tuples "exploded". The resulting list does not contain any sequences, and all inner sequences are exploded. For example: >>> flatten([7,(6,[5,4],3),2,1]) [7, 6, 5, 4, 3, 2, 1] """ lst = [] for e...
def _FunctionSelector(population, N, samples, stdFunction, sampleFunction, baseParams): """Fitness function that determines on the fly whether to use a sampling algorithm or not. """ L = len(population) combinations = L**N if samples < 1.0: samples = int(combinations*sampl...
def conjugate_row(row, K): """ Returns the conjugate of a row element-wise Examples ======== >>> from sympy.matrices.densetools import conjugate_row >>> from sympy import ZZ >>> a = [ZZ(3), ZZ(2), ZZ(6)] >>> conjugate_row(a, ZZ) [3, 2, 6] """ result = [] for r in row: ...
def partial_difference_quotient(f, v, i, h): """ compute the ith partial difference quotient of f at v """ w = [v_j + (h if j == i else 0) # add h to just the ith element of v for j, v_j in enumerate(v)] return (f(w) - f(v)) / h
def determina_putere(n): """ Determina ce putere a lui 2 este prima cea mai mare decat n :param (int) n: numarul de IP-uri necesare citit de la tastatura :return (int) putere: puterea lui 2 potrivita """ putere = 1 while 2**putere < n+2: putere += 1 ...
def calcbw(K, N, srate): """Calculate the bandwidth given K.""" return float(K + 1) * srate / N
def _is_repeating(password): """ Check if there is any 2 characters repeating consecutively """ n = 1 while n < len(password): if password[n] == password[n-1]: return True n += 1 return False
def print_summarylist(tags, vals): """ Prints a nice one-line listing of tags and their values in a nice format that corresponds to how the DIGITS regex reads it. Args: tags: an array of tags vals: an array of values Returns: print_list: a string containing formatted tags and val...
def exceptions_equal(exception1, exception2): """Returns True if the exceptions have the same type and message""" # pylint: disable=unidiomatic-typecheck return type(exception1) == type(exception2) and str(exception1) == str(exception2)
def merge_pnslots(pns1, pns2): """ Takes two sets of pronoun slots and merges them such that the result is valid for text that might follow text which resulted in either of the merged slot sets. """ result = {} for pn in pns1: if pns1[pn][1] == pns2[pn][1]: result[pn] = [max(pns1[pn][0], pns2[pn...