content
stringlengths
42
6.51k
def interpolate_color(color1, color2, f): """ Helper function for color manipulation. When f==0: color1, f==1: color2 """ color1 = [int(color1[x:x+2], 16) for x in [1, 3, 5]] color2 = [int(color2[x:x+2], 16) for x in [1, 3, 5]] r = (1 - f) * color1[0] + f * color2[0] g = (1 - f) * color1[1] ...
def tup_list_maker(tup_list): """ Takes a list of tuples with index 0 being the text_id and index 1 being a list of sentences and broadcasts the text_id to each sentence """ final_list = [] for item in tup_list: index = item[0] sentences = item[1] for sentence in sentence...
def _column_letter(n: int) -> str: """ >>> _column_letter(0) 'A' >>> _column_letter(1) 'B' >>> _column_letter(25) 'Z' >>> _column_letter(26) 'AA' >>> _column_letter(27) 'AB' """ code = "" n += 1 while n > 0: n, mod = divmod(n - 1, 26) cod...
def bytes_to_int(value): """cast byte value to int""" return int.from_bytes(value, 'big')
def fib(n): """ This is an example of decorated function. Decorators are included in the documentation as well. This is often useful when documenting web APIs, for example. """ if n < 2: return n return fib(n - 1) + fib(n - 2)
def isValidAsciiStr(filename): """Return false if filename contains non-printable char.""" for i in range(len(filename)): s = filename[i] c = ord(s) if (c < 32) or (c >= 127): return False return True
def Hn(n): """ Hexagonal numbers.""" return n * (2 * n - 1)
def _parse_spectrum(line: str, spec: list) -> int: """ Add peak data to spec :param line: The raw line information from .msp file :param spec: The spectrum will be added. :return: 0: success. 1: no information in this line. """ lines = line.split() if len(lines) >= 2: mz, intensi...
def projectLogsFileName(id, config): """ Returns the filename of the log zip file created by calling syscfg.projectLogs(id) """ return config['converter.project_logs_name'] % id
def get_slots(intent_request): """ Fetch all the slots and their values from the current intent. """ return intent_request["currentIntent"]["slots"]
def quick_sort(m): """Select a random number (pivot), then divide the array into 3 arrays of [smaller than pivot], [equal to pivot], and [larger than pivot], and merge them again in quick_sort([small])-[equal]-quick_sort([large]) order""" if len(m) <= 1: return m pivot = m[0] # random p...
def is_numeric(value): """ Check whether *value* is a numeric value (i.e. capable of being represented as a floating point value without loss of information). :param value: The value to check. This value is a native Python type. :return: Whether or not the value is numeric. :rtype: bool """ if not isinstance(v...
def escaper(msg): """ escape message this function escapes special characters in the message. These are 0x5c, 0x11 and 0x13 which are '\' and XON and XOFF characters. @param msg: the message to escape @return: the escaped message """ out = bytes(sum([[0x5c, 0xFF ^ x ] if x in [0x11, 0x1...
def shearStress(f_parallel,A): """variables: sigma_shear=shear stress (parallel) f=force a=area""" sigma_shear = f_parallel/A return sigma_shear
def set_var(L=1, rho=1, gamma=0.1, nodes=5): """ Set variable/parameter args: L: length (m) (default=1) rho: density (kg/m3) (default=1) gamma: gamma (kg/(m.s)) (default=0.1) nodes: nodes (default=5) returns: dictionary: with key 'L, rho, gamma, nodes, d...
def evens_using_for_loop(count): """ Calculate evens using for loop """ evens = [] for i in range(count): if i % 2 == 0: evens.append(i) return evens
def unique_code(codecs): """Returns a list where every code exists only one. The first item in the list is taken """ seen = [] unique = [] for codec in codecs: if 'code' in codec: if codec['code'] in seen: continue else: seen.appen...
def format_review(__, data): """Returns a formatted line showing the review state and its reference tags.""" return ( "<li>[{state}] <a href='{artist_tag}/{album_tag}.html'>" "{artist} - {album}</a></li>\n" ).format(**data)
def time_format(sec): """ Args: param1 """ hours = sec // 3600 rem = sec - hours * 3600 mins = rem // 60 secs = rem - mins * 60 return hours, mins, secs
def user(user): """User profile page. .. :quickref: User; Get Profile Page :param user: user login name :status 200: when user exists :status 404: when user doesn't exist """ return 'hi, ' + user
def parse_server(node): """Return hostname and presence_id for given server.presence node.""" if '#' not in node: return node, '-1' hostname, presence_id = node.split('#') return hostname, presence_id
def byte_to_megabyte(byte): """Convert bytes to megabytes """ return byte / 1024 ** 2
def rosenbrock_2par(x, *args): """Rosenbrock function with 2 parameters. To be used in the constrained optimization examples. When subject to constraints: (x[0] - 1) ** 3 - x[1] + 1 <= 0 x[0] + x[1] - 2 <= 0 the global minimum is at f(1., 1.) = 0. Bounds: -1.5 <= x[0] <= 1.5 ...
def remap_values(values, target_min=0.0, target_max=1.0, original_min=None, original_max=None): """ Maps a list of numbers from one domain to another. If you do not specify a target domain 0.0-1.0 will be used. Parameters ---------- val : list of int, list of long, list of float The val...
def hailstone(n): """ *** write a proper docstring here *** >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 *** add two more testcases here *** """ # *** YOUR CODE HERE *** return n
def parse_multiline_as_lines(s): """Same as parse_multiline, but returns a list of lines. (This is the inverse of format_multiline_lines.) """ lines = s.splitlines() for i, line in enumerate(lines): if i == 0: continue if line.startswith(' '): line = line[1:]...
def sanitize_id(id): """ Ids may only contain a-z, A-Z, 0-9, - and must have one character :param id: the ID to be sanitized :return: sanitized ID """ return id.replace(':', '-')
def f_end(version): """Gives fortran file ending used in MESA depending on the version used Parameters ---------- version : int version number of MESA to be checked Returns ------- str Either 'f90' or 'f', depending on `version`. """ if version >= 7380: retu...
def rc_node(node): """ gets reverse complement spades node label """ if node[-1] == "'": return node[:-1] else: return node + "'"
def detag(sentences, tags): """ remove all tag strings out of all sentences :param sentences: a list of string sentences :param sentences: a list of string tags :return: """ re_sentences = [] for sentence in sentences: re_sent = sentence for tag in tags: re_s...
def usage(progname): """ print program usage """ print("Usage: %s /path/to/generated/tables output.cpp " % progname) return 1
def offer_str(rq_offer): """ this function converts the offer_dict of travelers to a string for debugging """ return ", ".join(["{}:{}".format(k, str(v)) for k, v in rq_offer.items()])
def _date_handler(obj): """Convert date objects to JSON serializable format.""" return obj.isoformat() if hasattr(obj, 'isoformat') else obj
def is_numeric(s): """Test whether or not a given value is numeric (integer or float)""" try: float(s) return True except ValueError: return False except TypeError: return False
def get_lv_name_base(fs_type, mount_point): """Return a logical volume base name using given parameters""" if 'swap' in fs_type.lower(): lv_default = 'swap' elif mount_point.startswith('/'): if mount_point == '/': lv_default = 'root' else: lv_default = mount_p...
def autofill(field, value): """ Return a bcm dictionary with a command to automatically fill the corresponding "field" with "value" """ return {'mode': 'autofill', 'field': field, 'value': value}
def property_from_topic(mqtt_topic): """Extract the RuuviTag's property from the MQTT topic.""" return mqtt_topic.split("/")[3]
def parse_network(dyn_data: dict) -> dict: """ parses out network information from dynamic data dictionary Args: dyn_data: dictionary read from dynamic data Returns: network_dict: dictionary parsing the network information extracted from dyn_data """ if dyn_data == {}: ...
def buildConnectString(params): """ Build a connect String from a dictionary of parameters. Returns String.""" return ";".join(["%s=%s" % (k,v) for k,v in params.items()])
def decide_winners(matches): """ Assignment 4 """ result = [] for match in matches: match_result = [] for game in match: score = game.split("-") if int(score[0]) > int(score[1]): match_result.append(0) else: match_re...
def sample_period_to_seconds(sample_period: str) -> int: """ Convert the sample period to seconds. Parameters ---------- sample_period : str A sample period reading from the data file. Returns ------- sample_period int Sample period in seconds. """ hours, minute...
def gr_correction(bprop, xi, redshift): """Returns gr correction factor to convert from kepler to mesa frame """ corrections = { 'rate': 1, # mesa time in observer coordinate? 'dt': 1, 'fluence': xi**2, 'peak': xi**2, } return corrections[bprop]
def val_to_list(val, allow_none=False, convert_tuple=False): """ Convert a single value to a list :param val: Value to convert to list :param allow_none: Convert the value even if it's None :param convert_tuple: Convert to list if it's a tuple :return: """ if val is not None or allow_non...
def get_new_goal(prev_turn, curr_turn): """ If multiple domains are updated between turns, return all of them """ new_goals = [] # Sometimes, metadata is an empty dictionary, bug? if not prev_turn or not curr_turn: return new_goals for domain in prev_turn: if curr_turn[domai...
def reverse_mac(rmac): """Change LE order to BE.""" if len(rmac) != 12: return None reversed_mac = rmac[10:12] reversed_mac += rmac[8:10] reversed_mac += rmac[6:8] reversed_mac += rmac[4:6] reversed_mac += rmac[2:4] reversed_mac += rmac[0:2] return reversed_mac
def _high_bit(value: int) -> int: """Return index of the highest bit, and -1 if value is 0.""" return value.bit_length() - 1
def map_type_web2py_to_sql(dal_type): """ This function maps the web2py type into sql type , It is usefull when writing sql queries to change the properties of a field Mappings string --> Varchar """ if dal_type == "string": return "varchar" else: return dal_typ...
def gray2bin(val): """ convert a binary Gray code number to reflected binary number. :param val: value to convert (gray code) :return: binary value """ bits = 64 tmp = val max_val = 0 for i in range(bits): max_val |= 1 << i try: assert tmp <= max_val except Asserti...
def round_day(tval): """Round tval to nearest day.""" return(round(tval/86400) * 86400)
def get_duplicates(sequence): """Get all duplicates of a list :param sequence: Generator configuration entity :type sequence: dict :returns: The duplicates :rtype: list """ seen = set() seen_add = seen.add seen_twice = set(x for x in sequence if x in seen or seen_add(x)) return ...
def get(dic, *keys, **kwargs): """Return the value of the last key given a (nested) dict and list of keys. If any key is missing, or if the value of any key except the last is not a dict, then the default value is returned. The default value may be passed in using the keyword 'default=', otherwise ...
def ensure_list(string_or_list): """Ensure that the input is converted to a list. Parameters ---------- string_or_list : str or list Returns ------- list Examples -------- >>> ensure_list("a") ['a'] >>> ensure_list(["b"]) ['b'] """ return [string_or_list] ...
def secant(f,x0,x1, TOL=0.001, NMAX=100): """ Takes a function f, start values [x0,x1], tolerance value(optional) TOL and max number of iterations(optional) NMAX and returns the root of the equation using the secant method. """ n=1 while n<=NMAX: x2 = x1 - f(x1)*((x1-x0)/(f(x1)-f(x0))) if x2-x1 < TOL: ret...
def _convert_template_name_to_file_name(template_name: str, plugin_name: str) -> str: """ Convert template names to pythonic file names. Args: template_name (str): The template's name plugin_name (str): The plugin's name Returns: A string containing the customized/pythonic file...
def find_first_tag(tags, entity_type, after_index=-1): """Searches tags for entity type after given index Args: tags(list): a list of tags with entity types to be compaired too entity_type entity_type(str): This is he entity type to be looking for in tags after_index(int): the start tok...
def GetBuildLogPathInGCS(logs_folder, build_id): """Gets a full Cloud-Storage path to a log file. This is a simple convenience function that mirrors the naming convention that the Blueprints Controller API uses for log files. Args: logs_folder: string, the full Cloud Storage path to the folder containing ...
def create_command(command, params, quotes): """Create commandline substring for codegen --reload commandline """ result_command = command if len(params) > 0: for item in params: if quotes: result_command = result_command + u' "{}"'.format(item) else: ...
def extract_description(texts): """Returns all the text in text annotations as a single string""" document = '' for text in texts: try: document += text['description'] except KeyError as e: print('KeyError: %s\n%s' % (e, text)) return document
def and_query(*qrys): """create a and query from a given set of querys. :param qrys: the respective queries """ return "(" + "&".join([qry for qry in qrys if qry]) + ")"
def pass_through(info, inner, *args, **kw): """ To add another frame to the call; detectable because __tracback_info__ is set to `info` """ __traceback_info__ = info return inner(*args, **kw)
def mb(bytes): """Format the given value in bytes as a string in megabytes""" return "%dMB" % (bytes/1024.0/1024.0)
def get_filename(url): """ Extracts filename from the url return the last path """ return url.split('/')[-1]
def infer_index_rep(motif, postfilter): """ Infer index of a repeated element from postfilter and motif. Return 2 if not found. :param motif: list(tuple(seq, rep)) - motif object :param postfilter: list(int)/None - postfilter numbers :return: int - 1-based inferred index of a repeated element ""...
def find_nested_operators(addresses, op_ids): """ Given a list of string of the form "n1-n2-...-" (the address strings from operator_addr). Return all the nested operators. The way we do it is pretty inefficient but that's okay... """ nested_operators = set() for addr in addresses: # Ig...
def set_contourf_properties_style(stroke_width, fcolor, fill_opacity): """Set style property values for Polygon using Leaflet naming convention. Assignment pattern: wrong name leaflet name - - - - - - fill fillColor fill-opacity ...
def not_radical(cgr): """ Checking for charged atoms in a Condensed Graph of Reaction :param cgr: Condensed Graph of the input reaction :return: bool """ if cgr and cgr.center_atoms: if any(x.is_radical or x.p_is_radical for _, x in cgr.atoms()): return False ret...
def mtof(p): """Converts midi pitch to frequency.""" return 440.0 * 2 ** ((p - 69) / 12.0)
def find_missing_08s(all_texts): """determines which $08s have yet to be inserted based on their start addresses""" missing_08s = 0 for map_id in all_texts.keys(): for text_id in all_texts[map_id].keys(): for line_id in all_texts[map_id][text_id].keys(): if not line_i...
def region_str(chrom, start, end=None, strand=+1): """Assemble a region string suitable for consumption for the Ensembl REST API. The generated string has the format: ``{chrom}:{start}..{end}:{strand}`` """ if end is None: end = start return f'{chrom}:{start}..{end}:{stran...
def subtractQueryParameters(args, request_keywords=None): """subtract parameters related to sorting and limiting search results from a given set of arguments, also removing them from the input""" def get(name): for prefix in "sort_", "sort-": key = "%s%s" % (prefix, name) va...
def get_lh5_element_type(obj): """Get the lh5 element type of a scalar or array For use in the datatype attribute of lh5 objects Parameters ---------- obj : str or any object with a numpy dtype Returns ------- el_type : str A string stating the determined element type of the o...
def is_float(word: str): """ Checks if a number is a float """ if "." not in word: return False split = word.split(".") if len(split) > 2 or len(split) < 1: return False for num in split: if not num.isdigit(): return False return True
def filter_file_paths_by_extension(file_paths, ext='csv'): """ Filters out file paths that do not have an appropriate extension. :param file_paths: list of file path strings :param ext: valid extension """ valid_file_paths = [] for file_path in file_paths: ext = ".%s" % ext if ext[0...
def default_max_eep(mass): """For MIST v1.2 """ if mass < 0.6: return 454 elif mass == 0.6: return 605 elif mass == 0.65: return 808 elif mass < 6.0: return 1710 else: return 808
def swap(input_list, switch): """ Given an input list and a tuple of indices, the indexed list elements are swapped. """ input_list[switch[1]], input_list[switch[0]] = input_list[switch[0]], input_list[switch[1]] return input_list
def generate_image_master(categories: list) -> dict: """ Takes in the list of categories and images and generate a master dictionary containing all of the images :param categories: :return: """ master_dict = {} for category in categories: master_dict = {**master_dict, **category....
def placeholders_for(iterable, paramstyle='qmark', startfrom=1, delim=','): """Makes query placeholders for the input iterable: [1, 2, 3] => '?,?,?' Returns a string that can safely be formatted directly into your query. Generally equal to delim.join('?' for x in iterable) but see below for exceptions ...
def get_type(attributes): """ Compute mention type. Args: attributes (dict(str, object)): Attributes of the mention, must contain values for "pos", "ner" and "head_index". Returns: str: The mention type, one of NAM (proper name), NOM (common noun), PRO (pronoun), DEM (d...
def _GetPrincipleQuantumNumber(atNum): """ Get the principle quantum number of atom with atomic number equal to atNum """ if atNum<=2: return 1 elif atNum<=10: return 2 elif atNum<=18: return 3 elif atNum<=36: return 4 elif atNum<=54: return 5...
def _safe_rep(obj, short=False): """Helper for assert_* ports""" try: result = repr(obj) except Exception: result = object.__repr__(obj) if not short or len(result) < 80: return result return result[:80] + ' [truncated]...'
def metalicity_sandage(amplitude_v, log_p): """ Returns the Sandage formula metalicity of the given RRab RR Lyrae. Note that this formula "produces an unphysically bimodal distribution of photometric metalicities, which is a reflection of the Oosterhoff dichotomy". (Skowron et al., 2016) (Sand...
def remove_unnamed_parameters(db): """Remove parameters which have no name. They can't be used in formulas or referenced.""" for ds in db: if "parameters" in ds: ds["parameters"] = { key: value for key, value in ds["parameters"].items() if not ...
def convert_weight_metric(weight): """Converts user's weight from Imperial to metric and returns a float""" weight_metric = weight * 0.45359237 return weight_metric
def relevance_gain_np(grading, max_grade): """Plain python version of `relevance_gain`, see the documentation of that function for details.""" inverse_grading = -grading + max_grade return (2 ** inverse_grading - 1) / (2 ** max_grade)
def wrap_neg_index(index, dim): """Converts a negative index into a positive index. Args: index: The index to convert. Can be None. dim: The length of the dimension being indexed. """ if index is not None and index < 0: index %= dim return index
def NOT(expression): """ Evaluates a boolean and returns the opposite boolean value. See https://docs.mongodb.com/manual/reference/operator/aggregation/not/ for more details :param expression: An array of expressions :return: Aggregation operator """ return {'$not': [expression]}
def find_alias(names, aliases): """Given a list of names, find the one that matches a list of aliases. Inspired by and very similar to `sncosmo.alias_map`. Parameters ---------- names : list[str] List of names that are available aliases : list[str] List of aliases to search thr...
def unique(seq): """Remove duplicate elements from seq. Assumes hashable elements. >>> unique([1, 2, 3, 2, 1]) [1, 2, 3] """ return list(set(seq))
def fibonacci(position): """ Based on a position returns the number in the Fibonacci sequence on that position """ if position == 0: return 0 elif position == 1: return 1 return fibonacci(position-1)+fibonacci(position-2)
def iou(box1, box2): """Computes Intersection over Union value for 2 bounding boxes """ b1_x0, b1_y0, b1_x1, b1_y1 = box1 b2_x0, b2_y0, b2_x1, b2_y1 = box2 int_x0 = max(b1_x0, b2_x0) int_y0 = max(b1_y0, b2_y0) int_x1 = min(b1_x1, b2_x1) int_y1 = min(b1_y1, b2_y1) int_area = (int_x1...
def gcd(p, q): """Returns the greatest common divisor of p and q >>> gcd(48, 180) 12 """ while q != 0: (p, q) = (q, p % q) return p
def get_minimal_representation(pos, ref, alt): """ Get the minimal representation of a variant, based on the ref + alt alleles in a VCF This is used to make sure that multiallelic variants in different datasets, with different combinations of alternate alleles, can always be matched directly. Note ...
def kernel_1D(n, a=0.6): """Kernel function in 1 dimension""" kernel = [0.0625, 0.25, 0.375, 0.25, 0.0625] # if n == 0: # return a # elif n == -1 or n == 1: # return 1./4 # elif n == -2 or n == 2: # return 1./4 - float(a)/2 # else: # return...
def tonum(s): """Converts a string representation of a decimal, hexadecimal, or binary number to a number value or None.""" if type(s) in (int, float): return s if s is None: return 0 base = 10 if isinstance(s, str): if "x" in s: base = 16 elif "b" in s:...
def version_value(major, minor, patch): """ Return a numeric version code based on a version string. The version code is useful for comparison two version strings to see which is newer. """ value = (major << 16) | (minor << 8) | patch return value
def get_template_titles(templates): """ Given an iterable of templates, return a set of pages. @param templates: iterable of templates (L{pywikibot.Page}) @type templates: iterable @rtype: set """ titles = set() for template in templates: if template.isRedirectPage(): ...
def hamming_distance(seq1, seq2): """ Calculate the Hamming distance between two sequences of the same length. The Hamming distance corresponds to the number of characters that differ between these two sequences. Args: seq1 (str), seq2 (str): Sequences to compare. Returns: ...
def unpack_singleton(x): """ >>> unpack_singleton([[[[1]]]]) 1 >>> unpack_singleton(np.array(np.datetime64('2000-01-01'))) array(datetime.date(2000, 1, 1), dtype='datetime64[D]') """ while True: try: x = x[0] except (IndexError, TypeError, KeyError): ...
def computeFraction( poi_messages, all_messages ): """ compute the fraction of messages to/from a person that are from/to a POI """ fraction = 0 if poi_messages == 'NaN' or all_messages == 'NaN': fraction = 0 else: fraction = float(poi_messages)/all_messages return fraction
def is_oppo_interception(event_list, team): """Returns whether the opponent intercepted the ball""" is_true = False for e in event_list[:1]: if e.type_id == 8 and e.team != team: is_true = True return is_true