content
stringlengths
42
6.51k
def input_param(name, value): """ Display input name and value for checking. :param name: parameter name. :param value: parameter value. :return: value. """ print('{} = {}'.format(name, value)) return value
def IsValidKeyForZeroQuery(key): """Returns if the key is valid for zero query trigger.""" is_ascii = all(ord(char) < 128 for char in key) return not is_ascii
def inverse_reframe_curves(raw_data, position_of_base_origin): """ Inverts the shift in a frame of reference of 3D curves, given the position of the old origin in the new frame of reference """ # Define the current origin for i in range(len(raw_data)): raw_data[i][0] -= position_of_base_orig...
def is_valid_host(ip): """ roughly """ parts = list(map(int, ip.split('.'))) return len(parts) == 4 and all(0 <= p < 256 for p in parts)
def process(max_slices, no_of_types, slices_list): """ The main program reads the input file, processes the calculation and writes the output file Args: max_slices: Maximum number of slices allowed no_of_types: Number of Pizza to be selected slices_list: List of number of slices...
def to_line_equation(coefs, p): """ Substitutes point p into line equation determined by coefs :param coefs: list or tuple of 3 elements (or anything that can be unzipped to 3 elements) :param p: point :return: A * p.real + B * p.imag + C """ A, B, C = coefs return A * p.real + B * p.ima...
def justify_center(content: str, width: int, symbol: str) -> str: """ Centers string in symbol, width chars wide. Parameters ---------- content : string The string (1+ lines long) to be centered. width : integer Width of the column in characters within which the stri...
def is_numeric_port(portstr): """return: integer port (== True) iff portstr is a valid port number, False otherwise """ if portstr.isdigit(): port = int(portstr) # 65536 == 2**16 if 0 < port < 65536: return port return False
def complement(x): """ This is a helper function for reverse(rule) and unstrobe(rule). It is assumed that x is a character and the returned result is also a character. """ return str(8 - int(x))
def test_while_reassign(obj1, obj2, obj3, obj4): """ >>> test_while_reassign(*values[:4]) (9L, Value(1), 2L, 5L) >>> sig, syms = infer(test_while_reassign.py_func, ... functype(None, [object_] * 4)) >>> types(syms, 'obj1', 'obj2', 'obj3', 'obj4') (object_, object_, int, int...
def _path(path): """Helper to build an OWFS path from a list""" path = "/" + "/".join(str(x) for x in path) return path.encode("utf-8") + b"\0"
def writeADESHeader( observatory_code, submitter, telescope_design, telescope_aperture, telescope_detector, observers, measurers, observatory_name=None, submitter_institution=None, telescope_name=None, telescope_fratio=None, ...
def get_tag_value(tags, key): """Get a specific Tag value from a list of Tags""" for tag in tags: if tag['Key'] == key: return tag['Value'] else: raise KeyError
def toBytesString(input): """ Convert unicode string to bytes string """ result = input.encode('latin-1') return result
def set_timeout(timeout=None): """ Set requests timeout default to 250 sec if not specified :return: """ if not timeout: timeout = 250 else: timeout = int(timeout) return timeout
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*'\ , '*2*1***']) True >>> check_uniqu...
def _underscore_to_camelcase(value, cap_segment=None): """ Converts underscore_separated string (aka joined_lower) into camelCase string. >>> _underscore_to_camelcase('foo_bar_baz') 'FooBarBaz' >>> _underscore_to_camelcase('foo_bar_baz', cap_segment=0) 'FOOBarBaz' >>> _underscore_to_camelcase('...
def cancel_job(job_id): """ Cancel job :param job_id: int, job id :return: if success, return 1, else return 0 """ import subprocess try: step_process = subprocess.Popen(('qdel', str(job_id)), shell=False, stdout=subprocess.PIPE, stderr=subproc...
def surface_margin_waste (A_approx_waste, A_real_waste): """ Calculates the surface margin. Parameters ---------- A_approximate_waste : float The approximate heat ransfer area, [m**2] A_real_waste : float The real heat transfer area, [m**2] Returns ------- surface_mar...
def filterCoins(coins): """Filtering Coins to useful ones. Parameters: coins (lst[(str, str)]): Cryptocurreny Index Returns: lst[(str, str)]: List of coins we want to fetch for. """ unwanted = set(['USDT', 'USDC', 'BUSD', 'UST', 'WBTC','DAI', 'CRO']) filtered = filter(lambda coin: co...
def get_direction(call): """ :param call: represents a call :return: what direction is the elevator going UP = 1, DOWN = -1 """ if call[2] < call[3]: return 1 else: return -1
def _belongs_to_one_of_these_classes(obj, classes): """ Returns true if the given object belongs to one of the classes cited in the list of classes provided. :param obj: The object to lib_test. :param classes: The qualifying classes. :return: Boolean. """ for cls in classes: if i...
def code_block(text, language=""): """Return a code block. If a language is specified a fenced code block is produced, otherwise the block is indented by four spaces. Keyword arguments: language -- Specifies the language to fence the code in (default blank). >>> code_block("This is a simple c...
def to_digit(x): """ convert a string into an int if it represents an int otherwise convert it into a float if it represents a float otherwise do nothing and return it directly :param x: the input string to be converted :return: the result of convert """ if not isinstance(x, str): ...
def parse_hpo_disease(hpo_line): """Parse hpo disease line Args: hpo_line(str) a line with the following formatting: #Format: HPO-id<tab>HPO label<tab>entrez-gene-id<tab>entrez-gene-symbol\ <tab>Additional Info from G-D source<tab>G-D source<tab>disease-ID for link ...
def is_pythagorean_triplet(a, b, c): """ A Pythagorean triplet is a set of three natural numbers a < b < c for which: a^2 + b^2 = c^2 Example: 3,4,5 3^2 + 4^2 = 5^2 9 + 16 = 25 :param int a: first number :param int b: second number :param int c: third numbe...
def value(card): """Returns the numeric value of a card or card value as an integer 1..13""" prefix = card[:len(card) - 1] names = {'A': 1, 'J': 11, 'Q': 12, 'K': 13} if prefix in names: return names.get(prefix) else: return int(prefix)
def g(x): """ y = (1/3)x**3 - x """ return x**3 / 3 - x
def hex_to_64(hexstr): """Convert a hex string to a base64 string. Keyword arguments: hexstr -- the hex string we wish to convert """ B64CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' ## internals # bits contains the bits read off so far that don't make enou...
def format_team_outputs(team: dict = {}) -> dict: """Take GitHub API team data and format to expected context outputs Args: team (dict): team data returned from GitHub API Returns: (dict): team object formatted to expected context outputs """ ec_team = { 'ID': team.get('id'...
def btc(amount_satoshis, units='BTC'): """Given an amount in satoshis return a display string""" divisor = { 'BTC': 1e8, 'mBTC': 1e5, 'uBTC': 1e2, 'bit': 1e2, 'sat': 1}[units] amount = amount_satoshis/divisor spec = units if spec == 'bit' and amount != 1: ...
def get_ip_address_discovery_ports(app): """ :return: list """ ip_address = app.get('ipAddress', {}) if len(ip_address) == 0: return [] discovery = app.get('ipAddress', {}).get('discovery', {}) return [int(p['number']) for p in discovery.get('ports', []) if 'n...
def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: raise ValueError('len < 1') return sum(data)/float(n)
def first_non_repeating_letter(the_string): """ Find first non-repeating letter in a string. Letters are to be treated case-insensitive, which means 't' = 'T'. However, one must return the first non-repeating letter as it appears in the string, either in uppercase or lowercase. 'sTress'...
def hebrew_date(year, month, day): """Return an Hebrew date data structure.""" return [year, month, day]
def check_undirected(graph): """ dict -> boolean Just a sanity check that a graph is in fact undirected. """ for node in graph: for neighbor in graph[node]: if node not in graph[neighbor]: return False return True
def dcrossing(m_): """ Return the largest k for which the given matching or set partition has a k-distant crossing. INPUT: m -- a matching or set partition, as a list of 2-element tuples representing the edges. You'll need to call setp_to_edges() on the objects returned by SetPartitions() ...
def is_anagram(str1, str2): """ :rtype: bool :param str1: First string :param str2: Second string :return: True if the two strings are anagrams """ if len(str1) == len(str2): if sorted(str1) == sorted(str2): return True else: return True else: ...
def _density_factor(density_units_in: str, density_units_out: str) -> float: """helper method for convert_density""" factor = 1.0 if density_units_in == 'slug/ft^3': pass elif density_units_in == 'slinch/in^3': factor *= 12**4 elif density_units_in == 'kg/m^3': factor /= 515....
def text_reply(text): """ simplify pure text reply :param text: text reply :return: general message list """ return [{ 'type': 'text', 'data': {'text': text} }]
def first_is_higher(v1, v2): """ Return a boolean value to indicate if the first software version number is higher than the second. Args: v1 - The first version string to compare v2 - The second version string to compare """ v1_split = v1.split('.') v2_split = v2.split('.') ...
def _Indentation(indentation_level): """Returns the indentation string.""" return " " * indentation_level
def get_data_from_given_model(spam_mail_model, ham_mail_model): """ This is the function used to divide the data into test and train data :param spam_mail_model: This is the representation(list) of each spam document in the given format :param ham_mail_model: This is the representation(list) of each...
def replace_cr_with_newline(message: str) -> str: """ TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output. Displaying those in a file won't work correctly, so we'll just make sure that each batch shows up on its one li...
def bubble_sort(array): """Repeatedly step through the list, compare adjacent items and swap them if they are in the wrong order. Time complexity of O(n^2). Parameters ---------- array : iterable A list of unsorted numbers Returns ------- array : iterable A list of sorte...
def calculate_test_code_to_production_code_ratio(production_code_metrics, test_code_metrics): """Calculate the ratio between the test code and the production code.""" lines_of_code = production_code_metrics["SUM"]["code"] lines_of_test_code = test_code_metrics["SUM"]["code"] return float(lines_of_test...
def is_boundary_edge(a, b, bdy_edges): """ Checks whether edge (a, b) is in the list of boundary edges """ for edge in bdy_edges: a0, b0 = edge if a == a0 and b == b0: return True return False
def align(bytes, alignment=16): """Align BYTES to a multiple of ALIGNMENT""" return ((bytes + alignment - 1) // alignment) * alignment
def get_name(row): """ Returns a built string containing of last name and first name :param row: Raw row from CSV :return: Name string """ return row[0] + " " + row[1]
def is_mirror(master_uri, compare_uri): """ check if the given add_url is idential or a mirror of orig_uri e.g.: master_uri = archive.ubuntu.com compare_uri = de.archive.ubuntu.com -> True """ # remove traling spaces and "/" compare_uri = compare_uri.rstrip("/ ") master_uri =...
def display_benign_graph(value): """ Function that either displays the graph of the top 20 benign domains or hides them depending on the position of the toggle switch. Args: value: Contains the value of the toggle switch. Returns: A dictionary that communicates with the Dash inter...
def pollardlambda(g, p, t, q, b, w, theta=8) : """ Find x = dlog_g(t) in Z/pZ*, given that is in [b, b+w]. """ from itertools import count from math import sqrt # Size of domain of f (heuristic). #L = int(sqrt(w)) L = 5 # Psuedorandom function to walk on exponents. def f(TW) : # return 1 return pow(2, T...
def _hue_process_transition_time(transition_seconds): """ Transition time is in 1/10th seconds and cannot exceed MAX_TRANSITION_TIME. """ # Max transition time for Hue is 900 seconds/15 minutes return min(9000, transition_seconds * 10)
def _pop(line, key, use_rest): """ Helper for the line parser. If key is a prefix of line, will remove ir from the line and will extract the value (space separation), and the rest of the line. If use_rest is True, the value will be the rest of the line. Return a tuple with the value and the r...
def misclassification_rate(preds, alt_preds, k=1): """ Computes the misclassification rate for a group of base and alternative predictions. For details, check: Narodytska, Nina, and Shiva Prasad Kasiviswanathan. "Simple black-box adversarial perturbations for deep networks." arXiv preprint arXiv:1612.06...
def l2_bit_rate(packet_size, preamble, pps): """ Return the l2 bit rate :param packet_size: packet size on the line in bytes :param preamble: preamble size of the packet header in bytes :param pps: packets per second :return: l2 bit rate as float """ return (packet_size * preamble) * pps
def get_node_attr_by_key(nodes, key, attr, subkey=None): """ returns given attribute of element in nodes (=filtered by key) """ if not subkey: possible_nodes = [node for node in nodes if node['key'] == key] else: possible_nodes = [node for node in nodes if node['key'] ...
def _toint(string): """ Some bits sometimes are a character. I haven't found what do they mean, but they break cinfony fingerprints unless taken care of. This functions is just for that. """ if string.isdigit(): return int(string) else: return 0
def flare_value(flare_class): """Convert a string solar flare class [1] into the lower bound in W/m**2 of the 1-8 Angstrom X-Ray Band for the GOES Spacecraft. An 'X10' flare = 0.001 W/m**2. This function currently only works on scalars. Parameters ---------- flare_class : string c...
def delete_from(string, deletes): """ Delete the strings in deletes from string. """ for d in deletes: string = string.replace(d, '') return string
def main(A): """Pythagorean Triplet in Array A.""" squares = sorted([x**2 for x in A]) for x in reversed(squares): for y in squares[0: squares.index(x)]: if x - y in squares[squares.index(y): squares.index(x)]: retu...
def get_iou(bb1, bb2): """ Calculate the coverage of two bounding boxes. Parameters ---------- bb1 : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner bb2 : dict Keys: {'x1', '...
def all_keys_known(dictionary, known_keys, logger=None): """ Checks whether all keys of the dictionary are listed in the list of known keys. :param dictionary: dict, dictionary whose keys are verified :param known_keys: list, list of known keys :param logger: logger instance :return: ...
def ricc_lrcf_solver_options(lrradi_tol=1e-10, lrradi_maxiter=500, lrradi_shifts='hamiltonian_shifts', hamiltonian_shifts_init_maxiter=20, hamiltonian_shifts_init_seed=None, h...
def check_height(hgt): """hgt (Height) - a number followed by either cm or in: If cm, the number must be at least 150 and at most 193. If in, the number must be at least 59 and at most 76. """ num, unit = hgt[:-2], hgt[-2:] if unit == 'cm' and (150 <= float(num) <= 193): return True...
def _get(weather_data, item): """get the data from url""" return weather_data.get(item, "")
def custom_sort(stack): """Custom version of list sort. This should never be used.""" new_stack = [] while len(stack): temp = stack.pop() while len(new_stack) and new_stack[-1] > temp: stack.append(new_stack.pop()) new_stack.append(temp) return new_stack
def doMath(op, op1, op2): """ compute the infix statement""" #checks what operator is being used and returns the result if op == "^": return op1 ^ op2 elif op == "*": return op1 * op2 elif op == "/": if op2 == 0: #raises an error when divided by zero ...
def get_hd_domain(username, default_domain='default'): """Returns the domain associated with an email address. Intended for use with the OAuth hd parameter for Google. Args: username: Username to parse. default_domain: Domain to set if '@suchandsuch.huh' is not part of the username. Defaults to ...
def vnc_bulk_get(vnc_api, obj_name, obj_uuids=None, parent_uuids=None, fields=None): """Get bulk VNC object.""" # search using object uuid list or parent uuid list chunk_size = 20 obj_list = [] chunk_idx = 0 if obj_uuids and parent_uuids or obj_uuids and not parent_uuids: ...
def translate(sequence): """ Translates a given nucleotide sequence to a string or sequence of amino acids. returns a string of sequence of amino acids. :param sequence: :return: """ valid = (len(sequence) % 3 == 0) table = { 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M...
def __rall_power(parent_diam,e=1.5): """ Returns the diameter of a child segment of a branch according to Rall's Power Law as described in Van Ooyen et al 2010. Assumes child branches will be of equal diameter. """ child_diam=parent_diam/(2**(1/e)) return child_diam
def tokenize_chinese_chars(text): """Adds whitespace around any CJK character.""" def _is_chinese_char(cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Uni...
def _determine_format(format_string: str): """ Determines file format from a string. Could be header/ext. Args: format_string: Header or file extension. Returns: str: Type of the image. """ formats = ["PNG", "TIF", "TIFF", "JPG", "JPEG"] for fo...
def urljoin(base, *args): """ :param base: :param args: :return: """ url = base if url[-1] != '/': url += '/' for arg in args: arg = arg.strip('/') url += arg + '/' if '?' in url: url = url[:-1] return url
def as_strs(x): """Convert a list of items to their string representations""" return [str(xi) for xi in x]
def msb(n): """Given an integer >= 0, return the most significant bit position.""" assert n < 2**32 c = 0 while n > 0: n >>= 1 c += 1 return c
def check_sample(n_samples: int, sample: int) -> bool: """ Check sample is between 0 <= from_sample < n_samples Parameters ---------- n_samples : int Number of samples sample : int Sample to check Returns ------- bool Return True if no errors Raises ...
def appname_task_id(appname): """Returns the task id from app instance name.""" _appname, taskid = appname.split('#') return taskid
def _bowtie_major_version(stdout): """ bowtie --version returns strings like this: bowtie version 0.12.7 32-bit Built on Franklin.local Tue Sep 7 14:25:02 PDT 2010 """ version_line = stdout.split("\n")[0] version_string = version_line.strip().split()[2] major_version = int(versi...
def get_json_list(list_of_strings, include_brackets=True): """ Convert a list of strings into a single string representation, suitable for inclusion in GraphQL queries. Parameters --------- list_of_strings : list of str Strings to convert to single string include_backets : bool ...
def _map_key_binding_from_shortcut(shortcut): """Return a keybinding sequence given a menu command shortcut""" if not shortcut: return None keys = shortcut.split("+") key_mappings = {"Cmd": "Command", "Ctrl": "Control"} keybinding = [] for k in keys: if k in key_mappings: ...
def parseKernelLog(raw): """Parse a raw message from kernel log format /dev/kmsg record format: facility,sequence,timestamp,[optional,..];message\n Args: raw : the raw log message as a string Returns: {level, sequence, timestamp, message} message None on format error ...
def output_test(filename: str, pattern: str) -> bool: # pylint: disable=unused-argument """Test the output. Always passes if ``pattern == "pass"``. Otherwise, fails. """ return pattern == "pass"
def compute_internet_checksum(data): """ Function for Internet checksum calculation. Works for both IP and UDP. """ checksum = 0 n = len(data) % 2 # data padding pad = bytearray('', encoding='UTF-8') if n == 1: pad = bytearray(b'\x00') # for i in range(0, len(data + pad)...
def is_blank(value): """Check for blankness. Args: value: The value to check Returns: True if value is an empty string, not a string, etc. False if value is a non-empty string """ if value is None: return True if isinstance(value, str) is False: return...
def get_cheat_sheet(cheat_sheet): """converts a cheat sheet from .json to string to display Parameters ---------- :param dictionary cheat_sheet: dictionary that stores the content of given cheat sheet. :return: a str representation of a cheat sheet. """ sheet = [] separator = '\n' ...
def parse_no_db(cmd, args, user): """ Parses commands relating to locating and opening a database """ cmd = cmd.lower() if cmd == "open" or cmd == "connect": if args: try: user.connect(args) return f"successfully connected to {' '.join(args)}" ...
def update_tr_radius(Delta, actual_reduction, predicted_reduction, step_norm, bound_hit): """Update the radius of a trust region based on the cost reduction. Returns ------- Delta : float New radius. ratio : float Ratio between actual and predicted reductions. Z...
def calculate_internal_jumps(alignments): """ Count number of times the set of source word indices aligned to a target word index are not adjacent Each non adjacent set of source word indices counts only once >>> calculate_internal_jumps([{1,2,4}, {42}]) 1 >>> calculate_internal_jumps([{1,2,3,4}...
def integer_to_ascii_symbol(value): """Convert value to ascii symbol.""" if(value == 0): return ' ' elif(value == 1): return '+' elif(value == 2): return '#'
def name_parser(name): """ {INDEX}.png """ seg = name.split(".") return "Dataset index: {}".format(seg[0])
def mysorted(*args, **kwargs): """sorted that accepts the chunksize param""" _ = kwargs.pop("chunksize", None) return sorted(*args, **kwargs)
def serialize_recent_url(analysis, type_str): """Convert output of images to json""" tmp_output = [] output = {} if type_str == 'recentimages-thumbs': output['id'] = None output['type'] = type_str for e in range(len(analysis)): temp_obj = { 'source': a...
def fill_template(map_filepath, resolution, origin): # NOTE: Copied from generate_map_yaml.py """Return a string that contains the contents for the yaml file, filling out the blanks where appropriate. Args: map_filepath: Absolute path to map file (e.g. PNG). resolution: Resolution of each ...
def count_consecutives(tosses): """ Counts the number of consecutive heads or tails. """ consecutive_tosses = 1 max_consecutive_tosses = 1 for i in range(0, len(tosses) - 1): if tosses[i] == tosses[i + 1]: consecutive_tosses += 1 max_consecutive_tosses = max(max_c...
def is_parent( parent_path, path ): """ Is a path the parent path of another path? /a/b is the parent of /a/b/c, but /a/b is not the parent of /a/b/c/d or /a/e or /f. """ pp = parent_path.strip("/") p = path.strip("/") if not p.startswith( pp ): return False if "/" in pp[len(p...
def imports_on_separate_lines(logical_line): """ Imports should usually be on separate lines. """ line = logical_line if line.startswith('import '): found = line.find(',') if found > -1: return found, "E401 multiple imports on one line"
def calculate_input_voltage(excitation, Rdc, nominal_impedance): """Simplify electrical input definition to input voltage.""" val, type = excitation if type == "Wn": input_voltage = (val * nominal_impedance) ** 0.5 elif type == "W": input_voltage = (val * Rdc) ** 0.5 elif type == "V"...
def headerns(target): """ Returns the header_namespace of a target, suffixed with a /, or empty string if no namespace. target: JSON map for a target. """ ns = target['headerNamespace'] if 'headerNamespace' in target else "" return ((ns + "/") if len(ns) > 0 else "")