content
stringlengths
42
6.51k
def validKey(key, pkeys): """ Helper function """ if key in pkeys and len(pkeys[key]) > 0: return True return False
def _parse_ids(ids, info_dict): """Parse different formats of ``ids`` into the right dictionary format, potentially using the information in ``info_dict`` to complete it. """ if ids is None: # Infer all id information from info_dict return {outer_key: inner_dict.keys() for outer_key, inn...
def __get_params(argv): """Function to manage input parameters.""" # Correct syntax syntax = '%s pcap_input csv_output format' % argv[0] # Not enough parameters if len(argv) != 4: print('Usage: %s' % syntax) exit() # Return the parameters return argv[1], argv[2], argv[3]
def get_hosts(path, url): """ Creates windows host file config data :param path: :param url: :return: string """ info = """ # host for %%path%% 127.0.0.1\t%%url%% """.replace("%%url%%", url).replace("%%path%%", path) return info
def coerce_to_list(value): """Splits a value into a list, or wraps value in a list. Returns: value, as a sorted list """ if isinstance(value, list): return sorted(value) for split_char in (",", ";", ":", "|", " "): if split_char in value: return sorted([val.stri...
def compare_fw_versions( v1, v2 ): """ :param v1: left FW version :param v2: right FW version :return: 1 if v1 > v2; -1 is v1 < v2; 0 if they're equal """ v1_list = v1.split( '.' ) v2_list = v2.split( '.' ) if len(v1_list) != 4: raise RuntimeError( "FW version (left) '" + v1 + "'...
def return_statement(evaluator, ast, state): """Evaluates "return expr;".""" if ast.get("expr"): res = evaluator.eval_ast(ast["expr"], state) else: res = None return res, True
def split_by_max_length(sentence, max_text_length=128): """Standardize n_sentences: split long n_sentences into max_text_length""" if len(sentence) < max_text_length: return [sentence] split = sentence.split() new_n_sentences, text = [], [] for x in split: support_text = " ".join(...
def axis_helper(y_shape, x_shape): """ check which axes the x has been broadcasted Args: y_shape: the shape of result x_shape: the shape of x Return: a tuple refering the axes """ res = [] j = len(x_shape)-1 for i in range(len(y_shape)-1, -1, -1): if j < ...
def choice_text(val, choices): """Returns the display text associated with the choice value 'val' from a list of Django character field choices 'choices'. The 'choices' list is a list of two-element tuples, the first item being the stored value and the second item being the displayed value. Returns No...
def keep_step(metrics, step): """ Only keeps the values of the metrics for the step `step`. Default to None for each metric that does not have the given `step`. Args: metrics (dict): keys are metric names, values are lists of (step, value) pairs e.g. { ...
def aprs_to_redis(ts, par): """ change aprslib par onbject to a hash table redis can store """ return { "latitude":par.get("latitude", None), "longitude": par.get("longitude", None), "last_heard": ts, "symbol": par["symbol_table"]+par["symbol"], "from": par["from"...
def hex_no_0x(i): """ Return the equivalent of the C PRIx64 format macro. The removal of the extra L is to ensure Python 2/3 compatibility. """ tmp = str(hex(i)[2:]) if tmp[-1] == 'L': tmp = tmp[:-1] return tmp
def sum_numerator_fraction_expansion_e(x): """ Returns the digit sum of the numerator of the x-th continued fraction of e """ numerator = 1 if x % 3 == 2: denominator = 2*(x//3 + 1) else: denominator = 1 while x > 1: if x % 3 == 0: numerator += 2*(x//3)*de...
def solve_capcha(capcha_str): """Function which calculates the solution to part 1 Arguments --------- capcha_str : str, a string of numbers Returns ------- total : int, the sum of adjacent matches """ capcha = [int(cc) for cc in list(capcha_str)] total = 0 for ii in...
def number_formatter(number, pos=None): """Convert a number into a human readable format.""" magnitude = 0 while abs(number) >= 100: magnitude += 1 number /= 100.0 return '%.1f%s' % (number, ['', '', '', '', '', ''][magnitude])
def is_string(val): """ Return True iff this is a string """ return isinstance(val, str)
def get_sent_id(corpus_id, doc_id, naf_sent_id, fill_width=8): """ :param corpus_id: :param doc_id: :param naf_sent_id: :return: """ nltk_sent_id = '' for id_ in [corpus_id, doc_id, naf_sent_id]: id_filled = str(id_).zfill(fill_wi...
def check_historical(previous_downs, current_downs): """ Runs a comparison check between two failed ping test dictionaries to determine whether the tests have recently failed, recovered or in a recent warning state. Parameters: previous_downs - dictionary of previously failed and warn sta...
def extract_y(lst): """ Extract y coordinate from list with x, y, z coordinates :param lst: list with [[x, y, z], ..., [x, y, z]] :return: list with y coordinates [x, ..., x] """ return [item[1] for item in lst]
def pad_with_zeros(hist_list): """ For each year which doesn't exist here, put 0 """ last_year = hist_list[0][0] - 1 # initialize to be less than the first year i = 0 while i < len(hist_list): year_item = hist_list[i] if year_item[0] - last_year > 1: # fill the gap ...
def triangle_coordinates(i, j, k): """ Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangles are parallel to the lower axis on the lower side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A numpy ar...
def convert_attribute(aim_attribute, to_aim=True): """Convert attribute name from AIM to ACI format converts from this_format to thisFormat :param aim_attribute: :return: """ if to_aim: # Camel to _ (APIC to AIM) result = [] for x in aim_attribute: if x.isupp...
def send_message(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Messag...
def split_list_email(str_email): """ return list to emails """ if not isinstance(str_email, list): return [e.strip() for e in str_email.split(",")] return str_email
def merge(root_config, *args): """Merge two configuration dictionaries together.""" root = root_config.copy() for arg in args: clean = {k: v for k, v in arg.items() if v is not None} root.update(clean) return root
def get_patches_per_dimension(dimension: int, size: int, stride: int) -> int: """ Returns the number of patches that can be created in the given dimension without going over the dimension bounds. """ assert size % stride == 0 overlapping = (size // stride) - 1 if stride != size else 0 retur...
def check_url(url): """ Check if exist a well-formed url""" if url[:8] == "https://" or url[:7] == "http://": return True else: return False
def migrate_packetbeat(line): """ Changes things like `interfaces:` to `packetbeat.interfaces:` at the top level. """ sections = ["interfaces", "protocols", "procs", "runoptions", "ignore_outgoing"] for sec in sections: if line.startswith(sec + ":"): return ["...
def is_strong_subclass(C, B): """Return whether class C is a subclass (i.e., a derived class) of class B and C is not B. """ return issubclass (C, B) and C is not B
def worst_resident_index(hospital, hospital_prefs_dict, matched_dict): """ returns the index of worst resident assigned to the hospital based on hospital's prefrences list. """ idxs = [] for res in hospital_prefs_dict[hospital]: if res in matched_dict[hospital]: idxs.append(...
def strip(line): """Removes any \r or \n from line and remove trailing whitespaces""" return line.replace('\r\n', '').strip()
def hash_add(element, table_size): """ Hash by adding the ascii values of the letters in the string. Return an integer. """ char_val_list = list(map(lambda x: ord(x), str(element))) hash_val = 0 for val in char_val_list: hash_val += val index = hash_val % table_size return ...
def map_traps(prev_pat, row_limit): """Work out the number of safe tiles in a trapped room.""" safe = prev_pat.count('.') row = 1 while row < row_limit: next_row = '' trap_patterns = ('^^.', '.^^', '^..', '..^') pattern = '.{}{}'.format(prev_pat[0], prev_pat[1]) if patte...
def shortest_angle_interpolation(start, end, amount): """ This interpolation method considers the 'start' and 'end' as angles in a circumference where the objective is to find the smallest arch between two angles. param start: Start angle with values in the range of [0 to 360[ param end: Final angle...
def make_creator(child): """Generate code-block for creating sub-resources""" if child.get("creator") is None: return "" class_ = child["class"] name = child["name"] creator_name = child["creator"]["name"] path = child['json_path'] path = path.rstrip('.*') return ( f""" ...
def is_p2sh(script: bytes) -> bool: """ Determine whether a script is a P2SH output script. :param script: The script :returns: Whether the script is a P2SH output script """ return len(script) == 23 and script[0] == 0xa9 and script[1] == 0x14 and script[22] == 0x87
def convertObjectsToXml(result_set): """ Convert a set of objects to XML using the get_xml method of those objects. result_set must be an object capable of being iterated over. """ xmlstream = [] for result in result_set: xmlstream.append(result.get_xml()) xmlstream = map(...
def scales_from_voices_per_octave(nu, range): """Returns the list of scales based on the voices per octave parameter """ return 2 ** (range / nu)
def WendlandC6_2D(u: float, h_inv: float): """ Evaluate the WendlandC6 spline at position u, where u:= x*h_inv, for a 2D projection. Values correspond to 295 neighbours. """ norm2D = 78. / (7. * 3.1415926) if u < 1.0: n = norm2D * h_inv**2 u_m1 = (1.0 - u) u_m1 = u_m1 *...
def cell_multiply(c, m): """ Multiply the coordinates (cube or axial) by a scalar.""" return tuple( m * c[i] for i in range(len(c)) )
def number(value, minimum=None, maximum=None, cut=False, pad=False): """Returns back an integer from the given value""" value = int(value) if minimum is not None and value < minimum: if pad: return minimum raise ValueError( "Provided value of {} is below specified min...
def sum(data): """ Get sum of list elements. """ result = 0 for value in data: result += value return result
def decode(x: bytes) -> str: """Decode a string like done in `os._createenviron` (hard-coding utf-8)""" return x.decode("utf-8", errors="surrogateescape")
def _amzs(pHI,pFA): """recursive private function for calculating A_{MZS}""" # catch boundary cases if pHI == pFA == 0 or pHI == pFA == 1: return .5 # use recursion to handle # cases below the diagonal defined by pHI == pFA if pFA > pHI: return 1 - _amzs(1-pHI, 1-pFA) ...
def check_inputs(input1, input2): """ Checks the inputs given to ensure that input1 is a list of just numbers, input2 is a number, and input2 is within input1. Raises an exception if any of the conditions are not true. >>> check_inputs([1, 2.0, 3.0, 4], 4) 'Input validated' >>> check_i...
def prepend_license(license_text, src_text, file_extension): """Prepend a license notice to the file commented out based on the extension. Args: src_text (str): The text which will have the license prepended. file_extension (str): The relevant file extension. Returns: str: The full...
def batch_image(im_list, batch_size): """ to put the image into batches """ bs = batch_size fnames = [] fname = [] for _, im_name in enumerate(im_list): bs -= 1 fname.append(im_name) if bs == 0: fnames.append(fname) fname = [] bs = ...
def calc_chi_square_distance(counts_sim, counts_real): """Returns the chi-square-distance for the two histograms of simulator and quantum computer""" coefficient = 0 for key in counts_real.keys(): # add missing keys from quantum computer to simulator if key not in counts_sim.keys(): ...
def _best_art(arts): """Return the best art (determined by list order of arts) or an empty string if none is available""" return next((art for art in arts if art), '')
def find_largest_digit_helper(n, max_digit_now): """ :param n: int, the number which user wants to find max digit now :param max_digit_now: int, the max digit now :return: int, the max digit of n Reduce one digit in each recursive case to approach base case(n<10) """ if n < 0: # Negative number, should plus -1...
def merge(prevArtifacts, nextArtifacts): """Merge artifact lists with nextArtifacts masking prevArtifacts""" artifactList = list(nextArtifacts.copy()) artifactList.extend(prevArtifacts) merged = [] excludedNames = set() for artifact in artifactList: if artifact.name not in excludedName...
def isTheOnlyOne(elements): """ Checks whether there is the only one true positive object or not. @param {Array.<*>} elements. @return {boolean} True, if there is the only one element, which is not None, empty or 0. False if it's not. """ count = 0 ...
def _check_value(value): """Convert the provided value into a boolean, an int or leave it as it.""" if str(value).lower() in ["true"]: value = True elif str(value).lower() in ["false"]: value = False elif str(value).isdigit(): value = int(value) return value
def swap_key_val_dict(a_dict): """ swap the keys and values of a dict """ return {val: key for key, val in a_dict.items()}
def GCS(string1, string2): """ Returns: (str): The greatest (longest) common substring between two provided strings (returns empty string if there is no overlap) """ # this function copied directly from: # https://stackoverflow.com/a/42882629 answer = "" len1, len2 = len(st...
def set_verbosity(level=1): """Set logging verbosity level, 0 is lowest.""" global verbosity verbosity = level return verbosity
def _swap(x): # pylint: disable=invalid-name """Helper: swap the top two elements of a list or a tuple.""" if isinstance(x, list): return [x[1], x[0]] + x[2:] assert isinstance(x, tuple) return tuple([x[1], x[0]] + list(x[2:]))
def _get_baseline_options(site): """ Extracts baseline options from ``site["baseline"]``. """ # XXX default for baseline_beta currently set here options_dict = site["baseline"].copy() options_tuple = (options_dict.pop('nn_baseline', None), options_dict.pop('nn_baseline_input...
def longestPalindrome2(s): """ :type s: str :rtype: str """ dp=[[False for col in range(len(s))] for row in range(len(s))] res=[0,0]; for i in range(len(s)): dp[i][i]=True if i>1 and s[i]==s[i-1]: dp[i-1][i]=True res[0]=i-1 res[1]=i fo...
def dkeys(dict): """ Utility function to return the keys of a dict in sorted order so that the iteration order is guaranteed to be the same. Blame python3 for being FUBAR'd.""" return sorted(list(dict.keys()))
def get_units(name, attr_dict): """ """ try: units = attr_dict[name]["units"] if not isinstance(units, str): units = "{0}".format(units) except KeyError: units = None if units in [None, "None", "none"]: return None return units
def all_in(sequence1, sequence2): """ Confirm that all elements of one sequence are definitely contained within another """ return all(elem in sequence2 for elem in sequence1)
def object_type_repr(obj): """Returns the name of the object's type. For some recognized singletons the name of the object is returned instead. (For example for `None` and `Ellipsis`). """ if obj is None: return "None" elif obj is Ellipsis: return "Ellipsis" cls = type(obj)...
def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ cls = value.__class__ if cls.__module__ in set(['builtins', '__builtin__']): retur...
def mult_values(*values): """Return the product of values, considering only elements that are not None. An item v,w in values can be anything that contains __mul__ function such that v*1 and v*w is defined. """ current = 1 for v in values: if v is not None: current = v * curr...
def _trace_level(master): """Returns the level of the trace of -infinity if it is None.""" if master: return master.level return float('-inf')
def is_inside_image(xp, yp, r): """ Description of is_inside_image Returns True if the point is inside the image, False otherwise Args: xp (undefined): x pixel yp (undefined): y pixel r (undefined): radius of image """ return ((xp - r)**2 + (yp - r)**2) <= r**2
def num_to_str(num): """ Convert an int or float to a nice string. E.g., 21 -> '21' 2.500 -> '2.5' 3. -> '3' """ return '{0:0.02f}'.format(num).rstrip('0').rstrip('.')
def break_words(stuff: str) -> list: """This function will break up words for us""" words = stuff.split(' ') return words
def zoo(total_head, total_legs, animal_legs=[2, 4]): """ Find the number of kangaroo and tiger in a zoo. For example: zoo(6, 16) -> (4, 2) zoo(8, 20, [4, 2, 2]) -> (2, 0, 6) Parameters ---------- total_head: int Total number of animals total_legs: int ...
def likelihood(sensor_valuesA, sensor_valuesB): """ 1. compare A and B A,and B must be same range list of integers. 2. return likelihood. if A is completely equaly as B, then likelihood is 1.0(Max) if A is completely different as B, likelihood is 0.0(Min) In almost cases, likeli...
def natural_list_parse(s, symbol_only=False): """Parses a 'natural language' list, e.g.. seperated by commas, semi-colons, 'and', 'or', etc...""" tokens = [s] seperators = [',', ';', '&', '+'] if not symbol_only: seperators += [' and ', ' or ', ' and/or ', ' vs. '] for sep in seperators:...
def get_name_from_seq_filename(seq_filename): """Get sequence name from the name of an individual sequence fasta filename. Args: seq_filename: string. Of the form 'sequence_name'.fasta, like OLF1_CHICK/41-290.fasta. Returns: string. Sequence name. """ return seq_filename.split('.')[0]
def translate_format_item_value(a: str): """ Preprocess: we replace all marks like %1$s to regex capture group (\S+) param a: The string to be processed. :return: The processed string. """ i = 1 pattern = '%{i}$s' desired = r'(\[.+\]|\S+)' while pattern.format(i=i) in a: a = ...
def build_creative_name(order_name, creative_num): """ Returns a name for a creative. Args: order_name (int): the name of the order in DFP creative_num (int): the num_creatives distinguising this creative from any duplicates Returns: a string """ return 'HB {order_name...
def count_bulls_cows(user_string, comp_string): """ Function compare two strings and count bulls and cows :param user_string: string which has the same length as comp_string :param comp_string: string which has the same length as user_string :return: tuple with number of cows and bulls """ ...
def get_grid(rows, columns): """Get grid with number of rows and columns.""" return [[0 for _ in range(columns)] for _ in range(rows)]
def lucas_mod(n, mod): """ Compute n-th element of Fibonacci sequence modulo mod. """ P, Q = 1, -1 x, y = 0, 1 # U_n, U_{n+1}, n=0 for b in bin(n)[2:]: x, y = ((y - P * x) * x + x * y) % mod, (-Q * x * x + y * y) % mod # double if b == "1": x, y = y, (-Q * x + P * y...
def div_growth_rate(t, dt, d0): """ Calculates the growth rate of a dividend using the dividend growth rate valuation model. parameters: ----------- t = time dt = current price of dividend d0 = price of dividend t years ago """ growth_rate = (((dt/d0) ** (1/t)) - 1) * 100 return round(growth_rate, 4)
def bytecount(numbytes): #---------------------------------------------------<<< """Convert byte count to display string as bytes, KB, MB or GB. 1st parameter = # bytes (may be negative) Returns a short string version, such as '17 bytes' or '47.6 GB' """ retval = '-' if numbytes < 0 else '' # leadi...
def get_raw_times(times, starttime, endtime): """ Return list of times covering only the relevant time range. times - all times in input file starttime, endtime - relevant time range """ i_min, i_max = 0, len(times) - 1 for (i, time) in enumerate(times): if time < starttime: ...
def json_str_list_to_int_list(json_list,json_number_base=16): """ returns a json list to a list of ints with base 'json_number_base' [default 16] """ return [int(k,json_number_base) for k in json_list]
def sturm_liouville_function(x, y, p, p_x, q, f, alpha=0, nonlinear_exp=2): """Second order Sturm-Liouville Function defining y'' for Lu=f. This form is used because it is expected for Scipy's solve_ivp method. Keyword arguments: x -- independent variable y -- dependent variable p -- p(x) para...
def convert_keys_to_string(dictionary): """Recursively converts dictionary keys to strings.""" if not isinstance(dictionary, dict): return dictionary return dict((str(k), convert_keys_to_string(v)) for k, v in dictionary.items())
def get_natoms_element(formula): """ Converts 'Be24W2' to {'Be': 24, 'W' : 2}, also BeW to {'Be' : 1, 'W' : 1} """ import re elem_count_dict = {} elements = re.findall('[A-Z][^A-Z]*', formula) #re.split('(\D+)', formula) for i, elm in enumerate(elements): elem_count = re.findal...
def update_position(dir, x, y): """Returns the updated coordinates depending on the direction of the path""" if dir == 'DOWN': return x, y + 1 elif dir == 'UP': return x, y - 1 elif dir == 'LEFT': return x - 1, y elif dir == 'RIGHT': return x + 1, y
def deriveRefinedCollisionData(model): """This function collects all collision bitmasks in a given model. Args: model(dict): The robot model to search in. Returns: : dict -- a dictionary containing all bitmasks with corresponding element name (key). """ collisiondata = {} for link...
def primes_sieve3(n): """ Sieve method 3: Returns a list of primes < n >>> primes_sieve3(100) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] """ # begin half-sieve, n>>1 == n//2 sieve = [True] * (n>>1) upper = int(n**0.5)+1 fo...
def _policy_dict_at_state(callable_policy, state): """Turns a policy function into a dictionary at a specific state. Args: callable_policy: A function from `state` -> lis of (action, prob), state: the specific state to extract the policy from. Returns: A dictionary of action -> prob at this st...
def is_valid_vpsaos_account_id(account_id): """ :param account_id: Account ID to check validity :return: True iff VPSAOS account is valid """ valid_set = set('0123456789abcdef') return all(c in valid_set for c in account_id)
def xstr(s): """ Converts None types to an empty string, else the same string """ if s is None: return '' return str(s)
def EvaluateOnePotential(position,potential): """Defines a function that evaluate the potential at a certain point x. This function will be vectorized with np.vectorize to evaluate the potential on a list of position [x1,x2,...] Parameters: ----------- position (float) : a float that defines the x ...
def char_fun(A, b): """ Returns True if dictionary b is a subset of dictionary A and False otherwise. """ result = b.items() <= A.items() return result
def _ensure_is_list(obj): """ Return an object in a list if not already wrapped. Useful when you want to treat an object as a collection,even when the user passes a string """ if obj: if not isinstance(obj, list): return [obj] else: return obj else: ...
def abs(i): """ https://docs.mongodb.com/manual/reference/operator/aggregation/abs """ return f"{{'$abs' :{i}}}"
def _total(data): """Sum all downloads per category, regardless of date""" # Only for lists of dicts, not a single dict if isinstance(data, dict): return data totalled = {} for row in data: try: totalled[row["category"]] += row["downloads"] except KeyError: ...
def epochJulian2JD(Jepoch): """ ---------------------------------------------------------------------- Purpose: Convert a Julian epoch to a Julian date Input: Julian epoch (nnnn.nn) Returns: Julian date Reference: See JD2epochJulian Notes: e.g. 1983.99863107 converts into 2445700.5 Inverse of ...
def reverse_dictionary(d): """ Reverses the key value pairs for a given dictionary. Parameters ---------- d : :obj:`dict` dictionary to reverse Returns ------- :obj:`dict` dictionary with keys and values swapped """ rev_d = {} [rev_d.update({v:k}) for k, v in d....
def removeStopwords(terms,stopwords): """ This function removes from terms all occurrences of words in the list stopwords. """ """ This will be provided for the student. """ output = [] for x in terms: if x not in stopwords: output.append(x) return output