content
stringlengths
42
6.51k
def _check_remove_item(the_list, item): """Helper function for merge_lists that implements checking wether an items should be removed from the list and doing so if needed. Returns ``True`` if the item has been removed and ``False`` otherwise.""" if not isinstance(item, str): return False if ...
def _shorten(s, n=100): """Shorten string s to at most n characters, appending "..." if necessary.""" if s is None: return None if len(s) > n: s = s[:n-3] + '...' return s
def convert_bool_str(input_string): """ Helper to convert a string representation of a boolean to a real bool(tm). """ if input_string.lower() in ('1', 'true'): return True return False
def slice_nested(l, slice_pos, slice_size): """ Slice the nested list :param l: a nested list :param slice_pos: a 2-tuple (x, y) of slice start :param slice_size: a 2-tuple (width, height) of slice size """ r = [] for y in range(slice_pos[1], slice_pos[1] + slice_size[1]): lin...
def clean_mentions(msg): """Prevent discord mentions""" return msg.replace("@", "@\u200b")
def dec(val, encoding='utf-8'): """ Decode given bytes using the specified encoding. """ import sys if isinstance(val, bytes) and sys.version_info > (3, 0): val = val.decode(encoding) return val
def isGColRequired(config, num): """A quick helper function that checks whether we need to bother reading the g1,g2 columns. It checks the config dict for the output file names gg_file_name, ng_file_name (only if num == 1), etc. If the output files indicate that we don't need the g1/g2 columns, then w...
def urandom(num_bytes): """ urandom returns a bytes object with n random bytes generated by the hardware random number generator. """ import os return os.urandom(num_bytes)
def multi_bracket_validation(input_str): """this function take in a string and return a value true or false base on if the brackets are balance or not Args: input_str ([type]): [description] Returns: [type]: [description] """ #checks a base case to reduce computing where not n...
def _apply_presets(preset_dict, *args, **kwargs): """ Pair with `unpack` to alter input arguments with preset values. """ if 'presets' in kwargs: presets = kwargs['presets'] if presets is None: return kwargs if not isinstance(presets, list): presets = [pre...
def sqlite_table_foreign_keys(c=None, table=None): """ """ db_fk = [] if c is not None and table is not None: c.execute('PRAGMA foreign_key_list({0})'.format(table)) rows = c.fetchall() for r in rows: db_fk.append(r) return db_fk
def _jobpair_satisfies_filters(jp, failed_job_id, passed_job_id): """ Not currently used. True if the jobpair meets the filters indicated by the presence of the -p and -f arguments. """ # Always include if no job ID filters provided. if not failed_job_id and not passed_job_id: return Tru...
def create_ib_tuple(instrument): """ create ib contract tuple """ # tuples without strike/right if len(instrument) <= 7: instrument_list = list(instrument) if len(instrument_list) < 3: instrument_list.append("SMART") if len(instrument_list) < 4: instrument_li...
def hostport(scheme, host, port): """ Returns the host component, with a port specifcation if needed. """ if (port, scheme) in [(80, "http"), (443, "https")]: return host else: return "%s:%s"%(host, port)
def read_file(filename, alt=None): """ Read the contents of filename or give an alternative result instead. """ lines = None try: with open(filename, encoding='utf-8') as f: lines = f.read() except IOError: lines = [] if alt is None else alt return lines
def path_to_module_format(py_path): """Transform a python file path to module format.""" return py_path.replace("/", ".").rstrip(".py")
def index_to_feature(p, dims): """convert index form (single integer) to feature form (vector)""" feature = [] for dim in dims: feature.append(p % dim) p //= dim return feature
def max_number(number: int) -> int: """Returns number starting from the largest item. Args: number (int): input number Examples: >>> assert max_number(132) == 321 """ return int("".join(sorted(tuple(str(number)), reverse=True)))
def error(text, error_code): """Returns the error in json format Keyword arguments: text -- Human readable text for the error error_code -- http status code """ return '{{"Error": "{}"}}'.format(text), error_code
def reader_filepath(sample, filename, pathfunc): """ Construct filepath from sample, filename and/or pathfunction. Helper function used in ReadImage and ReadNumpy. :param tuple|list sample: E.g. ('nut_color', 1) :param filename: :param string|function|None pathfunc: Filepath with wildcard '*',...
def get_unscanned_account_error(graph_dict): """Returns the error message stored in the graph dictionary generated by Altimeter as the result of getting an error trying to scan one account.""" vertices = graph_dict["vertices"] for v in vertices: if v["~label"] == "error" and "error" in v: ...
def rivers_with_stations(stations): """Get names of rivers with an associated monitoring station. Parameters ---------- stations : list[MonitoringStation] generated using build_station_list. Returns ------- output : set A set containing the names of all the rivers with a mo...
def fib(n): """ :param n: :return: """ if n == 1 or n == 2: return 1 n1 = n - 1 n2 = n - 2 fibr1 = fib(n1) fibr2 = fib(n2) res = fibr1 + fibr2 return res
def square_matrix(square): """ This function will calculate the value x (i.e. blurred pixel value) for each 3 * 3 blur image. """ tot_sum = 0 # Calculate sum of all the pixels in 3 * 3 matrix for i in range(3): for j in range(3): tot_sum += square[i][j] ...
def qr_to_cube(p): """Convert axial coordinates to cube in q-type hexagonal grid.""" q, r = p x, y, z = q, -q-r, r return x, y, z
def filename_to_domain(filename): """[:-4] for the .txt at end """ return filename.replace('-', '/')[:-4]
def _join_package_name(ns, name): """ Returns a app-name in the 'namespace/name' format. """ return "%s/%s" % (ns, name)
def bytes_to_hex_str(data): """ converts a sequence of bytes into its displayable hex representation, ie: 0x?????? :param data: byte sequence :return: Hexadecimal displayable representation """ return "0x" + "".join(format(b, "02x") for b in data)
def inrange(value, bits): """ Test if a signed value can be fit into the given number of bits """ upper_limit = 1 << (bits - 1) lower_limit = -(1 << (bits - 1)) return value in range(lower_limit, upper_limit)
def serialise_matched_reference(data, current_timestamp): """Serialise the data matched by the model.""" serialised_data = { 'publication_id': data['WT_Ref_Id'], 'cosine_similarity': data['Cosine_Similarity'], 'datetime_creation': current_timestamp, 'document_hash': data['Documen...
def mySqrt(x): """ :type x: int :rtype: int """ if x < 2: return x i = round(x / 2) prev = x keep_looping = True while keep_looping: test = i * i if test == x: break if (prev * prev) < x and test > x: i = prev break ...
def invperm(perm): """Returns the inverse permutation.""" inverse = [0] * len(perm) for i, p in enumerate(perm): inverse[p] = i return inverse
def parse_args(given, control): """checks if some of the given args are valid for a condition""" pairs = [(x, y) for x in given for y in control] for g, c in pairs: if g == c: return True return False
def parse_score_qa(output, metric, digits=4): """Function for parsing the output from `pyserini.eval.evaluate_dpr_retrieval`. Currently, the implementation is the same as `parse_score_msmacro`, but we're keeping separate in case they diverge in the future.""" for line in output.split('\n'): if me...
def return_characters(data: bytes) -> bytes: """ Characters that are used for telegram control are replaced with others so that it is easier to parse the message over the wire. Final character is never replaced. This function returns them to their original form. '\x1b\x0e' -> '\x0d' '\x1b\x...
def last_delta(x): """difference between 2 last elements""" return x[-1]-x[-2]
def is_odd(x: int) -> bool: """ ARGS: integer RETURNS: true if integer is odd """ if x % 2 == 0: return False else: return True
def prepare_data(song: dict) -> dict: """ Prepares song dataa for database insertion to cut down on duplicates :param song: Song data :return: The song data """ song['artist'] = song['artist'].upper().strip() song['title'] = song['title'].upper().strip() return song
def optional_f(text): """Method for parsing an 'optional' generalized float.""" if text: return float(text) else: return None
def get_rule_bypass_line(rule_id): """ Get the coniguration line to use to bypass a ModSecurity rule. Args: rule_id - The numerical id of the ModSecurity rule """ return "SecRuleRemoveById " + rule_id
def _escape_filename(filename): """Escapes spaces in the given filename, Unix-style.""" return filename.replace(" ", "\\ ")
def _escape(value): """ This function prevents header values from corrupting the request, a newline in the file name parameter makes form-data request unreadable for majority of parsers. """ if not isinstance(value, (bytes, str)): value = str(value) if isinstance(value, bytes): ...
def info_header(label): """Make a nice header string.""" return "--{:-<60s}".format(" "+label+" ")
def get_label_map(label_list): """ Create label maps """ label_map = {} for (i, l) in enumerate(label_list): label_map[l] = i return label_map
def return_first_list_present_only(xs, ys): """ merge sorted lists xs and ys. Return a sorted result """ result = [] xi = 0 yi = 0 while True: if xi >= len(xs): return result if yi >= len(ys): result.append(xs[yi:]) return result if xs[x...
def normalize_path(path): """normalize path """ path = path.strip('/') return '/' + path
def format_duration(duration): """Given a duration in minutes, return a string on the format h:mm. >>> format_duration(75) '1:15' >>> format_duration(4) '0:04' >>> format_duration(601) '10:01' """ h = duration // 60 m = duration % 60 return f"{h}:{m:02}"
def clname_from_lastchar_cb(full_path): """Callback for changelist_all_files() that returns a changelist name matching the last character in the file's name. For example, after running this on a greek tree where every file has some text modification, 'svn status' shows: --- Changelist 'a': M A/B/...
def data_gen(list_length): """ >>> data_gen(3) {'numbers_list': [0, 1, 2]} >>> data_gen(7) {'numbers_list': [0, 1, 2, 3, 4, 5, 6]} """ numbers_list = [number for number in range(list_length)] return {"numbers_list" : numbers_list}
def getid(obj): """ Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ try: return obj.id except AttributeError: return obj
def _patch_header(header, ebcdic=False): """ Helper function to patch a textual header to include the revision number and the end header mark. """ revnum = "C39 SEG Y REV1" if ebcdic: revnum = revnum.encode("EBCDIC-CP-BE") end_header = "C40 END EBCDIC ".encode("EBCDIC-CP-...
def DES3028(v): """ DES-3028-series :param v: :return: """ return v["platform"].startswith("DES-3028")
def getstorypoint(title): """Function that will get in the title the first characters as storypoints :param title: Card title :return: """ tmp = "" for l in title: if l in [".", ",", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]: tmp += l else: b...
def fahrenheitToRankie(fahrenheit:float, ndigits = 2)->float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale """ return round(flo...
def container_elem_type(container_type, params): """ Returns container element type :param container_type: :param params: :return: """ elem_type = params[0] if params else None if elem_type is None: elem_type = container_type.ELEM_TYPE return elem_type
def is_module_available(module_name): """Return True if Python module is available""" try: __import__(module_name) return True except ImportError: return False
def p(text: str) -> str: """Wrap text into an HTML `p` tag.""" return f"<p>{text}</p>"
def append_unless(unless, base, appendable): """ Conditionally append one object to another. Currently the intended usage is for strings. :param unless: a value of base for which should not append (and return as is) :param base: the base value to which append :param appendable: the value to append t...
def typed_line(line, parser): """Parse one line of the dataset into a typed (user, item, rating) triplet.""" user, item, rating = parser(line) return int(user), int(item), float(rating)
def check_miss_numbers(number_string: str) -> list: """[summary] Args: number_string (str): [Phone Number For Cheack] Returns: list: [The Mising Numbers In Phone Numbers] """ miss_numbers = [] orginals_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers = [int(i) for i in numb...
def get_larger_channel(channel_range, channel_num): """ get channels which is larger than inputs :param channel_range: list,channel range :param channel_num: input channel :return: list,channels which is larger than inputs """ result = filter(lambda x: x >= channel_num, channel_range) r...
def clamp(val, min, max): """ Clamps values that are too high or too low to the min or max """ if val > max: val = max elif val < min: val = min return val
def find_period(samples_second): """ # Find Period Args: samples_second (int): number of samples per second Returns: float: samples per period divided by samples per second """ samples_period = 4 return samples_period / samples_second
def get_ranges_or_indices_in_name(name): """ recursive function that eventually collects all the list ranges/list indices in the specified component name""" exisiting_ranges = [] start_idx = name.find('[') end_idx = name.find(']') range = name[start_idx + 1: end_idx] if '..' in range: r...
def aws_ok(resp): """ Return true if response status is ok """ if resp['ResponseMetadata']['HTTPStatusCode'] == 200: return True return False
def while_lower_bound(lower): """ t_while """ rval = lower while rval < 100: rval = rval * rval return rval
def get_enum(s, enum_class): """Get an enum from a string where the enum class is assumed to have all upper-case keys, returning None if the key is not found. Args: s (str): Key of enum to find, case-insensitive. enum_class (:class:`Enum`): Enum class to search. Returns: T...
def mendProcess(result, file1, file2, wordsNumber): """ take every match location in 'result' list and get sure there is no sub-text of length(wordsNumber) matched get ignored. """ def searchPointInMatch(point, file): for position in reversed(result): if point >= position[file][0] and point <= position[file]...
def indent_string(string, chars): """Indents a string by x number of characters.""" indented_string = '' for line in string.splitlines(): indented_string += '%s%s\n' % ((' ' * chars), line) # Strip the ending '\n' and return result. return indented_string[0:-1]
def get_vms(app, scope='deployment'): """Return the VMs in an application.""" return app.get(scope, {}).get('vms', [])
def kappa(A: float, B: float, C: float): """ Calculate Ray's asymmetry parameter for a given set of A, B, and C rotational constants. This parameter determines how asymmetric a molecule is by setting a range between two limits: the prolate (+1) and the oblate (-1) limits. Parameters ---------- ...
def retifyxxyysize(img_height, img_width, xxyy): """return xxyy within image region img_height: img_width: xxyy: return xxyy """ xxyy[0] = max(xxyy[0], 0) xxyy[1] = max(xxyy[1], 0) xxyy[2] = max(xxyy[2], 0) xxyy[3] = max(xxyy[3], 0) xxyy[0] = min(xxyy[0], img_width) xxyy...
def wire_plotter(wire_code, current_location): """Accepts code list and current location (tuple). Returns list of tuples of locations.""" new_locations = [] if wire_code[0] == 'U': upper_value = int(wire_code[1:]) for i in range(1, upper_value+1): new_locations.append( (current_...
def parseLinksList(links, weighted, resdub): """Parse node links in Pajek format links - links string: <did1> <did2> ... weighted - generate weighted / unweighted links resdub - resolve dublicates return [(dest_id, weight), ...] """ links = links.split() if weighted: if resdub: links = {v: '1' for v in ...
def _iterable_has_any(itr, *items): """Test if an interable includes all of `items` (by equality). >>> _iterable_has_any((1, 2, 3), 1, 3) True >>> _iterable_has_any((1, 2, 3), 1, 4) True """ for item in itr: if item in items: return True return False
def partition(start, end, cores): """Split a range into (exactly or almost) parts Args: start (int): The first index of the range. end (int): The last index of the range. cores (int): The number of parts to split into. Returns: :obj:`list` of :obj:`list` of :obj:`int`: The ...
def _get_match(proto, filter_fn): """Finds and returns the first element that matches a query. If no element matches the query, it throws ValueError. If more than one element matches the query, it returns only the first. """ query = [elm for elm in proto if filter_fn(elm)] if len(query) == 0: raise Val...
def getPathValues(d, path): """ Given a nest structure, return all the values reference by the given path. Always returns a list. If the value is not found, the list is empty NOTE: Processing a list is its own recursion. """ pos = path.find('.') currentpath = path[0:pos] if pos > 0 ...
def check_bit_set(value: int, bit: int): """ Simple function to determine if a particular bit is set eg (12 - binary 1100) then positions 3 and 4 are set :param value: Number to be tested :param bit: Position to check; >0 (right to left) :return: Bool: True if bit is set """ if va...
def get_corr_reg_name(curr_name: str) -> str: """ Function that corrects wrong regions names """ # Specjalny wyjatek, bo w danych PRG jest powiat "JELENIOGORSKI", a od 2021 roku powiat ten nazywa sie "KARKONOSKI", # wiec trzeba to poprawic if curr_name == "JELENIOGORSKI": return "KARKONOSKI" ...
def getletter(variable, letternumber): """ Get the corresponding item in a object :type variable: string :param variable: The string to get the letter from :type letternumber: integer :param letternumber: The index of the letter to get """ # Get the corresponding letter return str...
def surroundings(center, radius, domains): """ The surroundings of a `center` is a list of new centers, all equal to the center except for one value that has been increased or decreased by `radius`. """ return [center[0:i] + (center[i] + d,) + center[i + 1:] for i in range(len(center)) fo...
def dict_match(a, b): """ Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False """ res = [] for k, v in a.items(): try: res.append(b[k] == v) except KeyError: pass return a...
def partition_first(array, start, end): """Selects the first element as pivot. Returns the index where the pivot went to. In this variant, we can guarantee that the pivot will be in its final sorted position. We need this guarantee for QuickSelect.""" if start + 1 == end: return start pivot ...
def count_snps(transform, count_indels_once=False): """ Counts the SNPs (technically, the number of variant bases) from a reference by a read's "transform". :param transform: :return: the number of bases different from a reference sequence as represented in the provided transform. """ if count_...
def _get_protocol_tuple(data): """Convert a dictionary to a tuple. :param dict data: :rtype: tuple[str,list,dict] """ return data['function'], data.get('args', []), data.get('kwargs', {})
def _after_each(separator, iterable): """Inserts `separator` after each item in `iterable`. Args: separator: The value to insert after each item in `iterable`. iterable: The list into which to intersperse the separator. Returns: A new list with `separator` after each item in `iterable`. ...
def filterSubjects(subjectList, filterUsing='equals') : """Return a natsListener filter which will filter NATS messages on the subjects by returning True on either of the following conditions: - `equals`: return True if the message subject is *equal* to any subject in the subjectList. - `startsWith`: ...
def sign(x): """ Returns the sign of x. :param x: A scalar x. :return: The sign of x \in (+1, -1, 0). """ if x > 0: return +1 elif x < 0: return -1 elif x == 0: return 0
def Eq(field, value): """ A criterion used to search for a equality. For example * search for TLP = 2 * search for flag = True * search for title = 'Sample case' Arguments: field (value): field name value (Any): field value Returns: dict: JSON repsentation of the c...
def remove_docstart_sentence(sentences): """Remove -DOCSTART- sentences in the list of sentences. Parameters ---------- sentences: List[List[TaggedToken]] List of sentences, each of which is a List of TaggedTokens. This list may contain DOCSTART sentences. Returns ------- ...
def human_size(size_bytes): """ Return a human size readable from bytes >>> human_size(906607633) '864.61 MB' :param size_bytes: bytes to transform :return: string in human readable format. """ if size_bytes is 0: return "0B" def ln(x): n = 99999999 return ...
def encode_null_terminated(s: str, encoding: str, errors: str = 'strict') -> bytes: """Encodes s using the given encoding, adding a zero character to the end if necessary. No attempt is made to detect a zero character before the end of the string, so if given a string like 'a\\0b', this will generate t...
def normalized_total_time(p, max_time=3600000 * 5): # by default 5 h (in ms) """If time was longer than max_time, then return max_time, otherwise return time.""" if p["result.totalTimeSystem"] == "3600.0": v = 3600000 # convert to ms (error in logging) else: v = int(float(p["result.totalTim...
def fnCalc_ApogeePerigee(a,e): """ Calculate the apogee and perigee of a space-object based on the semi-major axis a and the eccentricity e. Created: 07/04/17 Added here: 11/04/17 """ perigee = a*(1.-e); apogee = a*(1.+e); return perigee, apogee
def format_bytes(num): """Convert bytes to KB, MB, GB or TB""" step_unit = 1024 for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < step_unit: return "%3.1f %s" % (num, x) num /= step_unit
def print_scientific_16(value: float) -> str: """ Prints a value in 16-character scientific notation. This is a sub-method and shouldnt typically be called .. seealso:: print_float_16 for a better method """ if value == 0.0: return '%16s' % '0.' python_value = '%16.14e' % value # ...
def trim_shared_prefix(ref, alt): """ Sometimes mutations are given with a shared prefix between the reference and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids). This function trims the common prefix and returns the disjoint ref and alt strings, along with the shared prefi...
def punctuation(chars=r',.\"!@#\$%\^&*(){}\[\]?/;\'`~:<>+=-'): """Finds characters in text. Useful to preprocess text. Do not forget to escape special characters. """ return rf'[{chars}]'
def unsquish(selected, unadapted_data): """Transform our selected squished text back to the original text selected: the selected sentences unadapted_data: the list of original unadapted sentences returns: the selected sentences, with clear text """ for i, line in enumerate(selected): i...