content
stringlengths
42
6.51k
def is_parentheses_matched(open_paren, close_paren): """ checking if open_paren and close_paren are matching """ if open_paren == '(' and close_paren == ')': return True if open_paren == '{' and close_paren == '}': return True if open_paren == '[' and close_paren == ']': return T...
def quicksort_lc(nums): """Quick sort algorithm by recursion with list comprehension. Procedure: - Pick a pivot which ideally is a median pf the list. - Arrange half elements which are smaller than pivot to left, and the other half ones that are bigger than pivot to right. - Then to e...
def apply_case_mask(word, mask): """Applies a case mask to a word.""" while len(mask) < len(word): mask.append(False) chars = [] for i, char in enumerate(word): chars.append(char.upper() if mask[i] else char) return "".join(chars)
def circular_permuted(x): """Generates all possible circular permutations of the input. Args: x (str or any iterable?) Returns: list: All circular permutations of x """ return([x[i:] + x[:i] for i in range(len(x))])
def set_auth_credentials(auth_id=None, auth_token=None): """sets the auth_id and auth_token globally""" if auth_id is not None and auth_token is not None: global AUTH_ID global AUTH_TOKEN AUTH_ID = auth_id AUTH_TOKEN = auth_token return 0 print("Function takes two arg...
def activate_text(shell: dict, env_vars: dict, cat=False) -> str: """Returns the formatted text to write to the activation script based on the passed dictionaries.""" lines = [shell["shebang"]] for k, v in env_vars.items(): lines.append(shell["activate"].format(k, v)) if shell["activate_ex...
def format_gaming_string(infos): """ Construct a string from a dict containing the "user gaming" informations. (for now, only use address and name) :param dict infos: The informations :returns: The formatted string :rtype: :py:class:`str` """ name = infos.get('name') if not name...
def get_video_embed(video_url): """Returns proper embed code for a video url""" if 'youtu.be' in video_url or 'youtube.com' in video_url: # https://youtu.be/i0IDbHGir-8 or https://www.youtube.com/watch?v=i0IDbHGir-8 base_url = "https://youtube.com/embed" unique_url = video_url[video_ur...
def selection_sort(arr): """Sort the given array using selection sort. All cases is O(n^2). Arguments: arr: The array to sort. Returns: The same array, arr, but sorted in increasing order. """ # The array is separated into the sorted # section, with indices less th...
def tsFrequency(ts_kind, leaf): """Return the frequency (if any) of the time series. Only time series created via ``scikits.timeseries`` module have this attribute. """ ts_freq = None if ts_kind == 'scikits_ts': # The frequency of the time serie. Default is 6000 (daily) ...
def check_sequence(predecessor_list, sequence): """ Checks if predecessors are in the sequence""" check = False if predecessor_list == set(): check = None return check pred_set = set() seq_set = set() for pred in predecessor_list: pred_set.add(pred.name) for elem in ...
def cubeit(x,a,b): """ construct cubic polynomial of the form y = ax^3 + b Parameters ---------- x: vector or float x values a: float coefficient to multiply b: float coefficient to add """ return a*x**3 + b
def count_alignments(game, color, target_number): """Count the number of alignments of target_number discs for a color.""" alignments = 0 # Horizontal alignments for x, _ in enumerate(game): for y in range(len(game[x]) - target_number + 1): if game[x][y : y + target_number] == [col...
def check_value(val, reference): """Return whether value matches reference Args: val (scalar) reference (scalar|list|tuple) scalar check if val == reference list check if check_value(val, ref) for ref in reference tuple check if reference[0]...
def get_link_prop_keys(props): """ This function can be used to pull out the primary keys from a dictionary, and return success iff all primary keys are present. :param props: the dict :return: all primary keys, and success if they were all present. """ src_sw = props.get('src_switch','') ...
def bytes_to_short(higher_byte, lower_byte): """ Transforms two bytes into a short (Using Big-Endian!) :param higher_byte: The byte at position 0 (Higher byte) :param lower_byte: The byte at position 1 (Lower byte) :return: The two bytes transformed into a short """ return (higher_byte << 8...
def is_digit(s): """ """ return s.lstrip('+-').isdigit()
def difference(resources, other_resources, key): """Compare using key and return entries from resources which are not present in other_resources""" other_resources_keys = [ getattr(other_resource, key, None) for other_resource in other_resources ] return [ resource for resource i...
def z(j, k): """Calculates equivalence scale. z(2,1) is the equivalence scale for a household with two adults and one child Parameters ---------- j : float the number of adults in the household. k : float the number of children (under 18 years old). Returns ------- type...
def envelope_error(value_lists): """Calculate the envelope of a list of datasets. The returned "errors" are relative to the first dataset.""" negative_errs = [] positive_errs = [] transposed_value_lists = zip(*value_lists) for values in transposed_value_lists: negative_errs.append(values...
def d_x_diffr_dx(x, y): """ derivative of d(x/r)/dx :param x: :param y: :return: """ return y**2 / (x**2 + y**2)**(3/2.)
def _remove_items(items, text): """Remove each item from the text.""" for item in items: text = text.replace(item, ' ') return text
def _expanded_shape(ndim, axis_size, axis): """ Returns a shape with size = 1 for all dimensions except at axis. """ return tuple([axis_size if i == axis else 1 for i in range(ndim)])
def file_ext(filename): """return the file extension, including the ``.`` >>> file_ext('foo.tar.gz') '.tar.gz' >>> file_ext('.emacs') '' >>> file_ext('.mrjob.conf') '.conf' """ stripped_name = filename.lstrip('.') dot_index = stripped_name.find('.') if dot_index == -1: ...
def construct_index_dict(field_names, index_start=0): """This function will construct a dictionary used to retrieve indexes for cursors. :param - field_names - list of strings (field names) to load as keys into a dictionary :param - index_start - an int indicating the beginning index to start from (default ...
def _process_plotsummary(x): """Process a plot (contributed by Rdian06).""" xauthor = x.get('author') xplot = x.get('plot', '').strip() if xauthor: xplot += '::%s' % xauthor return xplot
def how_many_bytes(bits: int) -> int: """ how_many_bytes calculates how many bytes are needed to to hold the given number of bits E.g. => how_many_bytes(bits=0) == 0 => how_many_bytes(bits=8) == 1 => how_many_bytes(bits=9) == 2 Args: bits (int): The number of bits Returns: ...
def caesar_ascii_shuffle(shift): """Creates an array of the resulting ascii after the caesar shuffle. Args: shift (int): The number of places to shift the ascii. Returns: list: A list of the resulting ascii after caesar shuffled. """ _ascii = ["a", "b", "c", "d", "e", "f", "g", ...
def options_dict_to_list(opt_dict: dict): """ Converts a dictionary of named options for CLI program to a list. Example: { "option_name": "value" } -> [ "--option_name", "value" ] """ opts = [] for key, val in opt_dict.items(): opts.append('--' + key) if not(type(val) is list an...
def csv2list (s) : """ Takes a string of comma-separated values and returns a list of str's, int's, or float's. """ l = s.split(',') # SPLIT CONTENTS OF STRING try : if '.' in s : # PROBABLY CONTAINS float for i in range(len(l)) : l[i] = float(l[i]) else : # PROBABLY CONTAINS int for i in range(l...
def merge_dict_sum_numbers(dict1, dict2): """ Assumes two dictionaries with schema key:numeric value and merges them into a single dictionary whereby the numeric values are summed per key.""" result = {} if dict1 is None: dict1 = {} if dict2 is None: dict2 = {} for key in dict1: ...
def decimal_fmt(num, suffix='sec'): """A decimal pretty-printer.""" if num == 0.0: return '0 %s' % suffix if num < 1.0: for unit in ['', 'm', 'u', 'n', 'p', 'f', 'a', 'z']: if abs(num) >= 1.0: return '%.3g %s%s' % (num, unit, suffix) num *= 1000.0 return '%.3g %s%s' % (num, 'y', su...
def get_size(vol_size): """ convert size from megabyte to kilobytes """ tmp = int(vol_size) * 1024 * 1024 return tmp
def translate_time(x): """ translate time from hours to hours and minutes Parameters ---------- x : float Something like 6.75 Returns ------- y : str Something like '6:45' """ y = str(int(x)).zfill(2) + ":" + str(int((x*60) % 60)).zfill(2) return y
def is_return(param_name): # type: (str) -> bool """ Determine if a parameter is named as a (internal) return. :param param_name: String with a parameter name :returns: True if the name has the form of an internal return name """ return param_name.startswith('$return')
def _name_value(obj): """ Convert (key, value) pairs to HAR format. """ return [{"name": k, "value": v} for k, v in obj.items()]
def exclude_variants(pages): """Checks if page is not a variant :param pages: List of pages to check :type pages: list :return: List of pages that aren't variants :rtype: list """ return [page for page in pages if (hasattr(page, 'personalisation_metadata') is False) ...
def notseq(x): """ Returns C{True} if I{x} is not a sequence. """ return not hasattr(x, '__iter__')
def split_len(seq, length): """ Returns a list containing the elements of seq, split into length-long chunks. """ return [seq[i:i + length] for i in range(0, len(seq), length)]
def comb(N, k): """ The number of combinations of N things taken k at a time. Parameters ---------- N : int, array Number of things. k : int, array Number of elements taken. """ if (k > N) or (N < 0) or (k < 0): return 0 val = 1 for j in range(min(k, N -...
def _to_bytes_or_false(val): """An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicode or py3 str: return val.decode('ascii') - Other...
def add_absent_parameters(parameters, template_parameters): """Adds all parameters that the template does need""" parameters_keys = [p['ParameterKey'] for p in parameters] for stack_parameter in template_parameters: if stack_parameter['ParameterKey'] not in parameters_keys: parameters.ap...
def new_mmse_group(mmse_t): """ If the MMSE T-score is at or below 1.5 standard deviations from the mean, the participant is considered impaired, otherwise they are intact. """ if mmse_t > 35: return "Intact" elif mmse_t <= 35: return "Impaired"
def get_environment(hostname): """Get whether dev or qa environment from Keeper server hostname hostname(str): The hostname component of the Keeper server URL Returns one of 'DEV', 'QA', or None """ environment = None if hostname: if hostname.startswith('dev.'): environment ...
def get_node(node_id, properties): """reformats a NetworkX node for `generate_data()`. :param node_id: the index of a NetworkX node :param properties: a dictionary of node attributes :rtype: a dictionary representing a Neo4j POST request """ return {"method": "POST", "to": "/node", ...
def is_dicom_file(full_path): """Attempt to guess if a file is a DICOM""" for ext in ['.pinfo', '.info', '.txt']: if full_path.endswith(ext): return False return True
def wallOpeningOrganiser(openings): """Divide the openings per wall.""" if openings: holes = [[], [], [], []] opns = [[], [], [], []] for i in range(0,4): opns[i].append([]) opns[i].append([]) door = openings[0] if door != '': doorwall ...
def make_song_title(artists: list, name: str, delim: str) -> str: """ Generates a song title by joining the song title and artist names. Artist names given in list format are split using the given delimiter. """ return f"{delim.join(artists)} - {name}"
def by_descending_count(pair): """ This function acts as a key for sort. It helps sort pairs of (key,count) into descending order of count >>> x = [("c",1),("a",2),("b",0)] >>> x.sort(key=by_descending_count) >>> x [('a', 2), ('c', 1), ('b', 0)] """ return -pair[1]
def validarArea(vL, vA, vB): """ Eliminar puntos grises y fondo param: vL: valor espectro L param: vA: valor espectro a param: vB: valor espectro b """ # validate grayscale and mark points if vL >= 0 and vL <= 100 and vA > -5 and vA < 5 and vB > -5 and vB < 5: return False el...
def clip(val): """Standard clamping of a value into a fixed range (in this case -4.0 to 4.0) Parameters ---------- val: float The value to be clamped. Returns ------- The clamped value, now fixed to be in the range -4.0 to 4.0. """ return max(min(val, 4.0), -4.0)
def round_int(value): """Cast the specified value to nearest integer.""" if isinstance(value, float): return int(round(value)) return int(value)
def validate_start(value): """Validate "start" parameter.""" if value not in ("watch", "exec"): raise ValueError('Must be "exec" or "watch"') return value
def mergeFreqProfiles(freqp1, freqp2): """Returns a frequency profile from two merged frequency profiles. The two frequency profiles must be dictionary types. Parameters: freqp1: dictionary, i.e. frequency profile freqp2: dictionary, i.e. frequency profile Th...
def combine_dicts(new_dict, old_dict): """ returns a dictionary with all key, value pairs from new_dict. also returns key, value pairs from old_dict, if that key does not exist in new_dict. if a key is present in both new_dict and old_dict, the new_dict value will take precedence. """ old_data_k...
def logical_right_shift(n: int , shifted_by: int)-> str: """ Take in 2 positive integers. 'n' is the integer to be logically right shifted 'shifted_by' times. i.e. (number >> shifted_by) Return the shifted binary representation. """ if n < 0 or shifted_by < 0: raise ValueError('The ...
def GenerateConfig(context): """Creates the SQL instance.""" resources = [{ 'name': 'csye6225-cloud-sql', 'type': 'sqladmin.v1beta4.instance', 'properties': { "state":"RUNNABLE", "backendType": "SECOND_GEN", "databaseVersion": "MYSQL_5_6", "region": "us-e...
def is_blank(value: str): """ Returns True if the specified string is whitespace or empty. :param value: the string to check :return: True if the specified string is whitespace or empty """ try: return "".__eq__(value.strip()) except AttributeError: return False
def magratio( mag1, mag2, mag1_err=None, mag2_err=None ): """Calculates luminosity ratio given two magnitudes; optionally computes the error on the ratio using standard error propagation (only if at least one of the errors is given; if only one is given, the other is assumed to be = 0).""" diff = mag1 - mag2 ...
def image_name(name): """Get the name of the file and returns a string with .jpg format""" # Gets the '.' position dot = name.find('.') # Slice the name from beginning and before '.' img = name[:dot] # return string with jpg format return "{}.jpg".format(img)
def flatten (alst): """A recursive flattening algorithm for handling arbitrarily nested iterators >>> flatten([0, [1,(2, 3), [4, [5, [6, 7]]]], 8]) [1, 2, 3, 4, 5, 6, 7, 8] """ def _recur (blst): for elem in blst: if hasattr(elem, "__iter__"): for i in _recur(ele...
def _contains_library_name(file, library_name): """ Checks if the file contains the specified line. :return: True if the file contains the specified line """ for line in file: line = line.strip() line = line.split() if len(line) == 3: if line[1] == library_name: ...
def transpose(matrix): """ transposes a 2-dimensional list """ return [[matrix[r][c] for r in range(len(matrix))] for c in range(len(matrix[0]))]
def extract_relevant_metrics(config: dict): """Extract the `measures` field from the config.""" metric_names = [] for k, v in config["measures"].items(): metric_names.extend(v) return metric_names
def Multi(val, **kwargs): """returns a directory for mutlivalued attributes""" return dict(_default=val, **kwargs)
def riKey(pre, ri): """ Returns bytes DB key from concatenation with '.' of qualified Base64 prefix bytes pre and int ri (rotation index) of key rotation. Inception has ri == 0 """ if hasattr(pre, "encode"): pre = pre.encode("utf-8") # convert str to bytes return (b'%s.%032x' % (pre...
def suspend(server_id, **kwargs): """Suspend server.""" url = '/servers/{server_id}/action'.format(server_id=server_id) req = {"suspend": None} return url, {"json": req}
def get_frigate_entity_unique_id( config_entry_id: str, type_name: str, name: str ) -> str: """Get the unique_id for a Frigate entity.""" return f"{config_entry_id}:{type_name}:{name}"
def _more_than_one_index(s, brackets=2): """ Search for two sets of [] [] @param s: string @param brackets: int """ start = 0 brackets_num = 0 while start != -1 and brackets_num < brackets: start = s.find('[', start) if start == -1: break start = s.fin...
def check(x): """ Checking for password format Format::: (min)-(max) (letter): password """ count = 0 dashIndex = x.find('-') colonIndex = x.find(':') minCount = int(x[:dashIndex]) - 1 maxCount = int(x[(dashIndex + 1):(colonIndex - 2)]) - 1 letter = x[colonIndex - 1] password = x...
def get_mean(items=[]): """ The mean or arithmitic average is operationally defined as the sum of scores divided by the number of scores. We use the mean when the greatest reliability is desired, when the distribution is normal, or not greatly skewed, and when there is a need for further statis...
def max_votes(x): """ Return the maximum occurrence of predicted class. Notes ----- If number of class 0 prediction is equal to number of class 1 predictions, NO_VOTE will be returned. E.g. Num_preds_0 = 25, Num_preds_1 = 25, Num_preds_NO_VOTE = 0, ...
def _escape(string): """Converts single backslashes to double backslashes. Note that we do not do a full re.escape because only backslashes are problematic. Args: string: String to escape. Returns: Updated string with escaped backslashes. """ return string.replace('\\', '\...
def colorize_output(output: str, color: str) -> str: """Color output for the terminal display as either red or green. Args: output: string to colorize color: choice of terminal color, "red" vs. "green" Returns: colorized string, or original string for bad color choice. """ ...
def num_decodings(s): """ :type s: str :rtype: int """ if not s or s[0] == "0": return 0 wo_last, wo_last_two = 1, 1 for i in range(1, len(s)): x = wo_last if s[i] != "0" else 0 y = wo_last_two if int(s[i-1:i+1]) < 27 and s[i-1] != "0" else 0 wo_last_two = wo_...
def Dic_Subset_End_Since(indic,end_num): """ subset a dictionary by retaining several last elements since index end_num. it works like [newdic[key] = olddic[key][end_num:] for key in old_dic.keys()] Note: 1. Test has been done for only the case that indic[key] is 1D ndarray. """ outdic={...
def rgbcolor(h, f): """Convert a color specified by h-value and f-value to an RGB three-tuple.""" v = 1.0 s = 1.0 p = 0.0 # q = 1 - f # t = f if h == 0: return v, f, p elif h == 1: return 1 - f, v, p elif h == 2: return p, v, f elif h == 3: ret...
def capitalize(text): """ Returns a capitalized string. Note that this differs from python's str.capitalize()/title() methods for cases like "fooBarBaz" """ if text == '': return '' return text[0].upper() + text[1:]
def _findSubStr(X, Y, m, n): """ Helper function to find the longest similar substring in two strings. """ LCSuff = [[0 for k in range(n + 1)] for l in range(m + 1)] result = 0 for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: LCSuff[i][j] = ...
def scrap_signature(consensus, fix=b'SIGNATURE'): """ Consume a signature field if there is one to consume. :param bytes consensus: input which may start with a signature. :returns: a tuple (updated-consensus, signature-or-None) """ if not consensus.startswith(b'-----BEGIN ' + fix ...
def remove_suffix(string, suffix): """Strip the given suffix from a string. Unlike the builtin string rstrip method the suffix is treated as a string, not a character set. Only an exact match triggers a removal, and the suffix is only removed once. Examples: remove_suffix('azaz', 'az') ->...
def model_snowdry(Sdry_t1 = 0.0, Snowaccu = 0.0, Mrf = 0.0, M = 0.0): """ - Name: SnowDry -Version: 1.0, -Time step: 1 - Description: * Title: water in solid state in the snow cover Calculation * Author: STICS * Reference: doi:h...
def human_size(nbytes): """ Convert size in bytes to a human readable representation. Args: nbytes (int): Size in bytes. Returns: Human friendly string representation of ``nbytes``, unit is power of 1024. >>> human_size(65425721) '62.39 MiB' ...
def list_order_by(l,firstItems): """given a list and a list of items to be first, return the list in the same order except that it begins with each of the first items.""" l=list(l) for item in firstItems[::-1]: #backwards if item in l: l.remove(item) l.insert(0,item) ...
def mod_pwr2(e, p): """Return 2**e (mod p) for integers e, p with p >= 1. Raise ZeroDivsionError if this is not possible. This is faster than mod_exp(2, e, p) for negative e. """ assert p >= 1 if e >= 0: return pow(2, e, p) elif p & 1: return pow((p + 1) >> 1, -e, p) e...
def flatten(x): """ Input: ([people],[hashtags]). Output: [(hashtag, (main_author_flag, {person})),...] """ all_combinations = [] people = x[0] hashtags = x[1] for person in people: for hashtag in hashtags: main_author_flag = 0 if "@" in person else 1 ...
def split_list(n): #called only by get_sub_list function """takes a list of indices as input,subtracts the next(2) from the previous one(1),and returns the(2nd) index of the pairs that have diference>1""" return [(x+1) for x,y in zip(n, n[1:]) if y-x != 1]
def hanoi(n: int, L=None): """hanoi. storage the move process """ if L is None: L = [] def move(n, a='A', b='B', c='C'): """move. move the pagoda """ if n == 1: # print(a + '->' + c) L.append(a + '->' + c) # return (L) ...
def _get_object_presentation(obj_dict): """Returns one of object possible presentation: - display_name - title - name - slug if Nothing is presented in serrialized object than it will return `{tytle}_{id}` presentation. """ keys = ("display_name", "title", "name", "slug") for key in keys: if o...
def parse_n_features(n_features): """Utility: parses the number of features from a list of strings. Expects integers or the special value 'all'""" return [k if k == 'all' else int(k) for k in n_features]
def datetime_string_parser(value): """Ajusta string no formato %d/%m/%Y""" formated_date = value.split("-") return f"{formated_date[2]}/{formated_date[1]}/{formated_date[0]}"
def string_begins_with(string: str, substr: str) -> bool: """Determines whether string starts with substring or not >>> string_begins_with("hello", "he") True >>> string_begins_with("hello", "wo") False """ return string.startswith(substr)
def get_url(project, user, base='https://github.com'): """Gets the repo download url. Args: user (str): The username. base (str): The hosting site (default: 'https://github.com'). Returns: str: The url Examples: >>> get_url('pkutils', 'reubano') == ( ... 'h...
def get_item_name_and_spec(nodeid): """Split item nodeid into function name and - if existing - callspec res. parameterization.""" tokens = nodeid.split("[", 1) return tokens[0].strip(), "[" + tokens[1].strip() if len(tokens) > 1 else None
def max_amplitude(pathways): """Return the maximum of pathway prefactors Parameters ---------- pathways : list List of Liouville pathways Returns ------- pmax : float Maximum prefactor of the pathways rec : int positi...
def _strtobool(val: str) -> bool: """Convert a string representation of truth to true (1) or false (0). True values are "y", "yes", "t", "true", "on", and "1"; false values are "n", "no", "f", "false", "off", and "0". Raises ValueError if "val" is anything else. """ # Copied and updated from d...
def byte_to_string(byte): """ Converts an array of integer containing bytes into the equivalent string version :param byte: The array to process :return: The calculated string """ hex_string = "".join("%02x" % b for b in byte) return hex_string
def zip_append(items, tails): """Appends elements from iterator to the items in a zipped sequence.""" return [(*zpd, app) for (zpd, app) in zip(items, tails)]
def count_bulls_and_cows(number, guessed_number) -> tuple: """ :param number: the number to guess :param guessed_number: the guessed number :return: tuple containing the count of bulls and cows """ bulls = 0 cows = 0 for x in range(len(number)): if guessed_number[x] == number[x]...
def calculate_triangle_area(base, height): """ Computes the area of a triangle, given its base and height. Params: base (int or float) like 8 height (int or float) like 6 Examples: calculate_triangle_area(8, 6) calculate_triangle_area(base=8, height=6) calculate...