content
stringlengths
42
6.51k
def temp_to_str(temp): """ converts temperature from format 0.1 to format 0.100 by adding three places after decimal """ temp=str(temp) while len(temp)<5: temp='{}0'.format(temp) return temp
def central_differences(f, h, x): """ Forward Finite Differences. Approximating the derivative using the Central Finite Method. Parameters: f : function to be used h : Step size to be used x : Given point Returns: Approximation """ return (f(x + h) - f(x - h)) / (2 ...
def end_iter(foo): """Iterate to the end of foo.""" try: next(foo) return False except StopIteration: return True
def device_loc_to_type(loc): """Get the fixed, hardcoded device type for a device location.""" if loc in [461, 501]: return "ETC" elif loc in [541, 542]: return "GIF" elif loc in [11, 75, 150, 239, 321, 439, 482, 496, 517, 534]: return "FIF" elif loc in [ 38, ...
def make_row(unique_row_id, row_values_dict): """row_values_dict is a dictionary of column name and column value. """ return {'insertId': unique_row_id, 'json': row_values_dict}
def render_comment_list(comment_list, user, comment_list_css="main-thread"): """ Inclusion tag for rendering a comment list. Context:: Comment List Template:: comment_list.html """ return dict(comment_list=comment_list, comment_list_css=comment_list_css, user=user)
def format_param_dict_for_logger(params_dict): """ """ maxchars = max([len(key) for key in params_dict.keys()]) return "\n".join([f"{key.rjust(maxchars)} : {val}" for key, val in params_dict.items()])
def outline_style(keyword): """``outline-style`` properties validation.""" return keyword in ('none', 'dotted', 'dashed', 'double', 'inset', 'outset', 'groove', 'ridge', 'solid')
def pe31(target=200): """ >>> pe31() 73682 """ coins = [1, 2, 5, 10, 20, 50, 100, 200] ways = [1] + [0] * target for coin in coins: for i in range(coin, target + 1): ways[i] += ways[i - coin] return ways[target]
def prep_keyword(keyword): """ prepares keywords used for search. :param keyword: raw text. :return: formatted text. """ operator = '%' _term = '%(op)s%(kw)s%(op)s' term = _term % dict(op=operator, kw=keyword) return term
def stripnl(s): """Remove newlines from a string (and remove extra whitespace)""" s = str(s).replace("\n", " ") return ' '.join(s.split())
def get_message(name, value): """Provides the message for a standard Python exception""" if hasattr(value, "msg"): return f"{name}: {value.msg}\n" return f"{name}: {value}\n"
def reconcile_positions(pos_dict_1, pos_dict_2): """ Reconciles two position dictionaries into a new dictionary. I had run through a number of implementations of this function before settling on this one. See the repository history for further details. Parameters: pos_di...
def cover_points(points): """ Find the minimum number of steps to cover a sequence of points in the order they need to be covered. The points are in an infinite 2D grid and one can move in any of the 8 directions. points = [(0,0, (2,2), (0,5)] 0 1 2 0 * 1 \ ...
def repr_as_obj(d: dict) -> str: """Returns pretty representation of dict. >>> repr_as_obj({'a': 1, 'b': 2}) 'a=1, b=2' """ return ', '.join(f'{key}={value!r}' for key, value in d.items())
def esAnoBisiesto(ano): """Verifica si es un ano bisiesto""" if (ano % 4 == 0 and ano % 100 != 0) or ano % 400 == 0: return True return False
def getZoneLocFromGrid(gridCol, gridRow): """ Create a string location (eg 'A10') from zero based grid refs (col=0, row=11) """ locX = chr(ord('A') + gridCol) locY = str(gridRow + 1) return locX + locY
def _getObjectScope(objectid): """Intended for private use within wsadminlib only. Pick out the part of the config object ID between the '(' and the '|' -- we're going to use it in createObjectCache to identify the scope of the object""" return objectid.split("(")[1].split("|")[0]
def get_rate(value:str): """ v:values:'tensorflow_theano:325317.28125-tensorflow_cntk:325317.28125-tensorflow_mxnet:325317.28125-theano_cntk:0.07708668-theano_mxnet:0.09217975-cntk_mxnet:0.0887682' rate: max_Rl """ if 'inf' in value: return 'inf' else: try: value_spli...
def get_largest_logo(logos): """ Given a list of logos, this one finds the largest in terms of perimeter :param logos: List of logos :return: Largest logo or None """ if len(logos) >= 1: logo = max(logos, key=lambda x: int(x.get('height', 0)) + int(x.get('width', 0))).get('value') ...
def get_aic(lnL, Nf): """ Provides the Akaike Information Criterion (Akaike, 1973), i.e. AIC. Parameters ---------- lnL : float Minus the log-likelihood. Nf : int Number of free parameters. Returns ------- AIC : float AIC indicator. """ AIC = 2 * (...
def _get_package_status(package): """Get the status for a package.""" status = package['status_str'] or 'Unknown' stage = package['stage_str'] or 'Unknown' if stage == 'Fully Synchronised': return status return '%(status)s / %(stage)s' % { 'status': status, 'stage': stage ...
def range_overlap(a, b): """ >>> range_overlap(("1", 30, 45), ("1", 45, 55)) True >>> range_overlap(("1", 30, 45), ("1", 57, 68)) False >>> range_overlap(("1", 30, 45), ("2", 42, 55)) False """ a_chr, a_min, a_max = a b_chr, b_min, b_max = b # must be on the same chromosome ...
def overlay_file_name(p): """ generate overlay file name from ljpeg file name """ return '.'.join(p.split('.')[:-1]) + '.OVERLAY'
def caption_time_to_milliseconds(caption_time): """ Converts caption time with HH:MM:SS.MS format to milliseconds. Args: caption_time (str): string to convert Returns: int """ ms = caption_time.split('.')[1] h, m, s = caption_time.split('.')[0].split(':') return (int(h...
def tf_b(tf, _): """Boolean term frequency.""" return 1.0 if tf > 0.0 else 0.0
def log2(n): """ Smallest integer greater than or equal to log_2(n). """ i = 1 log = 0 while n > i: log += 1 i *= 2 return log
def remove_ansi(s : str) -> str: """ Remove ANSI escape characters from a string. """ import re return re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', s)
def html_mark_warning(text): """ Simple mark warning using html and css. """ return u"<div style='color:orange;'>%s</div>" % text
def rem(number=2304811, divisor=47): """ task 0.5.2 """ return number - ( (number // divisor) * divisor )
def get_version_number(data): """Gets the table version from the given section data Parses the given array of section data bytes and returns the version number of the section. """ vn = data[5] & int('00111110', 2) vn = vn >> 1 return vn
def solver_problem1(input_list): """walk through the binaries and calculate the most/least common bit""" common_bit = [0] * len(input_list[0]) for _, bin_list in enumerate(input_list): for j, bin_num in enumerate(bin_list): if bin_num == 1: common_bit[j] += 1 ...
def effective_area(subidx, subncol, cellsize, r_ratio=0.5): """Returns True if highress cell <subidx> is inside the effective area.""" R = cellsize * r_ratio offset = cellsize / 2.0 - 0.5 # lowres center ri = abs((subidx // subncol) % cellsize - offset) ci = abs((subidx % subncol) % cellsize - offs...
def linOriginRegression(points): """ computes a linear regression starting at zero """ j = sum([ i[0] for i in points ]) k = sum([ i[1] for i in points ]) if j != 0: return k/j, j, k return 1, j, k
def from_ymd(y, m=None, d=None): """take a year y, a month m or a d (all integers, or strings represeting integers) and return a stirng in the form "YYYY-MM-DD" """ if y and m and d: return '%s-%s-%s' % (str(y).zfill(4), str(m).zfill(2), str(d).zfill(2)) elif y and m: return '%s-%s' % (s...
def is_dict_of(d: dict, expected_type: type) -> bool: """Check whether it is a dict of some type.""" if not isinstance(expected_type, type): raise TypeError(f"`expected_type` must be a valid type. But got: {expected_type}.") return all(isinstance(v, expected_type) for k, v in d.items())
def first_line_of(step): """ Return the first line of a step """ return step.strip().splitlines()[0]
def n2s(counts): """convert a counts vector to corresponding samples""" samples = () for (value, count) in enumerate(counts): samples = samples + (value,)*count return samples
def get_transceiver_description(sfp_type, if_alias): """ :param sfp_type: SFP type of transceiver :param if_alias: Port alias name :return: Transceiver decsription """ if not if_alias: description = "{}".format(sfp_type) else: description = "{} for {}".format(sfp_type, if_ali...
def focus_index(average_pages_visited_in_section, total_pages_in_section): """Return the focus index for a section of a website. Args: average_pages_visited_in_section (float): Average number of pages visited in this section of the website. total_pages_in_section (int): Total number of pages in...
def escape_string(s: str) -> str: """escape special characters""" s = repr(s) if not s.startswith(('"', "'")): # u'hello\r\nworld' -> hello\\r\\nworld s = s[2:-1] else: # 'hello\r\nworld' -> hello\\r\\nworld s = s[1:-1] s = s.replace("\\'", "'") # repr() may escape "...
def get_pending_registration_ip_set( ip_from_dns_set, ip_from_target_group_set ): """ # Get a set of IPs that are pending for registration: # Pending registration IPs that meet all the following conditions: # 1. IPs that are currently in the DNS # 2. Those IPs must have not been registered y...
def delete_trailing_zeros(strValue): """ Remove all the trailing zeros""" newStr = strValue if '.' in strValue: lStr = strValue.split('.')[0] rStr = strValue.split('.')[1].rstrip('0') newStr = lStr + '.' + rStr if rStr == '': newStr = lStr return newStr
def character_arena_progress(pvp_data): """Accepts a JSON object containing pvp data and returns the players current arena/bg progression. """ brackets = pvp_data["pvp"]["brackets"] two_v_two = brackets["ARENA_BRACKET_2v2"]["rating"] two_v_two_skirmish = brackets["ARENA_BRACKET_2v2_SKIRMISH"]["rati...
def get_class_attr(obj, name, default=None): """Specifically get an attribute of an object's class.""" return getattr(obj.__class__, name, default)
def eppley_1979(pprod): """Export production from satellite derived properties Parameters ---------- pprod: array_like Primary Production (mg C m-3) Returns ------- eprod : ndarray or scalar Export production (mg C m-3) Ref --- """ eprod = 0.0025 * ppr...
def is_date_time(file_type, path): """ Return True if path is an object that needs to be converted to date/time string. """ date_time_objects = {} date_time_objects["Gzip"] = ("mod_time",) date_time_objects["PE"] = ("pe.coff_hdr.time_date_stamp",) date_time_objects["Windows shortcut"]...
def partition(alist, size): """ Returns a partition value of a list Always parts of size Ex.: ['1985', 1, '1990', 1] Returns: [['1985', 1], ['1990', 1]] """ return [alist[i : i + size] for i in range(0, len(alist), size)]
def converge(converging, branches, args): """Accepts a converging function and a list of branching functions and returns a new function. When invoked, this new function is applied to some arguments, each branching function is applied to those same arguments. The results of each branching function are pa...
def vars_in_env(type_env, keys=False): """Where `type_env` is a mapping to types, return all type varaibles found in the mapping. If `keys` is true, collect all keys.""" unsafe = set() for k in type_env: if keys: unsafe |= {k} unsafe |= type_env[k].bound_type_vars() retur...
def _rangelen(begin, end): """Returns length of the range specified by begin and end. As this is typically used to calculate the length of a buffer, it always returns a result >= 0. See functions like `_safeDoubleArray` and `safeLongArray`. """ # We allow arguments like begin=0, end=-1 on purp...
def is_empty(iterable): """ This filter checks whether the given iterable is empty. :param iterable: The requested iterable :type iterable: ~collections.abc.Iterable :return: Whether or not the given iterable is empty :rtype: bool """ return not bool(iterable)
def scalar_in_sequence(x, y): """Determine whether the scalar in the sequence.""" if x is None: raise ValueError("Judge scalar in tuple or list require scalar and sequence should be constant, " "but the scalar is not.") if y is None: raise ValueError("Judge scalar in...
def find_allowed_size(nx_size): """ Finds the next largest "allowed size" for the Fried Phase Screen method Parameters: nx_size (int): Requested size Returns: int: Next allowed size """ n = 0 while (2 ** n + 1) < nx_size: n += 1 nx_size = 2 ** n + 1 ...
def from_hex(hexstring) -> bytearray: # converts hex to bytearray """ converts hex to bytearray Converts the hex string received from databse to bytes for decryption :param hexstring: hex string recieved from database :type hexstring: hex :return: bytes from hex string :rtype: bytearra...
def parse_processing_parents(processings, parent_keys): """Return a dictionary relating each processing identifier to its parent. Parameters ---------- processings : dict A dictionary of processing data, whose keys are processing identifiers and values are dictionaries containing corres...
def pil_rect(rect_tup): """ x, y, w, h -> x, y, x, y """ x, y, w, h = [float(f) for f in rect_tup] return (x, y), (x + w, y + h)
def flip_case(phrase, to_swap): """Flip [to_swap] case each time it appears in phrase. >>> flip_case('Aaaahhh', 'a') 'aAAAhhh' >>> flip_case('Aaaahhh', 'A') 'aAAAhhh' >>> flip_case('Aaaahhh', 'h') 'AaaaHHH' """ to_swap = to_swap.lower() out = "" f...
def is_prime(n: int) -> bool: """Return True if *n* is a prime number """ n = abs(n) if n == 0: return False return all((n % i != 0 for i in range(2, int(n**.5)+1)))
def inv_map(dictionary: dict): """ creates a inverse mapped dictionary of the provided dict :param dictionary: dictionary to be reverse mapped :return: inverse mapped dict """ return {v: k for k, v in dictionary.items()}
def split_number(number, multiplier): """Decodes a number into two. The number = high * multiplier + low, and This method returns the tuple (high, low). """ low = int(number % multiplier) high = int(number / multiplier) return (high, low)
def parse_schema(raw: dict) -> dict: """Parse a field, adapter, or config schema into a more user friendly format. Args: raw: original schema """ parsed = {} if raw: schemas = raw["items"] required = raw["required"] for schema in schemas: name = schema[...
def remove_param_from_pytest_node_str_id(test_id, param_id_str): """ Returns a new test id where the step parameter is not present anymore. :param test_id: :param param_id_str: :return: """ # from math import isnan # if isnan(step_id): # return test_id new_id = test_id.repla...
def flip(func, a, b): """Call the function call with the arguments flipped. This function is curried. >>> def div(a, b): ... return a / b ... >>> flip(div, 2, 1) 0.5 >>> div_by_two = flip(div, 2) >>> div_by_two(4) 2.0 This is particularly useful for built in functions ...
def get_last_package_name(name): """ Returns module name. From `a.b.c` it returns `c`. :param str name: Full module name :return: Last package name / module name. :rtype: str """ return name.split(".")[-1]
def thumb_url_form(url): """Takes the SLWA photo url and returns the thumbnail url. Note this function is heavily influenced by the format of the catalogue and could be easily broken if the Library switches to a different url structure. """ if url[-4:] != '.png' and url[-4:] != '.jpg': url...
def get_target_value_list(data_set): """Get the list that contains the value of quality.""" target_value_list = [] for line in data_set: target_value_list.append(line[-1]) return target_value_list
def remove_duplicates(jobs): """ Removee test duplicates which may come from JOBSARCHIVED4 and JOBSARCHIVED :return: """ jobs_new = [] pandaids = {} for job in jobs: if job['pandaid'] not in pandaids: pandaids[job['pandaid']] = [] pandaids[job['pandaid']].append(...
def get_dot_indices(face_index_from_1): """Get indices (from 0 through 20) corresponding to dots on the given face (from 1 through 6).""" if face_index_from_1 == 1: return [0] elif face_index_from_1 == 2: return [1,2] elif face_index_from_1 == 3: return [3,4,5] elif face_inde...
def divided_by(base, dvdby): """Implementation of / or //""" if isinstance(dvdby, int): return base // dvdby return base / dvdby
def spotinst_tags_to_dict(tags): """ Converts a list of Spotinst tag dicts to a single dict with corresponding keys and values """ return {tag.get('tagKey'): tag.get('tagValue') for tag in tags or {}}
def make_kwargs_for_wallet(data): """ :param data: dict type """ fee_dict = {} channel_config = data.get("Channel") if channel_config: for key in channel_config: fee_dict[key] = channel_config[key].get("Fee") return { "ip": data.get("Ip"), "public_key": da...
def decode_int(string): """ Decodes integer from byte string """ result = 0 for n, c in enumerate(string): if isinstance(c, str): c = ord(c) result |= c << (8 * n) return result
def eval_add(lst): """Evaluate an addition expression. For addition rules, the parser will return [number, [[op, number], [op, number], ...]] To evaluate that, we start with the first element of the list as result value, and then we iterate over the pairs that make up the rest of the list, adding or subtracti...
def transpose(lines): """ Transpose the lines """ lines = lines.split("\n") if not lines: return "" max_length = max(map(len, lines)) result = [] for index in range(max_length): col, spaces = "", "" for line in lines: try: col += sp...
def _is_items(lst): """Is ``lst`` an items list? """ try: return [(a, b) for a, b in lst] except ValueError: return False
def reverse_complement(nuc_sequence): """ Returns the reverse complement of a nucleotide sequence. >>> reverse_complement('ACGT') 'ACGT' >>> reverse_complement('ATCGTGCTGCTGTCGTCAAGAC') 'GTCTTGACGACAGCAGCACGAT' >>> reverse_complement('TGCTAGCATCGAGTCGATCGATATATTTAGCATCAGCATT') 'AATGCTGAT...
def number(spelling): """ Number construction helper. This helper tries to cast the number as an integer. If that is not possible it switches over to float representation as a last resort. """ try: return int(spelling) except ValueError as e: try: v = float(spell...
def validate_server_port(port): """ Returns Whether or not gicen port is a valid server port. """ try: int(port) return True except: return False
def extract_edge_type(edge_address): """Given a graph edge address, returns the edge type. :param edge_address: The edge address :return: The label """ edge_type = edge_address[2] if edge_type == "REACTS": return "REACTS" + edge_address[3] else: return edge_type
def get_result_from_file(file_name): """ load dependency result from file :param file_name: name of the file that stores functional dependency :return: a sequence of each stripped line string """ try: with open(file_name, 'r') as f: raw_data = f.read() except IOError as e...
def return_code(text): """ Make return code for slack :param text(string): slack return text :return (string): json format for slack """ payload={'text': text} return payload
def indent(t, indent=0, sep='\n'): """Indent text.""" return sep.join(' ' * indent + p for p in t.split(sep))
def karatsuba(x, y): """Function to multiply 2 numbers in a more efficient manner than the grade school algorithm""" if len(str(x)) == 1 or len(str(y)) == 1: return x*y else: n = max(len(str(x)), len(str(y))) nby2 = n / 2 a = x / 10**(nby2) b = x % 10**(nby2) ...
def remove_unwanted_files(workdir, files): """ Remove files from the list that are to be ignored by the looping job algorithm. :param workdir: working directory (string). Needed in case the find command includes the workdir in the list of recently touched files. :param files: list of recently touch...
def get_id_from_airlabname(name): """ Directly get the clonenames from raulnames :param name: :return: """ newname = name.split('_')[-1] newname = newname.split('(')[0] if newname == '': newname = name return newname
def get_parameter_kwargs(args): """Get parameter name-value mappings from the raw arg list An example: ['-g', 'RG', '--name=NAME'] ==> {'-g': 'RG', '--name': 'NAME'} :param args: The raw arg list of a command :type args: list :return: The parameter name-value mappings :type: dict """ p...
def set_flag_state(flags: int, flag: int, state: bool = True) -> int: """Set/clear binary `flag` in data `flags`. Args: flags: data value flag: flag to set/clear state: ``True`` for setting, ``False`` for clearing """ if state: flags = flags | flag else: fla...
def sentence_preprocessing(sentence): """Prepossing the sentence for SQL query. Prepocessing the sentence for query: - Delete redundant space - Convert into lower case Args: sentence (str): the str to be processed Returns: str: the str after processing """ ...
def next_power_of_2(n): """ Return next power of 2 greater than or equal to n """ return 2**(n-1).bit_length()
def decode(string): """ Decode the string """ result, index, count = "", 0, "" while index < len(string): if string[index].isdigit(): count += string[index] else: if not count: result += string[index] else: resul...
def update_all_dict_values(my_dict, value): """ All the values of the given dictionary are updated to a single given value. Args: my_dict (dict): Given dictionary. value: Can be any data structure. list, dict, tuple, set, int or string. Returns: dict: Updated dict with the perf...
def apply_profile(fgraph, node, profile): """Return apply profiling informaton.""" if not profile or profile.fct_call_time == 0: return None time = profile.apply_time.get((fgraph, node), 0) call_time = profile.fct_call_time return [time, call_time]
def fibonacci(n): """Get all terms of the Fibonacci sequence until the first term has a length of N digits.""" a, b = 1, 1 f = [a, b] while len(str(b)) < n: a, b = b, a + b f.append(b) return f
def main(dog_name): """ This function takes in dog name and returns info about it. :param dog_name: string :return: string """ print("This is the best!") print(dog_name) return "My dog is named" + dog_name
def asId(v, default=0): """The *asId* method transforms the *value* attribute either to an instance of @ int@ or to @None@, so it can be used as *id* field in a @Record@ instance. If the value cannot be converted, then the optional *default* (default value is @0 @) is answered. >>> asId(123) == 123...
def DGS3600(v): """ DGS-3600-series :param v: :return: """ return ( "DGS-3610" not in v["platform"] and "DGS-3620" not in v["platform"] and v["platform"].startswith("DGS-36") )
def parser(response): """Parses the json response from CourtListener /opinions endpoint.""" results = response.get("results") if not results: return [] ids = [] for result in results: _id = result.get("id", None) if _id is not None: ids.append(_id) return ...
def iround(val, lower): """Round value to lower or upper integer in case of the equally good fit. Equas to math.round for lower = False. val: float - the value to be rounded lower: bool - direction of the rounding resolution in case of the equally good fit return v: int - rounded value >>> iround(2.5, True...
def teddy(do_print = True): """ Returns and optionally prints a teddy bear ASCII art. Arguments --------- do_print : bool Whether to print the teddy bear. Returns ------- str : Reeturns a teddy bear ASCII art. Examples -------- teddy() """ # Art by ...