content
stringlengths
42
6.51k
def sample_n_shape_converter(size): """Convert `size` to the proper format for performing sample_n. """ if size is None: return size if size == (): size = None else: if isinstance(size, int): size = (size,) size = (-2,) + size return size
def snakecase(var): # some_variable """ Snake case convention. Include '_' between each elements. :param var: Variable to transform :type var: :py:class:`list` :returns: **transformed**: (:py:class:`str`) - Transformed input in ``snake_case`` convention. """ return "_".join(var)
def is_valid_account_number(account_number): """ Checks if the given account number is valid """ if len(str(account_number)) != 64: return False try: bytes.fromhex(account_number) except Exception: return False return True
def bbcommon(bb, bbother): """ Checks for overlaps of bounding boxes. First, east-west, then north-south. Element 0 is west, element 2 is east, element 1 is north, element 3 is south All four checks must be false for chflag to be true, meaning the two ...
def bounding_box2D(coords): """Runs through a collection of x,y tuple pairs and extracts the values (xmin,ymin),(xmax,ymax).""" xmin = coords[0][0] ; xmax = coords[0][0] ymin = coords[0][1] ; ymax = coords[0][1] for xy in coords[1:]: x, y = xy if x < xmin: xmin = x if ...
def expectedPrimerPair(l,r): """ Inputs: left primer Segment right primer Segment Check if 2 primers come from the same primer pair Returns: Boolean """ return l[2] == r[2]
def retry_on_do_retry(value): """ Function that returns True (retries) on the value 'do_retry'. Args: value: The value to check against. Returns: (bool): Whether this should trigger a retry. """ if value == 'do_retry': return True else: return False
def RA2degRA(RA): """ Convert the RA string to float. Parameters ---------- RA : string Returns ------- degRA : float units are in degrees Examples -------- >>> ... """ hr = float(RA[0:2]) mn = float(RA[3:5]) sc = float(RA[6:]) ...
def mechanismHub_oracle_price_j(params, substep, state_history, prev_state, policy_input): """ This mechanismHub returns the updated oracle price for token j. """ return 'oracle_price_j', prev_state['oracle_price_j']
def is_numeric(value): """ Convenience function check if value is numeric :param value: value to check :return: True/False """ try: 0 + value return True except TypeError: return False
def var_to_list(var): """change the var to be a list. """ if isinstance(var, list): return var if not var: return [] return [var]
def same_class(instances, class_index): """ Determines if all the instances have the same class label :param instances: table :param class_index: index of the class label :return: True if all have same class label flase otherwise """ label = instances[0][class_index] for row in instances: ...
def _get_database_name(db_uri: str) -> str: """Get DB name in cluster from a MongoDB connection url""" db_name: str = db_uri.split("/")[-1] if "?" in db_name: db_name = db_name.split("?")[0] return db_name
def binary_radix_sort(k, arr): """ Radix sort for base 2 for a list of integers in the range [0, k) """ i = 0 while (1 << i) < k: buckets = [[], []] for key in arr: digit = (key // (1 << i)) & 1 buckets[digit].append(key) arr = [] for j in range(2): for key in buckets[j]: ...
def left_center_right(leftset, rightset): """Return left only, center (common) and right only elements""" left = leftset - rightset common = leftset & rightset right = rightset - leftset return left, common, right
def fibonacci(n): """ Return the n_th Fibonnaci number $F_n$. The Fibonacci sequence starts 0, 1, 1, 2, 3, 5, 8, ..., and is defined as $F_n = F_{n-1} + F_{n-2}.$ >>> fibonacci(0) 0 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(-1) Traceback (most recent call la...
def arg_is_natural_num(arg): """Return whether the string arg contains a natural number. >>> arg_is_natural_num('123') True >>> arg_is_natural_num('0') True >>> arg_is_natural_num('-1') False >>> arg_is_natural_num('1.5') False >>> arg_is_natural_num('foo2') False >>> ar...
def _merge_handler(prev_props, next_props): """On conflict in updating runtime-props, take the newer ones, but make sure that 'resumed' is true of either was true""" if 'resumed' in prev_props or 'resumed' in next_props: next_props['resumed'] = (prev_props.get('resumed', False) or ...
def reg2deg(reg): """ Converts phase register values into degrees. :param cycles: Re-formatted number of degrees :type cycles: int :return: Number of degrees :rtype: float """ return reg*360/2**32
def parse_failing_tryjobs(message): # pragma: no cover """Parse the message to extract failing try jobs.""" builders = [] msg_lines = message.splitlines() for line in msg_lines[1:]: words = line.split(None, 1) if not words: continue builder = words[0] builders.append(builder) return bui...
def parse_time(value: str) -> int: """ Parses the string into a integer representing the number of milliseconds. """ if value.endswith("ms"): return int(float(value.replace("ms", ""))) return int(float(value.replace("s", "")) * 1000)
def feat_overlap(f1, f2): """ Given two features (lists of length=9 from GFF3), determine whether they overlap. """ f1start = int(f1[3]) f1end = int(f1[4]) f2start = int(f2[3]) f2end = int(f2[4]) if f1start <= f2end and f1end >= f2start: return True return False
def equal(param1, param2): """ Compare two parameters and return if they are equal. This parameter doesn't run equal operation if first parameter is None. With this approach we don't run equal operation in case user don't specify parameter in their task. :param param1: user inputted parameter ...
def split_chain(chain): """ Split the chain into individual certificates for import into keystore :param chain: :return: """ certs = [] if not chain: return certs lines = chain.split('\n') cert = [] for line in lines: cert.append(line + '\n') if line =...
def get_qs_url(url, args): """ Accepts url string and dictionary of querystring parameters, returns properly formatted url. """ qs_url = url i = 0 for k, v in args.items(): if i == 0: qs_url += "?" else: qs_url += "&" qs_url += str(k) + "=" + s...
def bytes2human(n): """ >>> bytes2human(10000) '9K' >>> bytes2human(100001221) '95M' """ symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: ...
def convert_SI(val, unit_in, unit_out): """Unit converter. Args: val (float): The value to convert. unit_in (str): The input unit. unit_out (str): The output unit. Returns: float: The value after unit conversion. """ SI = { "cm": 0.01, "m": 1.0, ...
def version_update_handler(version, version_update_strategy): """ This method takes the current version and a function that produces a new version, and removes and re-adds non-numeric version qualifiers (such as "-SNAPSHOT"), if necessary. 1st argument: the current version 2nd argument: a func...
def clamp(value, lower=None, upper=None): """ Returns value no lower than lower and no greater than upper. Use None to clamp in one direction only. """ if lower is not None: value = max(value, lower) if upper is not None: value = min(value, upper) return value
def comparable(a, b): """ Tests if two sets of comparable. Parameters ---------- a : set One set. b : set The other set. Returns ------- comp : bool True if `a` is a subset of `b` or vice versa. """ return a < b or b < a
def get_email_from_user(user): """Get email address for user returned by cognito or database.""" key = "UserAttributes" if "UserAttributes" in user else "Attributes" return next(filter(lambda x: x["Name"] == "email", user[key]), {}).get("Value")
def is_message(event, no_channel=False): """Check whether an event is a regular message.""" return ('type' in event and event['type'] == 'message' and (no_channel or ('channel' in event and event['channel'])) and 'text' in event and not ('reply_to' in event) and '...
def parse_convergence_section(convergence_section_dict): """ Parse the convergence section dictionary Parameters ---------- convergence_section_dict : dict dictionary """ convergence_parameters = ["damping_constant", "threshold"] for convergence_variable in ["t_inner", "t_rad"...
def deep_update(target, source): """ Deep merge two dicts """ if isinstance(source, dict): for key, item in source.items(): if key in target: target[key] = deep_update(target[key], item) else: target[key] = source[key] return target
def iob_iobes(tags): """Transform tags in IOB format to IOBES format Args: tags (list): tags in IOB format Returns: list: tags in IOBES format """ new_tags = [] for i, tag in enumerate(tags): if tag == 'O': new_tags.append(tag) elif tag.split('-')[0...
def create_motion_name(test_name, sensor_code, code_suffix=""): """ Builds the full name of the file :param test_name: str, test name :param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M) :param code_suffix: str, suffix :return: """ return "%s-%s-%s" % (test_name, sensor_code, co...
def _set_up_gpg_env_vars_for_gpg_command(gpg_home_dir, gpg_command_args): """Produce a new command arguments that set required GPG env vars before running the command.""" result = [ "env", "-u", "GPG_AGENT_INFO", # There should not be a GPG agent on the system, unset the env var. ...
def substr_replace(string, starts, lengths, replace): """Replace substrings""" if not isinstance(starts, (tuple, list)): starts = [starts] if not isinstance(lengths, (tuple, list)): lengths = [lengths] assert len(starts) == len(lengths) if not isinstance(replace, (tuple, list)): replace = [replace] * len(sta...
def _check_maybe_route(variable_name, variable_value, route_to, validator): """ Helper class of ``Command`` parameter routing. Parameters ---------- variable_name : `str` The name of the respective variable variable_value : `str` The respective value to route maybe. route_to...
def formatAllArgs(args, kwds): """ makes a nice string representation of all the arguments :type args: ``list`` :param args: function arguments (required) :type kwds: ``dict`` :param kwds: function keyword arguments (required) :return: string representation of all the arguments :rtype...
def sample(X, y, sampling_fn): """Sample the given X and y data""" if sampling_fn is None: return X, y if not hasattr(sampling_fn, 'fit_resample'): raise ValueError(('Sampling function must implement' ' a "fit_resample" method')) X_samp, y_samp = sampling_...
def parse_reg_05h_byte(byte_val: int) -> int: """ Channel control (CH) 0-83. 84 channels in total 850.125 + CH *1MHz. Default 868.125MHz(SX1262), 410.125 + CH *1MHz. Default 433.125MHz(SX1268) """ assert 0 <= byte_val <= 83 return byte_val
def str_bool(s): """Make a sane guess for whether a value represents true or false. Intended for strings, mostly in the context of environment variables, but if you pass it something that's not a string that is falsy, like an empty list, it will cheerfully return False. """ if not s: ret...
def list_to_string(l): """take a python and return as string with all values in doubble quotes for SQL """ start = '' for x in l: start += f"\"{str(x)}\"," start = start.rstrip(',') return start
def _schultz_get_closest_extrema(contour): """ Part of Step 11. Returns the closest repeating extrema to the start and end of the contour. From Ex15B: >>> contour = [ ... [1, {1, -1}], ... [3, {1}], ... [0, {-1}], ... [3, {1}], ... [0, {-1}], ... [3, {1}], ... [0, {-1}], ... [3, {1}], ... [2, {1...
def server_role(server_tag, role_map): """ 1) given server name, determine node id from HostnameMap 2) given node id, determine role a) remove stack name from the beginning of the node id b) replace node id index with %index% c) find matching Scheduler Hints """ print("Tag: {}, R...
def calculate_indent(text): """ :param text: :type text: str :return: """ indent = 0 for c in text: if c is '\t': raise ValueError() if c is not ' ': return indent,text[indent:] indent += 1 return indent,''
def real_return(nominal_return, inflation_rate): """Calculate an inflation-adjusted return. Parameters ---------- nominal_return : float Nominal return. inflation_rate : float Inflation rate. Returns ------- float Real (inflation-adjusted) return. """ re...
def compress_dhist(dh): """Compress a directory history into a new one with at most 20 entries. Return a new list made from the first and last 10 elements of dhist after removal of duplicates. """ head, tail = dh[:-10], dh[-10:] newhead = [] done = set() for h in head: if h in ...
def _to_camel_name(name): """ Convert name to camel name. example: SysUser will convert to sysUser SysRole will convert to sysRole """ if name is not None and len(name) > 1: return name[0].lower() + name[1:] return name
def cumulative_discounted_rewards(trajectories): """calculate the cumulative rewards for the given trajectories 1. input: a list of trajectories is a list of tuples, one tuple being comprised of the following values, IN ORDER: 1. current state (s) 2. action agent chooses (a) 3. reward (r...
def expand_url(url, protocol): """ Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap' """ if protocol == 'soap': ws_part = 'api/?wsdl' elif protocol == 'xmlrpc': ws_part = 'index.php...
def hey(phrase: str) -> str: """Return Bob's response to a given phrase.""" phrase = phrase.strip() if not phrase: # if you address him without actually saying anything return "Fine. Be that way!" if phrase.isupper(): # if you yell at him if phrase.endswith('?'): # if you yell a ques...
def get_bbox_area(roi): """ Returns the bbox area :param roi: the bbox to use :return: area of the given bbox """ return (roi[3] - roi[1]) * (roi[2] - roi[0])
def sdf_enum_array(enumArray): """ Take the enum array value and additionally parse for sdf :param enumArray: array of items associated with enum type :return: json formatted string """ output = "[" for i, item in enumerate(enumArray): output = output + "\"" + item + "\"" ...
def wrap(a): """Wrap a floating-point number or array to the range -0.5 to 0.5.""" return (a + 0.5) % 1 - 0.5
def zip_with(f, xs, ys): """ Generalization of zip where the function f is applied instead of making a tuple. """ return [f(a, b) for (a, b) in zip(xs, ys)]
def electric_humidification_unit(g_hu, m_ve_mech): """ Refactored from Legacy Central AC can have a humidification unit. If humidification load is present, only the mass flow of outdoor air to be humidified is relevant :param g_hu: humidification load, water to be evaporated (kg/s) :type g_hu: ...
def normalizeExpression(licsConcluded): """ Combine array of license expressions into one AND'd expression, adding parens where needed. Arguments: - licsConcluded: array of license expressions Returns: string with single AND'd expression. """ # return appropriate for simple cases ...
def _gen_resource_type_index(service: str, resource_type: str) -> str: """Generate a hash key for the resource type index. Arguments: service (str): The service name (e.g. ``'ec2'``) resource_type (str): The resource type (e.g. ``'instance'``) """ return f"{service}#{resource_type}"
def get_next_func(step, func, deriv): """ (theta)i+1 = (theta)i + d_xi *[ (d_theta/d_xi)i+1]. """ return func + step * deriv
def url_resolver(url): """Resolve url for both documentation and Github online. If the url is an IPython notebook links to the correct path. Args: url: the path to the link (not always a full url) Returns: a local url to either the documentation or the Github """ if url[-6:] == '...
def normalize(x, scale, offset, reverse=False): """ Normalize data or reverse normalization :param x: data array :param scale: const scaling value :param offset: const offset value :param reverse: boolean undo normalization :return: normalized x array """ if reverse: return x...
def control_1_6_password_policy_lowercase(passwordpolicy): """Summary Args: passwordpolicy (TYPE): Description Returns: TYPE: Description """ result = True failReason = "" offenders = [] offenders_links = [] control = "1.6" description = "Ensure IAM password pol...
def get_key(dictlike, key): """Filter to return a dictionary value by name Returns ``None`` if the key does not exist so either check or use ``|default_if_none`` Usage:: {{ my_dict|get_key:"the key I want" }} """ return dictlike.get(key, None)
def get_not_none(node, attr, default): """ Returns ``node[attr]``. If it doesn't exists or is ``None``, return `default`. Parameters ---------- node: collections.abc.Mapping attr: collections.abc.Hashable default The value to return if ``node[attr]`` is either ``None``, or does ...
def predicate(line): """ Remove lines starting with `#` """ if "#" in line: return False return True
def is_int(potential_int: str) -> bool: """ Check if potential_int is a valid integer. Parameters ---------- potential_int : str Returns ------- is_int : bool Examples -------- >>> is_int('123') True >>> is_int('1234567890123456789') True >>> is_int('0') ...
def exists(thing=None, dictionary=None, key=None): """ Figure out if something exists. Args: thing (any): Use by itself. Could be anything. dictionary (dict): Use with key. key (string): use with dictionary. """ exists = False try: if callable(thing): ...
def _fermat_prime_criterion(n,b=2): """Fermat's prime criterion Returns False if n is definitely composite, True if posible prime.""" return pow(b,n-1,n) == 1
def maybe_parse_str(val, parse_func, vtype): """Parse argument value with function if string. """ if val is None: return None if isinstance(val, str): val = parse_func(val) if not isinstance(val, vtype): raise TypeError("expect %s for %s" % (vtype, type(val))) return val
def eq(left: str, right: str) -> str: """Cypher equality comparison.""" return left + ' = ' + right
def strip_state_dict(state_dict, strip_key='module.'): """ Strip 'module' from start of state_dict keys Useful if model has been trained as DataParallel model """ for k in list(state_dict.keys()): if k.startswith(strip_key): state_dict[k[len(strip_key):]] = state_dict[k] ...
def convert_to_demisto_severity(severity: str) -> int: """Maps HelloWorld severity to Cortex XSOAR severity Converts the HelloWorld alert severity level ('Low', 'Medium', 'High', 'Critical') to Cortex XSOAR incident severity (1 to 4) for mapping. :type severity: ``str`` :param severity: severi...
def prune_res_list(res_list, ran, one_word_or_letter): """ Check if res_list have consecutive lines that have only 1 word. If so , remove it/ :param res_list: :return: """ new_res_list = [] only_one = [] for res_i, res in enumerate(res_list): if one_word_or_letter == "word": ...
def get_salary_box(x): """ returns the int value for the ordinal value class :param x: a value that is either 'crew', 'first', 'second', or 'third' :return: returns 3 if 'crew', 2 if first, etc. """ if x == '>50K': return 1 else: return 0
def number(input): """Convert the given input to a floating point or integer value. In cases of ambiguity, integers will be prefered to floating point. :param input: the value to convert to a number :type input: any :returns: converted integer value :rtype: float or int """ ...
def string_to_binary(string, to_type): """ Converts a string into the desired type """ b = None if to_type == 'b': # Boolean b = int(string) elif to_type == 'B': # Byte b = int(string) elif to_type == 'h': # Short b = int(string) elif to_type == 'i...
def check_data_consistency(data1, data2): """Assumes data1 and data2 of any type. Returns True if they are equal, False otherwise""" if data1 == data2: return True return False
def delta_fxn(a, b): """Kronecker delta for objects `a` and `b`. Parameters ---------- a : First object b : Second object Returns ------- delta |int| -- Value of Kronecker delta for provided indices, as tested by Python ``==`` """ retur...
def rep_last(some_list, n): """ Makes a list have a number of elements divisible by n, by repeating the last entry """ while not (len(some_list)%n == 0): some_list.append(some_list[-1]) return some_list
def gender_identification(f_name): """return gender based on last letter of first name and lenght of name""" return {'last_letter': f_name[-1], 'lenght':len(f_name)}
def flatten(l): """Flatten a list of elements and/or lists recursively.""" out = [] for item in l: if isinstance(item, (list, tuple)): out.extend(flatten(item)) else: out.append(item) return out
def get_epsilons(max_attr): """ Given all explanations of one SNN model across both data subjects, find the epsilons at 25, 50 and 75% of the attribution range of positive attributions :param max_attr: maximum absolute attribution value :return: """ epsilons = [(0), (0.25 * max_attr), (0.5 *...
def section(name, underline_char='='): """ Generate reST section directive with the given underline. :Examples: >>> section('My section') ''' My section ========== <BLANKLINE> ''' >>> section('Subsection', '~') ''' Subsection ~~~~~~~~~~ <BLANKLINE> ''' """...
def get_all_user_ids(tweets, user_mentions): """Creates a list of all user_ids in tweets and user_mentions""" id_set = set() # the user_id of the target if tweets: id_set.add(tweets[0].user_id) id_set |= set([m.user_id for m in user_mentions]) id_set |= set([t.in_reply_to_user_id for...
def norm_mac(mac): """Normalize a MAC Address from the pypowervm format to the neutron format. That means that the format will be converted to lower case and will have colons added. :param mac: A pypowervm mac address. E.g. 1234567890AB :returns: A mac that matches the standard neutron format. ...
def _partition(l, pred): """ partitions a list according to boolean predicate """ res = ([], []) for x in l: res[not pred(x)].append(x) return res
def from_wsgi_header(header): """Convert a WSGI compliant HTTP header into the original header. See https://www.python.org/dev/peps/pep-3333/#environ-variables for information from the spec. """ HTTP_PREFIX = "HTTP_" # PEP 333 gives two headers which aren't prepended with HTTP_. UNPREFIXED_H...
def suffix_length(needle, p): """ Returns the maximum length of the substring ending at p that is a suffix. """ length = 0 j = len(needle) - 1 for i in reversed(range(p + 1)): if needle[i] == needle[j]: length += 1 else: break j -= 1 return le...
def distance(X, Y): """Retrun distance between two points of equal dimensions.""" radicand = sum([(x - y)**2 for x, y in zip(X, Y)]) return radicand**0.5
def removeTailReturn(aStr): """ Return a string without the tail "\n" if it has one. """ if aStr[-1:] == "\n": return aStr[:-1] else: return aStr
def int_wrapper(string): """A helper function.""" if string.startswith('#$'): return int(string[2:], base=16) elif string.startswith('$'): return int(string[1:], base=16) return int(string, 0)
def set_model_par(model_par, settings): """[Sets model parameters based on settings dictionary] Arguments: model_par {[dictionary]} -- Dictionary with base parameters to modify settings {[dictionary]} -- [keys are names of model parameters, values are parameter values] Ret...
def get_item_or_attr(obj, key): """Get item from dictionary or attribute from object. Args: obj (object): Dictionary or object. key (str): Key. Returns: object: The object for the provided key. """ return obj[key] if isinstance(obj, dict) else getattr(obj, key)
def calc_p(z,z0,psurf): """Compute the pressure at a given level from some surface pressure""" slp=psurf/(1 - 2.25577E-5*z0)**5.25588 # if z0=0 then slp=psurf p = slp*(1 - 2.25577E-5*z)**5.25588 return p
def compute_area(point): """compute the poly area""" s = 0.0 point_num = len(point) if point_num < 3: return 0.0 for i in range(len(point)): s += point[i][1] * (point[i-1][0]-point[(i+1)%point_num][0]) return abs(s/2.0)
def IsApproximatelyEqual(x, y, epsilon): """Returns True if y is within relative or absolute 'epsilon' of x. By default, 'epsilon' is 1e-6. """ # Check absolute precision. if -epsilon <= x - y <= epsilon: return True # Is x or y too close to zero?0. if -epsilon <= x <= epsilon or -...
def PyTmHMSXtoS(h, m, s, x): """ Convert hours-minutes-seconds-milliseconds to seconds as float Parameters ---------- h: int, hours m: int, minutes s: int, seconds x: float, milliseconds Returns ------- float, seconds """ return h * 3600.0 + m * 60.0 + s + x
def discoverable(thing): """ return True if the string given is discoverable information, False if not """ if thing is not None and thing.strip() != "Unknown" and thing.strip() != "": return True return False