content
stringlengths
42
6.51k
def bin16dec(bin: int) -> int: """Returns a signed integer from the first 16 bits of an integer """ num = bin & 0xFFFF return num - 0x010000 if 0x8000 & num else num
def fetch_method(obj, method): """ fetch object attributes by name Args: obj: class object method: name of the method Returns: function """ try: return getattr(obj, method) except AttributeError: raise NotImplementedError(f"{obj.__class__} has not impl...
def readline(file): """ Return the first unread line from this file, or the empty string if all lines are read. """ return file.readline()
def clip(lower, val, upper): """Clips a value. For lower bound L, upper bound U and value V it makes sure that L <= V <= U holds. Args: lower: Lower boundary (including) val: The value to clip upper: Upper boundary (including) Returns: value within bounds """ if v...
def flatten(nested_list): """ Flatten a list of nested lists """ return [item for sublist in nested_list for item in sublist]
def rev_strand(strand): """ reverse the strand :param strand: :return: """ if strand == "+": return "-" return "+"
def get_accuracy(y_bar, y_pred): """ Computes what percent of the total testing data the model classified correctly. :param y_bar: List of ground truth classes for each example. :param y_pred: List of model predicted class for each example. :return: Returns a real number between 0 and 1 for the model accura...
def delete_from_file_name_forbidden_characters(str_filename): """Delete forbidden charactars in a filename from the given string Args: str_filename (str): Name of the file Returns: str: filename with removed characters which are not allowed """ list_chars_of_filtered_filenames = []...
def num_steps(n, steps=0): """Determine number of ways a child can get to the top of the stairs.""" if steps > n: return 0 if steps == n: return 1 return num_steps(n, steps + 1) + num_steps(n, steps + 2) + num_steps(n, steps + 3)
def to_palindrome(seq): """ Generates two possible palindromic sequence from the input sequence """ init_type = type(seq) if not (init_type is str or init_type is int): raise TypeError("Input a string or integer only") if init_type == int: seq = str(seq) forward = ...
def create_sim_table(train, test, distances): """ create a table of similarity between the train program and test programs. Parameters ---------- train: list list of train programs names test: list list...
def _from_sRGB(component): """ Linearize sRGB color """ component /= 255.0 return component / 12.92 if component <= 0.04045 else ((component+0.055)/1.055)**2.4
def calc_bending_force(R_ring: float, params: dict) -> float: """Calculate the elastic bending force of a filament in a ring. Args: R_ring: Radius of the ring / m params: System parameters """ return params["EI"] * params["Lf"] / R_ring**3
def to_mixed_case(string: str): """ foo_bar_baz becomes fooBarBaz. Based on pydantic's `to_camel` utility, except without the initial capital letter. """ words = string.split("_") return "".join([words[0]] + [w.capitalize() for w in words[1:]])
def S_get_histogram_values(_data_list, _level=0.1): """ Finds the groups present for given data samples Groups will be divided based on value difference as set by level parameter """ ds = len(_data_list) if ds < 1: return [] s_data = sorted(_data_list) bins = [] bin_curso...
def _parse_s3_file(original_file): """ Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt') """ bits = original_file.replace('s3://', '').split("/") bucket = bits[0] object_key = "/".join(bits[1:]) return bucket, object_key
def in_dictionary(pairs, dictionary_one_to_set): """Returns a list of booleans indicating if each pair of the list appears in the dictionary""" result = [] for k, v in pairs: result.append(1 if k in dictionary_one_to_set and v in dictionary_one_to_set[k] else 0) return result
def is_blank(s): """ Returns True if the given string is None or blank (after stripping spaces), False otherwise. """ return s is None or len(s.strip()) == 0
def validate_password_policy(password): """ Password should contain - at least 1 uppercase character (A-Z) - at least 1 lowercase character (a-z) - at least 1 digit (0-9) - at least 1 special character (punctuation) """ # app.logger.info("Validating password policy") ...
def split_units(value): """Splits a string into float number and potential unit References Taken from https://stackoverflow.com/a/30087094 Args: value: String with number and unit. Returns A tuple of a float and unit string. Examples: >>> split_units("2GB") ...
def convert_set(iterable, convert_to='list'): """This function casts a ``set`` variable to be a ``list`` instead so that it can be scriptable. :param iterable: The iterable to be evaluated to see if it has a ``set`` type :param convert_to: Defines if the iterable should be cast to a ``list`` (default) or a...
def setter_helper(fn, value): """ Some property setters need to call a function on their value -- e.g. str() or float() -- before setting the property. But, they also need to be able to accept None as a value, which throws an error. This helper solves this problem :param fn: function to apply to va...
def find_number_to_keep(count_of_0, count_of_1, criteria) -> str: """ Compare numbers according to a criteria ('most' or 'least'). Criteria 'most' returns the number of which count is bigger. Criteria 'least' returns the number of which count is lesser. When counts are equal, criteria 'm...
def is_enumerable_str(identifier_value): """ Test if the quoted identifier value is a list """ return len(identifier_value) > 2 and identifier_value[0] in ('{', '(', '[') and identifier_value[-1] in ('}', ']', ')')
def chat_id(message: dict) -> int: """ Extract chat id from message """ return message["chat"]["id"]
def splitdrive(path): """Split a pathname into drive and path specifiers. Returns a 2-tuple "(drive,path)"; either part may be empty. """ # Algorithm based on CPython's ntpath.splitdrive and ntpath.isabs. if path[1:2] == ':' and path[0].lower() in 'abcdefghijklmnopqrstuvwxyz' \ and (pa...
def remove_underline(params): """Remove the underline in reserved words. The parameters def and type are python reserved words so it is necessary to add a underline to use this words, this method remove the underline before make a http request. Args: params (dict): Url query parameters. ...
def compare_thresh(values, op, thresh): """Check if value from metrics exceeds thresh.""" state = 'OK' for value in values: if value: if op == 'GT' and value <= thresh: return state elif op == 'LT' and thresh <= value: return state ...
def process_page(inp): """ Wraps around if we split: make sure last passage isn't too short. This is meant to be similar to the DPR preprocessing. """ (nwords, overlap, tokenizer), (title_idx, docid, title, url, content) = inp if tokenizer is None: words = content.split() e...
def link_to_changes_in_release(release, releases): """ Markdown text for a hyperlink showing all edits in a release, or empty string :param release: A release version, as a string :param releases: A container of releases, in descending order - newest to oldest :return: Markdown text for a hyperlin...
def get_gse_gsm_info(line): """ Extract GSE and GSM info Args: line: the entry to process Returns: the GSE GSM info tuple """ parts = line.strip().split(",") if parts[0] == "gse_id": return None return parts[0], parts[1:]
def rgb_clamp(colour_value): """ Clamp a value to integers on the RGB 0-255 range """ return int(min(255, max(0, colour_value)))
def write_tsv_file(out_filename, name_list, scalar_name, scalar_list): """Write a .tsv file with list of keys and values. Args: out_filename (string): name of the .tsv file name_list (list of string): list of keys scalar_name (string): 'volume', 'thickness', 'area' or 'meanC...
def _max_len(choices): """Given a list of char field choices, return the field max length""" lengths = [len(choice) for choice, _ in choices] return max(lengths)
def remove_measure(line): """ (str) -> str Returns provided line with any initial digits and fractions (and any sorrounding blanks) removed. """ char_track = 0 blank_char = ' ' while char_track < len(line) and (line[char_track].isdigit() or \ line[char_track] in ('/', blank_cha...
def get_payment_request(business_identifier: str = 'CP0001234', corp_type: str = 'CP', second_filing_type: str = 'OTADD'): """Return a payment request object.""" return { 'businessInfo': { 'businessIdentifier': business_identifier, 'corpType': corp_type, ...
def IsOutputField(help_text): """Determines if the given field is output only based on help text.""" return help_text and ( help_text.startswith('[Output Only]') or help_text.endswith('@OutputOnly'))
def get_speed(value): """ Return if the capturing speed is fast (no filtering) or slow (filtered) """ if (value & 64) == 64: return 'Fast' else : return 'Slow'
def _parse_common(row): """Parse common elements to TF Example from CSV row for non-spans mode.""" example = {} example['id'] = row['id'] example['text'] = row['comment_text'] example['parent_text'] = row['parent_text'] parent_id = row['parent_id'] or 0 example['parent_id'] = int(float(parent_id)) examp...
def binary_mode_to_cascade_mode(binary_list, num_cascade): """ Parameters ---------- binary_list: list num_cascade: int Returns --------- cascade_mode: int """ cascade_mode = 0 if binary_list == [0] * num_cascade: cascade_mode = 0 count = 1 for ele in binary_l...
def hdf_arrays_to_dict(hdfgroup): """ Convert an hdf5 group contains only data sets to a dictionary of data sets :param hdfgroup: Instance of :class:`h5py.Group` :returns: Dictionary containing each of the datasets within the group arranged by name """ return {key: h...
def generate_router_url(project_id, region, router): """Format the resource name as a resource URI.""" return 'projects/{}/regions/{}/routers/{}'.format( project_id, region, router )
def return_organisation_links(new_order): """ This can be updated to include the most relevant organisation links for the required country or region. Note the order of this list needs to vary with the F1-score so may be best implemented as a dictionary? """ links = ["http://"+i+".co...
def plural(st: str) -> str: """Pluralise most strings. Parameters ---------- st : str string representing any word ending in ss or not Returns ------- str plural form of string st """ if st[-2:] not in ['ss']: return f'{st}s' return f'{st}es'
def format_string(format_config, target_value): """ Formats number, supporting %-format and str.format() syntax. :param format_config: string format syntax, for example '{:.2%}' or '%.2f' :param target_value: number to format :rtype: string """ if (format_config.startswith('{')): re...
def tags_str_as_set(tags_str): """Return comma separated tags list string as a set, stripping out surrounding white space if necessary. """ return set(filter(lambda t: t != '', (t.strip() for t in tags_str.split(','))))
def get_handler_name(handler): """ Return name (including class if available) of handler function. Args: handler (function): Function to be named Returns: handler name as string """ name = '' if '__self__' in dir(handler) and 'name' in dir(handler.__self__):...
def repeat(s, question): """ Returns the user input repeated three times and if they include a third argument sys.argv[2] then it will add three question marks. """ result = s * 3 if question: result = result + "???" return result
def parse_summary(summary): """Parse a string from the format 'Anzahl freie Parkpl&auml;tze: 179' into both its params""" summary = summary.split(":") summary[0] = summary[0].strip() if "?" in summary[0]: summary[0] = "nodata" try: summary[1] = int(summary[1]) except ValueError...
def spectra(spall_dict): """ access skyserver for details on this object :param spall_dict: :return: """ url = "http://skyserver.sdss.org/dr16/en/get/SpecById.ashx?id={}".format( spall_dict['SPECOBJID'] ) print("\nSpectra:") print(url) return url
def sol(s, l, r): """ The recursive approach """ if r == l: return 1 if r-l == 1 and s[l] == s[r]: return 2 if r-l == 2 and s[l] == s[r]: return 3 if s[l] == s[r]: return sol(s, l+1, r-1) + 2 return max( sol(s, l, r-1), sol(s, l...
def ensure_keys(dict_obj, *keys): """ Ensure ``dict_obj`` has the hierarchy ``{keys[0]: {keys[1]: {...}}}`` The innermost key will have ``{}`` has value if didn't exist already. """ if len(keys) == 0: return dict_obj else: first, rest = keys[0], keys[1:] if first not in ...
def write_unit(value): """ Convert unit value to modbus value """ return [int(value)]
def count_bits(n): """Count number of ones in binary representation of decimal number.""" bits = 0 if n == 0 else 1 while n > 1: bits += n % 2 n //= 2 return bits
def xorGate(a, b): """ Input: a, b Two 1 bit values as 1/0 Returns: 1 if a is not equal to b otherwise 0 """ if a != b: return 1 else: return 0
def str_to_md5(tbhstring): """Converte uma str para md5""" import hashlib hashid = hashlib.md5(tbhstring.encode('utf-8')).hexdigest() return hashid
def parse_var(s): """ Parse a key, value pair, separated by '=' That's the reverse of ShellArgs. On the command line (argparse) a declaration will typically look like: foo=hello or foo="hello world" """ items = s.split('=') key = items[0].strip() # we remove blanks around keys, as is logical if...
def render_precipitation_chance(data, query): """ precipitation chance (o) """ answer = data.get('chanceofrain', '') if answer: answer += '%' return answer
def font_name(family, style): """Same as ``full_name()``, but ``family`` and ``style`` names are separated by a hyphen instead of space.""" if style == 'Regular': font_name = family else: font_name = family + '-' + style return font_name
def extract_version(txt): """This function tries to extract the version from the help text of any program.""" words = txt.replace(",", " ").split() version = None for x in reversed(words): if len(x) > 2: if x[0].lower() == "v": x = x[1:] if "." in x an...
def config_name_from_full_name(full_name): """Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like...
def string_dlt_to_dlt(dlt_str_rep): """ Return dictionary/list/tuple from given string representation of dictionary/list/tuple Parameters ---------- dlt_str_rep : str '[]' Examples -------- >>> string_dlt_to_dlt("[1, 2, 3]") [1, 2, 3] >>> string_dlt_to_dlt("[]") [] ...
def event_dot_nodes(doc, events, include_prop_anchors=False): """ Return a dot string that declares nodes for the given set of events, along with any entities or syn_nodes reachable from those events. """ # Collect node values event_node_values = set() entity_node_values = set() enti...
def easy_unpack(tuple): """ returns a tuple with 3 elements - first, third and second to the last """ tuple2=(tuple[0], tuple[2], tuple[-2]) return tuple2
def is_palindrome(n): """Returns True if integer n is a palindrome, otherwise False""" if str(n) == str(n)[::-1]: return True else: return False
def fibonacci(n): """ This function prints the Nth Fibonacci number. >>> fibonacci(3) 1 >>> fibonacci(10) 55 The input value can only be an integer, but integers lesser than or equal to 0 are invalid, since the series is not defined in these regions. """ if n<=0: return "Incorrect input." eli...
def _format_rest_url(host: str, append: str = "") -> str: """Return URL used for rest commands.""" return f"http://{host}:8001/api/v2/{append}"
def combine_results(lst): """ combines list of results ex: [[1, ["hey", 0]], [0,[]], [1, ["you", 1]]] -> [1, [["hey", 0],["you", 1]]] """ a = 0; b = [] for x in lst: a = max(a, x[0]) if x[1] != []: b += x[1] return a, b
def ip_family(address): """Return the ip family for the address :param: address: ip address string or ip address object :return: the ip family :rtype: int """ if hasattr(address, 'version'): return address.version if '.' in address: return 4 elif ':' in addres...
def farthest_parseinfo(parseinfo): """As we might have tried several attempts of parsing different formats we have several error reports from the respective parsers. The parser that made it the farthest (line, column) probably matched the format but failed anyway. The error report of this least unsu...
def is_query_complete(query): """ returns indication as to if query includes a q=, cb.q=, or cb.fq """ if query.startswith("cb.urlver="): return True if query.startswith("q=") or \ query.startswith("cb.q=") or \ query.startswith("cb.fq="): return True return False
def remove_inp_from_splitter_rpn(splitter_rpn, inputs_to_remove): """ Remove inputs due to combining. Mutates a splitter. Parameters ---------- splitter_rpn : The splitter in reverse polish notation inputs_to_remove : input names that should be removed from the splitter ...
def lcm(x, y): """This function takes two integers and returns the L.C.M. Args: x: y: """ # choose the greater number if x > y: greater = x else: greater = y while True: if (greater % x == 0) and (greater % y == 0): lcm = greater ...
def split_channels(rgb): """ Split an RGB color into channels. Take a color of the format #RRGGBBAA (alpha optional and will be stripped) and convert to a tuple with format (r, g, b). """ return ( float(int(rgb[1:3], 16)) / 255.0, float(int(rgb[3:5], 16)) / 255.0, float...
def contains(word, tiles): """ Takes two lists of a string. First checks if each letter in the word is in the tile set. If true then it will check each letter in the tile, removing it from the word and if at the end the word is a blank list it will return true. TBH, it's probably not perfect, but it's passed ...
def bleach_name(name): """ Make a name safe for the file system. @param name: name to make safe @type name: L{str} @return: A safer version of name @rtype: L{str} """ assert isinstance(name, str) name = name.replace("\x00", "_") name = name.replace("/", "_") ...
def remove_dupl(a_list): """ Remove duplicates from a list and returns the list :return: the list with only unique elements """ return list(dict.fromkeys(a_list))
def build_version(release_version: str) -> str: """Given 'X.Y.Z[-rc.N]', return 'X.Y.Z'.""" return release_version.split('-')[0]
def minsample(population, k, randomize=1): """Samples upto `k` elements from `population`, without replacement. Equivalent to :func:`random.sample`, but works even if ``k >= len(population)``. In the latter case, it samples all elements (in random order).""" if randomize: from random import samp...
def stop_worker(versionId: str) -> dict: """ Parameters ---------- versionId: str """ return {"method": "ServiceWorker.stopWorker", "params": {"versionId": versionId}}
def last_common_item(xs, ys): """Search for index of last common item in two lists.""" max_i = min(len(xs), len(ys)) - 1 for i, (x, y) in enumerate(zip(xs, ys)): if x == y and (i == max_i or xs[i+1] != ys[i+1]): return i return -1
def lychrel(n: int): """ A test for lychrel numbers candidates in base 10 capping at 10,000 """ cap, i, numb = 10000, 0, n while i < cap: if numb == int(str(numb)[::-1]): return i else: numb = numb+int(str(numb)[::-1]) i += 1 return True
def flatten_modules_to_line(modules): """Flatten modules dictionary into a line. This line can then be used in fc_statements to add module info. The flattend line looks like: module ":" symbol [ "," symbol ]* [ ";" module ":" symbol [ "," symbol ]* ] Parameters ---------- modul...
def _get_object_by_type(results, type_value): """Get object by type. Get the desired object from the given objects result by the given type. """ return [obj for obj in results if obj._type == type_value]
def get_max_day_events(events): """ return the maximum events count in one day over all the events given """ events_count = {} if len(events) == 0: return 0 for event in events: if not events_count.get(event.date_time_start.date()): events_count[event.date_time_start.date()...
def solve(captcha): """Solve captcha. :input: captcha string :return: sum of all paired digits that match >>> solve('1212') 6 >>> solve('1221') 0 >>> solve('123425') 4 >>> solve('123123') 12 >>> solve('12131415') 4 """ a = len(captcha) // 2 return sum(i...
def _is_text(shape): """ Checks if this shape represents text content; a TEXT_BOX """ return shape.get('shapeType') == 'TEXT_BOX' and 'text' in shape
def gassian_distribution(x,scale=1,mean=10,sigma=2): """Returns Gaussian distribution evaluated over 'x' according to 'scale', 'mean', and 'sigma' parameters.""" from numpy import exp,pi,sqrt return scale*(1/(sigma*sqrt(2*pi)))*exp(-(x-mean)**2/(2*sigma**2))
def build_query_data(result): """ Input: result: object of type main.result Output: result in the form of a list of parameters for an SQL query """ params = [] for attribute in result: # tags and groups are added separately if attribute[0] != "tags" and attribute[0] != "grou...
def listr(s): """'x,x,x'string to list""" return [ss for ss in s.split(',') if ss]
def is_not_false_str(string): """ Returns true if the given string contains a non-falsey value. """ return string is not None and string != '' and string != 'false'
def get_cls_import_path(cls): """Return the import path of a given class""" module = cls.__module__ if module is None or module == str.__module__: return cls.__name__ return module + '.' + cls.__name__
def seconds_to_ui_time(seconds): """Return a human-readable string representation of the length of a time interval given in seconds. :param seconds: the length of the time interval in seconds :return: a human-readable string representation of the length of the time interval """ if seconds >...
def init(client, **kwargs): """ :param client: :param kwargs: :return: """ global g_client g_client = client return True
def makeSiteWhitelist(jsonName, siteList): """ Provided a template json file name and the site white list from the command line options; return the correct site white list based on some silly rules """ if 'LHE_PFN' in jsonName: siteList = ["T1_US_FNAL"] print("Overwritting SiteWh...
def crossProduct(list1, list2): """ Returns all pairs with one item from the first list and one item from the second list. (Cartesian product of the two lists.) The code is equivalent to the following list comprehension: return [(a, b) for a in list1 for b in list2] but for easier reading...
def curate_url(url): """ Put the url into a somewhat standard manner. Removes ".txt" extension that sometimes has, special characters and http:// Args: url: String with the url to curate Returns: curated_url """ curated_url = url curated_url = curated_url.r...
def player_has_missed_games(game_being_processed, cur_pfr_game): """ Function that checks if the player has missing games :param game_being_processed: Game (by week) we are processing :param cur_pfr_game: Game (by week) we are on for the player :return: Bool """ if game_being_processed == cu...
def replicate_multilabel_document(document_tuple): """ Takes a document and a set of labels and returns multiple copies of that document - each with a single label For example, if we pass ('foo', ['a', 'b']) to this function, then it will return [ ('foo', 'a'), ('foo', 'b') ] :param document_tu...
def issues2dict(issues): """Convert a list of issues to a dict, keyed by issue number.""" idict = {} for i in issues: idict[i['number']] = i return idict