content
stringlengths
42
6.51k
def str_append(string, add): """Append add in end string. Example: str_append('hou', 'se'); Return='house'""" return string + str(add) + "\n"
def getSize(amt): """ This function takes a file size (in bytes) and converts the output into readable format. Supports file sizes in: 'bytes', 'kb', and 'mb'. """ fmt = lambda x: "{:,}".format(x) fstr = lambda x, y: float("%.1f" % (x / float(y))) kb = 1024 mb = (1024 * 1024) if amt >= mb: ...
def update_dict_from_params_using_path(keys_to_update: dict, params: dict, data: dict) -> dict: """Update a dictionary using a path given in a list [nest1, nest2] and update it. For example: some_dict[nest1][nest2] = some_value Args: keys_to_update (dict): The keys names with the path to update...
def check_position_detection(bounds): """Check whether the specified range of 5 intervals has the right proportions to correspond to a slice through a position detection pattern. An ideal slice through a position detection pattern consists of 5 intervals colored B,W,B,W,B with lengths proportional to 1...
def monkey_count(n): """Return count from 1 to n.""" return [i for i in range(1, n + 1)]
def is_int(num): """ is_int Confirms if an input is numeric. """ try: x = int(num) return True except: return False
def connect_arrays(first, second, place_holder=-1): """ It connects two arrays in provided order into one. Before the arrays are joined they are extended to longest array length where missing values are substituted by place_holder argument. >>> connect_arrays([1, 2], [3, 4, 5], -1) [1, 2, -...
def mean(s): """Returns the arithmetic mean of a sequence of numbers s. >>> mean([-1, 3]) 1.0 >>> mean([0, -3, 2, -1]) -0.5 """ # BEGIN Question 1 assert len(s) > 0 return sum(s) / len(s) # END Question 1
def get_url(package, version=None): """ Return homepage, repo, bugtracker URLs for a package. @package - :user/:repo """ urls = { 'homepage' : 'https://github.com/%s' % package, 'repository' : 'git://github.com/%s.git' % package, 'bugtracker' : 'https:/...
def _uint_to_bits(value): """Converts an integer value to a list of bits.""" int_value = int(value) bits = [] while int_value > 0: bits.insert(0, int_value % 2) int_value //= 2 return bits
def ccw(i): """Get index (0, 1 or 2) increased with one (ccw)""" return (i + 1) % 3
def append_tag(image_tag, append_str): """ Appends image_tag with append_str :param image_tag: str, original image tag :param append_str: str, string to be appended """ return f"{image_tag}-{append_str}"
def dump_args_json( args_json ): """ Diagnostic dump of args_json dictionary. """ print('dump args json dictionary keys level 1') for dict_key in args_json.keys(): print( 'dict_key: %s' % (dict_key)) print('dump args json dictionary keys level 2 (runs)') for sample in args_json['sam...
def find_smallest(arr: list) -> int: """ Function get list and find index of the smallest element. :param arr: list to sort :return: index of the smallest element of the list """ smallest = arr[0] smallest_index = 0 for index in range(1, len(arr)): if arr[index] < smallest: ...
def IsInTargetRange( target, error_ref, warning_percentage, error_percentage, value): """Test if a value falls into warning or error range around a target. Args: target: The target value. error_ref: The error reference as the base for warning/error percentage. warning_percentage: The percentage of ...
def number_of_groups_vi(no_x_names): """Determine no of groups for groupwise variable importance measure. Parameters ---------- no_x_names :INT. No of variables considered in analysis. Returns ------- groups : INT. merged_groups : INT. """ if no_x_names >= 100: groups ...
def _build_namespaces_dict(new_prefixes, defaults): """ It merges the default list of namespaces with a :param new_prefixes: :param defaults: :return: """ for a_key in new_prefixes: defaults[a_key] = new_prefixes[a_key] return defaults
def filter_point(point: int) -> int: """Filter a point. If point is below threshold, divide it by divisor. If above, multiple it by multiplier. This is a crude but effective way of skewing an image to black-and-white without actually thresholding it. """ if point < 160: return round(po...
def regroup_ranges(rgs): """ Functions to reduce sets of ranges. Examples: [[80,80],[80,80]] -> [80,80] [[80,80],[0,65000]] -> [0,65000] Taken from https://stackoverflow.com/questions/47656430/given-a-list-of-tuples-representing-ranges-condense-the-ranges-write-a-functio """ def overl...
def make_gateway_name( gateway_type, volume_name, host ): """ Generate a name for a gateway """ return "%s-%s-%s" % (volume_name, gateway_type, host)
def create_alow_null(tmp_allow_null): """ Args: tmp_allow_null(list): Returns: """ if tmp_allow_null: return ',' + (',').join(tmp_allow_null) else: return ''
def process_ubls(ubls): """ Return list of tuples of unique-baseline pairs from command line argument. Input: comma-separated value of baseline pairs (formatted as "b1_b2") Output: list of tuples containing unique baselines """ # test that there are ubls to process if ubls == ...
def close(session_attributes, fulfillment_state, message): """ Defines a close slot type response. """ response = { "sessionAttributes": session_attributes, "dialogAction": { "type": "Close", "fulfillmentState": fulfillment_state, "message":...
def DuplicateStyleDict(style_dict): """Duplicates the style dictionary to make a true copy of it, as simply assigning the dictionary to two different variables only copies a reference leaving both variables pointing to the same object. @param style_dict: dictionary of tags->StyleItems @return: a...
def turn_list_to_str(list_values, sep = ";"): """ Transforms a list to a string. Arguments: - list_values: The original list of values (int or string). - sep : The field separator in the output string (string). Outputs: - output_str : The output string (string). """ out...
def get_dlls(comments): """ Returns a lowercase set of DLLs accessed by the file does not preserve order. Remove set command to preserve redundency""" dlls = [line for line in comments if '.dll' in line.lower()] return list(set(line.split()[-1].lower() for line in dlls))
def generate_pairs(lst): """Return all possible pars of a list.""" pairs = [] for i in range(len(lst)): for j in range(i): if i != j: pairs.append([i, j]) return pairs
def _write_el_block(elParams): """ Args: elParams (dict) Returns str """ ep = elParams ret = ["%6.2f %4d %2d" % (ep["Etrial"], ep["Ndiff"], ep["Napw"])] # sort by l exceptions = sorted(list(ep["exceptions"].items()), key=lambda x: x[0]) for l, els in exceptions: ...
def zero_prefix(num): """ Adds '0' as a prefix to numbers less than 10 """ if num < 10: return '0' + str(num) else: return str(num)
def human_time(seconds): """Returns a human-friendly representation of the number of seconds.""" assert seconds >= 0 hours = seconds / (60 * 60) minutes = (seconds / 60) % 60 seconds = seconds % 60 return '%02d:%02d:%02d' % (hours, minutes, seconds)
def summer_69(arr): """ Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers. :param arr: list of integers :return: int """ get_result = 0 ...
def score(value): """General wrapper around objective function evaluations to get the score. :param value: output of the objective function :returns: the score If value is a scalar, it is returned immediately. If value is iterable, its first element is returned. """ try: return value[0...
def probe_id(subscription_id, resource_group_name, load_balancer_name, name): """Generate the id for a probe""" return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/loadBalancers/{}/probes/{}'.format( subscription_id, resource_group_name, load_balancer_name, na...
def remover_sp_add_sub(list_parameters): """ Remove "sp" of the elements of the list """ return [list_parameters[1]]
def hexagonal_num(n: int) -> int: """ Returns nth hexagonal number >>> hexagonal_num(143) 40755 >>> hexagonal_num(21) 861 >>> hexagonal_num(10) 190 """ return n * (2 * n - 1)
def _adjust_ix(i, n): """Internal helper function""" if i >= n: return i+1 else: return i
def to_camel_case(snake_str): """ From https://stackoverflow.com/questions/19053707/converting-snake-case-to-lower-camel-case-lowercamelcase """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them toget...
def is_success_http_code(http_code: int) -> bool: """Checks if a http response code indicates success (a 2xx code).""" return http_code >= 200 and http_code < 300
def area_square(length): """Calculates the area of a square. Calculates the area of a square based on the lenth of side. Args: length (float) : length is the length of side of a square. Returns: float: area of a square. """ if length < 0: raise ValueError("The length o...
def _dict_merge(dominant, recessive): """ Combines the two dicts. In case of duplicate keys, the values of 'dominant' are used. """ for key, value in recessive.items(): dominant[key] = dominant.setdefault(key, value) return dominant
def ArraySum(array:list, n:int=0): """ Sum of all the elements in the List using Recursion """ if n == len(array): return 0 return array[n] + ArraySum(array,n+1)
def file_to_dataset(file): """Example function to derive datasets from file names""" if "ZJet" in file: return "Z" elif "WJet" in file: return "W" elif "HToInvisible" in file: return "Hinv"
def getplain(formula): """ Method to make a chemical formula more readable for embedding in filenames Examples: CH3COOHv=0 -> CH3COOH g-CH3CH2OH -> CH3CH2OH (CH3)2COv=0 -> (CH3)2CO cis-CH2OHCHOv= -> CH2OHCHO g'Ga-(CH2OH)2 -> (CH2OH)2 Paramete...
def has_digits(password): """Return True if password has at least one digit.""" return any(char.isdigit() for char in password)
def str_to_bool(val: str) -> bool: """ Converts a string to a Boolean. Args: val: (str) Expects "True" or "False" Returns: Boolean """ return True if val.lower() == "true" else False
def fib(x): """ Fibonacci """ # global numFibCalls # numFibCalls += 1 if x == 0 or x == 1: # NB: we need to base cases return 1 else: return fib(x-1) + fib(x-2)
def pad_lists(lists, pad_token=0): """ Pads lists with trailing zeros to make them all the same length. """ max_list_len = max(len(l) for l in lists) for i in range(len(lists)): lists[i] += [pad_token] * (max_list_len - len(lists[i])) return lists
def format_bytes(num_bytes): """ Formats a number into human-friendly byte units (KiB, MiB, etc) """ if num_bytes >= 1024*1024*1024*1024: return "%.2fTiB" % (num_bytes / (1024*1024*1024*1024)) if num_bytes >= 1024*1024*1024: return "%.2fGiB" % (num_bytes / (1024*1024*1024)) if num_bytes >= 1024*1024: return...
def maxes(itr, key=lambda x: x): """Returns a list of MAX values""" itr = list(itr) mval = max(map(key, itr)) return list(filter(lambda x: key(x) == mval, itr))
def remove_comments(string: str): """ :param string: Must be a string of lines :return: A string representing the lines without comments (c or $) """ return ' '.join([line.split('$')[0].strip() for line in string.splitlines() if line[0].lower() != 'c'])
def solution(power: int = 1000) -> int: """ Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ num = 2 ** power string_num = str(num) list_num = list(string_num) sum_of_...
def coords2polygon(coord_list): """Formats list of 2D coordinate points as string defining Polygon in PostgreSQL""" coords_ = [str(x) + " " + str(y) for x, y in coord_list] return "POLYGON(("+",".join(t for t in coords_)+"))"
def itemfilter(predicate, d, factory=dict): """ Filter items in dictionary by item >>> def isvalid(item): ... k, v = item ... return k % 2 == 0 and v < 4 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> itemfilter(isvalid, d) {2: 3} See Also: keyfilter valfilter it...
def directionToDof(direction): """ Converts direction to degree of freedom """ directioMap = { "X": 1, "Y": 2, "Z": 3 } return directioMap[direction]
def formula_double_format(afloat, ignore_ones=True, tol=1e-8): """ This function is used to make pretty formulas by formatting the amounts. Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4. Args: afloat (float): a float ignore_ones (bool): if true, floats of 1 are ignored. tol ...
def weight(size): """Construct a weight of some size.""" assert size > 0 return ['weight',size]
def sentence_position(i, size): """different sentence positions indicate different probability of being an important sentence""" normalized = i * 1.0 / size if 0 < normalized <= 0.1: return 0.17 elif 0.1 < normalized <= 0.2: return 0.23 elif 0.2 < normalized <= 0.3: retu...
def convertLists(lists): """permet si besoin de convertir une liste de liste de plusieurs dictionnaires (format boto3) en simple liste de un dictionnaire""" newList = [] for list in lists: newDict = dict() for elt in list: newDict[elt['Key']]=elt['Value'] ...
def sat_trip(cred, cgreen, cblue): """ saturate rgb color """ mult = 255.0 / (float(max(cred, cgreen, cblue))**4) return int(mult * float(cred) ** 4), \ int(mult * float(cgreen) ** 4), \ int(mult * float(cblue) ** 4)
def smart_mean_per_call( maximum, minimum, per_minute, charge_interval, connection=0): """Returns the mean charge for a call. Args: maximum (seconds): maximum length of call to average (the minimum is 1) minimum (seconds): calls are effectively at least this long per_minute: cha...
def map_structure(op, *param_dicts): """ For a series of identically structured dicts, apply op to every same set of entries and return a single dict of the same shape """ ret = {} for k in param_dicts[0].keys(): ret[k] = op(*[param_dicts[i][k] for i in range(len(param_dicts))]) return ret
def list_hartree_kcal(list_): """ Convert the elements in the list from hartree units to kiloCalories units. Parameters ---------- list_ : list List with elements in units of hartree. Returns ------- converted_list : list List with elements in units of kcal. Ex...
def compute_determinant(p1, p2, p3): """ :param p1: :param p2: :param p3: :return: """ det = float(p1[0]) * float(p2[1]) + float(p2[0]) * float(p3[1]) + float(p3[0]) * float(p1[1]) det -= float(p1[0]) * float(p3[1]) + float(p2[0]) * float(p1[1]) + float(p3[0]) * float(p2[1]) return ...
def get_x_geocoord(coord, east, west, width): """Transform abscissa from pixel to geographical coordinate Parameters ---------- coord : list Coordinates to transform east : float East coordinates of the image west : float West coordinates of the image width : int ...
def score(word, f): """ word, a string of length > 1 of alphabetical characters (upper and lowercase) f, a function that takes in two int arguments and returns an int Returns the score of word as defined by the method: 1) Score for each letter is its location in the alphabet...
def _merge(*dicts): """ Merge dictionaries together. Last one have the biggest priority. Order should be: default_data, module_data, cls_data, function_data. """ data = {} for item in dicts: if item: data.update(item) return data
def safe_get(obj, *keys): """Utility function to safely perform multiple get's on a dict. Particularly useful on complex/deep objects. Args: obj (dict): object to perform get on. *keys (string): consecutive keys as args. Returns: object: object if found or None. """ ...
def traceback_formatter(backtrace): """ Accept a backtrace in the format of traceback.extract_tb or traceback.extract_stack and returns a list of dictionary matching this format:: { 'file': FILENAME, 'line_number': LINE_NUMBER, 'method': FUNCTION_NAME } """ frames = ...
def validate_tail(in_tail): """ Validate the --tail input """ if isinstance(in_tail, int): return in_tail else: if in_tail == "all": return in_tail else: try: out_tail = int(in_tail) if out_tail > 0: ...
def lens2memnamegen_second50(nmems): """Generate the member names for members 50-100 of LENS2 Input: nmems = number of members Output: memstr(nmems) = an array containing nmems strings corresponding to the member names """ memstr=[] for imem in range(0,nmems,1): if (imem <...
def change_width_of_rdd_row(new_widths, old_widths, which_element, row): """ Zero pads the fixed width of each geolevel in a DAS_GEOID to ensure that the number of additional digits required to represent each of the geolevels are given by new_widths rather than old_widths. :param new_widths: the geoleve...
def hello_get(name: str): """ Example of passing parameters via GET. """ return {"message": f"Hello {name}!"}
def isin(a, b): """ Returns True if a in b. """ for bi in b: if (bi == a): return True return False
def format_subject(subject: str, _type="outlook") -> str: """Properly format subject Args: subject: _type: Returns: """ import re # Highlight keywords subject = re.sub(r"(@\w+\([^\]]+\))", "<b>\\1</b>", subject) return subject
def fixyears(yearstr): """ Summary Parameters ---------- yearstr : TYPE DESCRIPTION. Returns ------- TYPE DESCRIPTION. """ if len(yearstr) == 4: return yearstr else: if int(yearstr) < 70: return '19' + yearstr else: ...
def width_from_max_int(value): # pragma: no cover """Convert the value specified to a bit_width.""" for i in range(0, 64): if value == 0: return i value >>= 1
def full_pipe_address(addr): """Return the full address of the pipe `addr`""" if not isinstance(addr, bytes): addr = addr.encode("ascii") if addr.startswith(b"\\\\"): return addr return br"\\.\pipe" + "\\".encode() + addr
def clean_tag(tag): """clean up tag.""" if tag is None: return None t = tag if t.startswith('#'): t = t[1:] t = t.strip() t = t.upper() t = t.replace('O', '0') t = t.replace('B', '8') return t
def platform_name(project, platform): """"Get the untrusted platform name.""" return project.upper() + '_' + platform.upper()
def section_decision(indexer, sentence, offset_list, end_matches): """Decides what section mask token is in Returns a specific section of the sentence given which error is being worked on by splitting the text at the offset given in the offset_list. """ if indexer == 0: # First section: ...
def cover_multiple(current_length, multiple): """ https://stackoverflow.com/questions/41214432/how-do-i-split-a-2d-array-into-smaller-2d-arrays-of-variable-size """ return ((current_length - 1) // multiple + 1) * multiple
def is_abstract_method(method): """ @type: method: object @param: A method object. """ return getattr(method, '__isabstractmethod__', False)
def snap_value(input, snap_value): """ Returns snap value given an input and a base snap value :param input: float :param snap_value: float :return: float """ return round((float(input) / snap_value)) * snap_value
def pretty_tree(x, kids, show): """(a, (a -> list(a)), (a -> str)) -> str Returns a pseudographic tree representation of x similar to the tree command in Unix. """ (MID, END, CONT, LAST, ROOT) = ('|-- ', '`-- ', '| ', ' ', '') def rec(x, indent, sym): line = indent + sym + show(x)...
def prettyprint(s, toUpper=False): """Given a string, replaces underscores with spaces and uppercases the first letter of each word ONLY if the string is composed of lowercased letters. If the param, toUpper is given then s.upper is returned. Examples: "data_quality" -> "Data Quality" "copy_number...
def iam_policy_to_dict(bindings): """ iam_policy_to_dict takes an iam policy binding in the GCP API format and converts it into a python dict so that it can be easily updated """ bindings_dict = dict() for binding in bindings: role = binding['role'] bindings_dict[role] = set(binding['members']) re...
def to_camel_case(value): """ Convert the given string to camel case :param value: string :return: string """ content = value.split('_') return content[0] + ''.join(word.title() for word in content[1:] if not word.isspace())
def import_module_from_name(modname): """ Args: modname (str): module name Returns: module: module CommandLine: python -m xdoctest.utils import_module_from_name Example: >>> # test with modules that wont be imported in normal circumstances >>> # todo write...
def get_abs_axle_location(axle_spacing, start_pt, direction): """Calculates the absolute location of the axles wrt the start point.""" abs_axle_location = [] loc = start_pt #initialize for spacing in axle_spacing: if direction == "ltr": loc = loc - spacing elif direction ==...
def reverse_sentence(s: str) -> str: """ Parameters ----------- Returns --------- out: Reversed words in s. Notes ------ """ reverse = "".join(reversed(s)) res = [] splits = reverse.split() if not splits: return reverse for w in splits: w ...
def run_maaslin(read_config_file, maaslin_outfile, pcl_file): """Run the maaslin software. You probably don't want to use this workflow on its own; the `maaslin` workflow encapsulates this workflow and works on any OTU table. :param read_config_file: String; file generated based on pcl and metadata ...
def tweet_text(tweet): """Return a string, the words in the text of a tweet.""" "*** YOUR CODE HERE ***" return tweet['text']
def _handle_special_yaml_cases(v): """Handle values that pass integer, boolean, list or dictionary values. """ if "::" in v: out = {} for part in v.split("::"): k_part, v_part = part.split(":") out[k_part] = v_part.split(";") v = out elif ";" in v: ...
def bitmap_to_repr(bitmap, black='[]', white=' ', eol='\n'): """ Returns a string representation of a QR Code bitmap. """ string = '' for col in bitmap: for val in col: if val: string += black else: string += white string += eo...
def find_missing_letter(chars): """ chars: string of characters return: missing letter between chars or after """ letters = [char for char in chars][0] chars = [char.lower() for char in chars] alphabet = [char for char in "abcdefghijklmnopqrstuvwxyz"] starting_index = alphabet.index(chars[0]) for lett...
def format_pkt(data): """Put data packets in a human readable format""" return ', '.join([f'{bite:#04x}' for bite in data])
def isbn10_checksum (isbn_str): """ Return the checksum over the coding (first 9 digits) of an ISBN-10. :Parameters: isbn_str : string An ISBN-10 without the trailing checksum digit. :Returns: The checksum character, ``0`` to ``9`` and ``X``. For example: >>> isbn10_checksum ("094001673") '7'...
def flush(hand): """Return True if there is a flush""" suits = [s for r,s in hand] return len(set(suits)) == 1
def _compress_list(l): """Removes consecutive duplicate elements from |l|. >>> _compress_list([]) [] >>> _compress_list([1, 1]) [1] >>> _compress_list([1, 2, 1]) [1, 2, 1] """ result = [] for e in l: if result and result[-1] == e: continue result.append(e) return result
def try_int(x): """Safely convert anything that can be converted to int""" try: return int(x) except ValueError: return x