content
stringlengths
42
6.51k
def do_one(fns, x): """ Try each of the functions until one works. Then stop. """ for fn in fns: result = fn(x) if result != x: return result return x
def to_anchor_id(text: str) -> str: """ Converts `text` to an anchor ID. This method is intended to be compatible with GitHub's method of converting heading text to anchors for tables of content. """ a = "" for c in text: if c in [" ", "-"]: a += "-" elif str.is...
def encode_string(string): """Encodes a string to bytes, if it isn't already. :param string: The string to encode""" if isinstance(string, str): string = string.encode('utf-8') return string
def find_grid_index_on_dimension(pos: float, min_value: float, cell_len: float) -> int: """ Parameters ---------- pos: float position min_value: float min value of the dimension cell_len: float size of each grid cell of the dimension Returns ------- int ...
def make_tweet_content(preamble: str, message: str, link: str) -> str: """ Make formatted tweet message from preamble, message and link. Arguments: preamble (str): Preamble to be used in the beginning of the tweet. message (str): Main message of the tweet. link (str): Link to be add...
def _ci_to_hgvs_coord(s, e): """ Convert continuous interbase (right-open) coordinates (..,-2,-1,0,1,..) to discontinuous HGVS coordinates (..,-2,-1,1,2,..) """ def _ci_to_hgvs(c): return c + 1 if c >= 0 else c return (None if s is None else _ci_to_hgvs(s), None if e is None else _ci_to_hg...
def part1(lines): """ >>> part1(['(())']) 0 >>> part1(['()()']) 0 >>> part1(['(((']) 3 >>> part1(['(()(()(']) 3 >>> part1(['))(((((']) 3 >>> part1(['())']) -1 >>> part1(['))(']) -1 >>> part1([')))']) -3 >>> part1([')())())']) -3 """ lin...
def eh_peca(arg): """ Reconhecedor peca. Recebe um argumento de qualquer tipo e devolve True se o seu argumento corresponde a um TAD peca e False caso contrario. :param arg: universal, argumento. :return: bool, veracidade do argumento. """ return isinstance(arg, list) and len...
def lru(x): """ Lru function """ return (1./2)**x
def results_config(current_page): """Returns a config for each source's search results page.""" return { "coindesk": { "page_url": "https://www.coindesk.com/page/" + str(current_page) + "/?s=Bitcoin", "item_XPATH": '//div[@class="post-info"]', # XPATH for the search result item ...
def count_ordinal(n: int) -> str: """ Convert an integer into its ordinal representation:: make_ordinal(0) => '0th' make_ordinal(3) => '3rd' make_ordinal(122) => '122nd' make_ordinal(213) => '213th' """ n = int(n) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] if 11 ...
def mcari(b3, b4, b5): """ Modified Chlorophyll Absorption in Reflectance Index \ (Daughtry et al. 2000). .. math:: MCARI = ((b5 - b4) - 0.2 * (b5 - b3)) * (b5 / b4) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-e...
def get_sbo_terms( miriam_urns): """ takes a list of miriam encoded urn, e.g. ['urn:miriam:GO:0016579', 'urn:miriam:SBO:0000330'] and returns the strings ["SBO:0000330"] """ return [ i[11:]for i in miriam_urns if i.startswith( "urn:miriam:SBO:")]
def geometric_sum(n): """ calculate the geometric sum of n-1 :param n: :return: """ if n < 1: return 1 else: return 1 / (pow(2, n)) + geometric_sum(n - 1)
def repl_num(s:str, sub="xxnum") -> str: """Removed digits""" if s.isdigit(): return sub return s
def str2tuple(string: str, type_func) -> tuple: """ Takes a Python list-formatted string and returns a tuple of type type_func """ return tuple(map(type_func, string.strip("()[]").split(",")))
def create_events_blocks(events): """ Function to create list of events grouped by time. :param events: all (or available) elements of `DayStudyEvents` :type events: list :return: list of events grouped by time :rtype: list of list """ event_blocks = [] for i, event in enumerate(eve...
def dm2skin_getNumberOfNonZeroElements(list): """Returns the number of non-zero elements in the given list""" return int(sum([1 for x in list if x != 0.0]))
def str_to_bytes(s): """ Converts a given string into an integer representing bytes where G is gigabytes, M is megabytes, K is kilobytes, and B is bytes. """ if type(s) is int: return s units = {'B': 1, 'K': 1024, 'M': 1024 ** 2, 'G': 1024 ** 3} if len(s) < 2: raise Valu...
def get_subdivision_resource(country_alpha2: str, subdivision_code=None) -> str: """Get the """ if subdivision_code is None: return 'country/{country_alpha2}/subdivision'.format(country_alpha2=country_alpha2) else: return 'country/{country_alpha2}/subdivision/{subdivision_code}'.format(count...
def get_var(input_dict, accessor_string): """Gets data from a dictionary using a dotted accessor-string""" current_data = input_dict for chunk in accessor_string.split('.'): current_data = current_data.get(chunk, {}) return current_data
def is_lag(local_link_information): """Judge a specified port param is for LAG(linkaggregation) or not. :param local_link_information: physical connectivity information :type local_link_information: list of dict :returns: True(mode is LAG) or False(otherwise) :rtype: boolean """ return (l...
def trim(str): """Remove multiple spaces""" return ' '.join(str.strip().split())
def time_to_string(time: int) -> str: """Convert time to string representation Args: time (int): Time in seconds Returns: str: Time in MM:SS format """ return "%02d:%02d" % (time // 60, time % 60)
def translate(a, b) -> tuple: """Translates the point.""" return a[0] + b[0], a[1] + b[1]
def make_pairs(txt): """ Takes a string ('txt') and separates it into pairs of characters returning a list with those pairs. """ lista = [] string = "" count = 0 if len(txt)%2 != 0 : count = 1 for i in range(len(txt)): s...
def is_response_paginated(response_data): """Checks if the response data dict has expected paginated results keys Returns True if it finds all the paginated keys, False otherwise """ try: keys = list(response_data.keys()) except AttributeError: # If we can't get keys, wer'e certainl...
def ToLower(v): """Transform a string to lower case. >>> s = Schema(ToLower) >>> s('HI') 'hi' """ return str(v).lower()
def string_is_bigger(s1, s2): """ Return s1 > s2 by taking into account None values. None is always smaller than any string. None > "string" works in python2 but not in python3. This function makes it work in python3 too. """ if s1 is None: return False elif s2 is None: ret...
def is_valid_mimetype(response): """Return ``True`` if the mimetype is not blacklisted. :rtype: bool """ blacklist = ["image/"] mimetype = response.get("mimeType") if not mimetype: return True for bw in blacklist: if bw in mimetype: return False return Tr...
def bytes_to_string(data: bytes): """Converts data to string""" return str(data, "utf-8") if isinstance(data, bytes) else data
def _partition_anomalies(windows, k): """ :param windows: windows, sorted by anomaly score in descending order :param k: number of partitions :return: partition positions """ diffs = [windows[iw - 1][1] - windows[iw][1] for iw in range(1, len(windows))] top_jump_positions = sort...
def _ical_escape(text): """ Format value according to iCalendar TEXT escaping rules. from https://github.com/collective/icalendar/blob/4.0.2/src/icalendar/parser.py#L20 """ return ( text.replace(r'\N', '\n') .replace('\\', '\\\\') .replace(';', r'\;') .replace(',', r'...
def searchfiles(pattern='C:\\RoboDK\\Library\\*.rdk'): """List the files in a directory with a given extension""" import glob return glob.glob(pattern)
def krieger(client, channel, nick, message, cmd, args): """ film film FILM FILM FILM! FILM!! FILM!!! """ fmt = '{0} {0} {1} {1} {1}! {1}!! {1}!!!' try: word = args[0] except IndexError: word = 'film' return fmt.format(word.lower(), word.upper())
def ebay_fee(sell_price): """Returns the fees charged by ebay.com given the selling price of fixed-price books, movies, music, or video games. fee is $0.50 to list plus 13% of selling price up to $50.00, 5% of amount from $50.01 to $1000.00, and 2% for amount $1000.01 or more.""" p50 = 0.13 #...
def get_intersection(cx1, cy1, cos_t1, sin_t1, cx2, cy2, cos_t2, sin_t2): """ Return the intersection between the line through (*cx1*, *cy1*) at angle *t1* and the line through (*cx2*, *cy2*) at angle *t2*. """ # line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0. # line1...
def create_args_list(arg_map): """Create a list of arguments for a node from a map. Create a list of arguments that can be passed to a node from a dictionay of key, value argument pairs. * arg_map -- the map of arguments """ args = [] for key, value in arg_map.items(): args.append...
def get_glyph(entity_type): """ Generates appropriate Font Awesome icon strings based on entity type strings, such as a person icon (fa-male) for the 'person' entity, etc. :param entity_type: String specifying the entity type to be visualized :return: HTML string with the corresponding Font Awesome icon """ if ...
def hr_size(size): """Returns human readable size input size in bytes """ units = ["B","kB","MB","GB","TB","PB"] i = 0 # index while (size > 1024 and i < len(units)): i += 1 size /= 1024.0 return f"{size:.2f} {units[i]}"
def list_objects(list_object): """Extracting uuids from informed json. Args: list_object(json): string containing the project's uuid Returns: all uuids """ all_projects_ids = [] for i in list_object: all_projects_ids.append(i['uuid']) return all_projects_ids
def rgb2hex(rgb, max_val=1): """Convert color code from ``rgb`` to ``hex``""" return "#" + "".join([format(int(255 / max_val * e), "02x") for e in rgb]).upper()
def is_smaller(target: int, other: int) -> bool: """ Number is considered smaller if it makes up a bigger number by being concatenated in front This way, such numbers will be on the left """ return str(target) + str(other) > str(other) + str(target)
def _compute_precisions(gold_labels, ranked_lines, threshold): """ Computes Precision at each line_number in the ordered list. """ precisions = [0.0] * threshold threshold = min(threshold, len(ranked_lines)) for i, line_number in enumerate(ranked_lines[:threshold]): if gold_labels[line_number] ...
def solve(input): """Solve the puzzle.""" return int(input/3)-2
def early_stopping(val_bleus, patience=3): """Check if the validation Bleu-4 scores no longer improve for 3 (or a specified number of) consecutive epochs.""" # The number of epochs should be at least patience before checking # for convergence if patience > len(val_bleus): return False l...
def count_variants(rows, only_variant_to_process=True): """Sum variants in the rows provided.""" stay_unchanged = {row['Will stay unchanged'] for row in rows} return sum([ int(row['Number Of Variants (submitted variants)'].replace(',', '')) for row in rows if not only_variant_to_proc...
def dot(v, w): """v_1 * w_1 + ... + v_n * w_n""" return sum(v_i * w_i for v_i, w_i in zip(v, w))
def is_authorized(access_roles, available_roles): """Check if access roles is in available roles""" for role in access_roles: if role in available_roles: return True return False
def _detailed_parse_choice(choice): """Return Selected Choice's Full Name string as per its codename. Choices are based as per our server. :param choice: str The code name of the choice :return: str Return Selected Choice's Full Name string as per its codename """ ...
def validate_ref_component_required(ref_component: int) -> int: """ Validates the reference to a component of an object. :param ref_component: The reference to a component of the object. :return: The validated reference to a component. """ if ref_component <= 0: raise ValueError("Refere...
def subdict(d, expected_dict): """Return a new dict with only the items from `d` whose keys occur in `expected_dict`. """ return {k: v for k, v in d.items() if k in expected_dict}
def _infer_fortran_zones(n_words): """Returns the inverse of n_words = matrix_size * (matrix_size + 1)""" n = int(0.5 + ((1 + 4 * n_words)**0.5)/2) - 1 assert n_words == (n * (n + 1)), "Could not infer a square matrix from file" return n
def compact_name(name): """Remove spaces and other special characthers""" return name.replace(" ","").replace("'","")
def remove_info_last_updated(raw_line): """Used for filter() to ignore time-sensitive lines in summary HTML files. :param raw_line: A line to filter :return: True if no time-sensitive fields are present in the line """ if '<em>Information last updated:' in raw_line: return False return ...
def checkB(board, intX, intY, newX, newY): """Check if the bishop move is legal, returns true if legal""" tmp=False count=1 if abs(intX-newX)==abs(intY-newY): tmp=True if intX<newX and intY<newY:#Checks SE while count<newX-intX: if board[intY-1+count][...
def prefix_match(choices, string, *, key=str): """ Returns the element of `choices` of which `string` is an unambiguous prefix. :param choices: Iterable of strings. :raise ValueError: `string` is a prefix of no `choices` or of more than one. """ matches = { c for c in choices if key...
def _get_opener(filename: str): """Helper to get the opener type based upon the filename.""" import pathlib path = pathlib.Path(filename) if not path.is_file(): raise OSError(f'Filename "{filename}" does not exist.') extension = path.suffix if extension == '.gz': import gzip ...
def srow(string, i): """Get line numer of ``string[i]`` in `string`. :Returns: row, starting at 1 :Note: This works for text-strings with ``\\n`` or ``\\r\\n``. """ return string.count('\n', 0, max(0, i)) + 1
def build_local_context(num_tasks): """ Create local context that you don't intend to be shared with the frontend, but which you may want your remote functions to use """ # NOTE this can be used to establish any kind of shared local context you # might need access to context = {} for x i...
def bisection(l, x): """ Returns the index of the last element smaller than x. """ if len(l) == 0: return 0 else: middle = len(l) // 2 l1 = l[:middle] l2 = l[middle:] if l[middle] >= x: # Element is in the first half return bisection(l1, x) else: ...
def ltrunc(string, width, marker='...'): """Truncates a string from the left to be at most 'width' wide. Args: string: String to truncate. width: Width to make the string at most. May be 0 to not truncate. marker: String to use in place of any truncated text. Returns: Trun...
def _insert_extensions(c): """Insert the ``extensions`` variable into the configuration state.""" c["extensions"] = [ "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.mathjax", "sph...
def reassign_dof_bloch(ndofs, dofs_ima, dofs_ref): """Find dof number after applying boundary conditions Parameters ---------- ndofs : int Number of degrees of freedom. dofs_ima : list, int List with image degrees of freedom. dofs_ref : list, int List with reference degr...
def amr2dict(inst, rel1, rel2): """ Get tables of AMR data indexed by variable number """ node_inds = {} inst_t = {} for (ind, (i, v, label)) in enumerate(inst): node_inds[v] = ind inst_t[ind] = label rel1_t = {} for (label, v1, const) in rel1: if (node_inds[v1], const) not in rel1_t: rel...
def split_role(r): """ Given a string R that may be suffixed with a number, returns a tuple (ROLE, NUM) where ROLE+NUM == R and NUM is the maximal suffix of R consisting only of digits. """ i=len(r) while i>1 and r[i-1].isdigit(): i -= 1 return r[:i],r[i:]
def get_json_attr(obj): """ Returns the serialized version of the object if it has to_json() defined """ if hasattr(obj, "to_json"): return getattr(obj, "to_json")() else: return obj
def hex_to_rgba(hex_str: str, alpha: float): """Converts hex string to rgba """ if "#" in hex_str: hex_str = hex_str.replace("#", "") out = "rgba({0},{1},{2},{alpha})".format( *[int(hex_str[i : i + 2], 16) for i in (0, 2, 4)], alpha=alpha ) return out
def step_function(index, start, init_val, end, final_val): """Approximates the Heaviside step function with a cubic polynomial. Example ------- >>> x = [2, 3, 3.5, 4, 5] >>> start = 3 >>> init_val = 0 >>> end = 3 >>> final_val = 1 >>> step_function(x, start, init_val, end, final...
def isSimpleNumeric(x): """ returns True if x is has type int or float; anything else, False >>> isSimpleNumeric(5) True >>> isSimpleNumeric(3.5) True >>> isSimpleNumeric("5") False >>> isSimpleNumeric([5]) False >>> isSimpleNumeric(6.0221415E23) True >>> """ return ((type(...
def areDisplayOutputsCloned(outputs): """returns True whether more than one display output points at the same framebuffer address :outputs: array :returns: boolean """ for index,output in enumerate(outputs): if index > 0: if output['x'] != outputs[index-1]['x'] or output['y...
def first_half(dayinput): """ first half solver: """ half = len(dayinput) // 2 end = len(dayinput) dayinput = dayinput * 2 i = 0 total = 0 while i < end: next_i = i + half if dayinput[i] == dayinput[next_i]: total += int(dayinput[i]) i += 1 ret...
def remove_empty(seq): """ Removes #None types from sequences @seq: a #list or sequence-like object -> #list """ return [x for x in seq if x is not None]
def parse_schedule(schedule_data): """Simple parse schedule_data. Return list of bus numbers. Bus number represents time between bus departures""" return [int(bus) for bus in schedule_data.split(',') if bus.isdigit()]
def get_calculator_impstr(calculator_name): """ Returns the import string for the calculator """ if calculator_name.lower() == "gpaw" or calculator_name is None: return "from gpaw import GPAW as custom_calculator" elif calculator_name.lower() == "espresso": return "from espresso impo...
def index_dict(d: dict, x: float): """ return a value from d for range x 0-1 the best range""" keys = list(d.keys()) index = int(x * (len(keys) - 1)) return d[keys[index]]
def convert_UCSC_to_bed_format(l): """ Given a locus in UCSC format this function converts it to bed format with 3 fields chr1:121-21111 --> ['chr1', 121, 21111] """ chr=l[:l.find(':')] st=int(l[l.find(':')+1:l.find('-')]) en=int(l[l.find('-')+1:]) return (chr,st,en)
def noiseVariance(SNR, Eb): """ Given an SNR in dB and an energy per bit Eb, calculate the noise variance N0. Note: This calculates Eb / gamma, where gamma is the SNR on a linear scale. """ return Eb / (10 ** (SNR/10))
def game_over(player_decks): """ Determines if either of the player decks are empty and if so, game is over. Parameters: player_decks - Decks for each player Returns: True if either deck is empty, False otherwise """ return_value = Fa...
def post_message_failed_commands(channel, text, thread_ts): """ Test when something failed """ return {"failed": "failed"}
def _is_instance(obj): """is custom class instance""" return hasattr(obj,'__dict__') or hasattr(obj,'__slots__')
def remove_dict_fields(d, fields): """Remove multiple keys from a dictionary. Args: d (dict): The dictionary to clean. fields (list): A list of keys (str) to remove. """ for key in fields: if key in d: del d[key] return d
def extract_subsection(conf: dict, section: str) -> dict: """Takes a nested dictionary and returns the dictionary corresponding to a dot-delimited sub-dict. >>> test_dict = {'foo': {'bar': {1: 42, 2: 55}}, 'baz': "Hello"} >>> extract_subsection(test_dict, "foo.bar") {1: 42, 2: 55} """ for subs...
def gte(this, that): """ >>> gte('1.2.3', None) True >>> gte('1.3.1', [1,3,0]) True >>> gte('1.3', [1,3,0]) True >>> gte('1.3', (1,3,0)) False """ if not that: return True this = list(map(int, this.split('.'))) while len(this) < 3: this.append(0) ...
def dotted_name(names): """Returns a dotted name of a list of strings, integers, lists, and tuples.""" # It will just return the value instead of "b.a.d" if input was "bad"! if isinstance(names, str): return names if isinstance(names, (int, float)): return str(names) resolved = [] for name in name...
def _supports_binary_writing(path): """Whether this path implies a storage system that supports and requires intermediate directories to be created explicitly.""" return not path.startswith("/bigstore")
def camel_to_snake(s: str) -> str: """Converts "CamelCase" to "snake_case".""" return "".join(f"_{c}" if c.isupper() else c for c in s).strip("_").lower()
def constant_time_compare(val1, val2): # taken from Django Source Code """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two str...
def sum_array(arr): """Returns sum of list without highest and lowest vlues""" return 0 if arr is None or arr == [] else sum(sorted(arr)[1:-1])
def check_if_two_hsp_ranges_overlap(lists): """Takes two lists which contain the start and stop positions of two HSPs, and returns True if they overlap. Note: This assumes that the SearchIO coordinates are provided using Python string slicing conventions (this is suggested to be the case here: http...
def build_select(table, to_select, where): """ Build an select request. Parameters ---------- table : str Table where query will be directed. to_set: iterable The list of columns to select. where: iterable The list of conditions to constrain the query. Returns ...
def parser_short_service_name_Descriptor(data,i,length,end): """\ parser_short_service_name_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "short_service_name", "contents" : unparsed_descriptor_conte...
def catch_attribute_error(what, otherwise): """ runs callable 'what' and catches AttributeError, returning 'otherwise' if one occurred :param what: callable :param otherwise: alternate result in case of IndexError :return: result of 'what' or 'otherwise' in case of IndexError """ try: ...
def _earlygetopt(aliases, args): """Return list of values for an option (or aliases). The values are listed in the order they appear in args. The options and values are removed from args. >>> args = ['x', '--cwd', 'foo', 'y'] >>> _earlygetopt(['--cwd'], args), args (['foo'], ['x', 'y']) >...
def isNamedClass(obj, cls): """this is essentially a replacement for isinstance(obj, cls) that looks if an objects class name matches that of a class obj.__class__.__name__ == cls.__name__ """ return obj.__class__.__name__ == cls.__name__
def map_with_obj(f, dct): """ Implementation of Ramda's mapObjIndexed without the final argument. This returns the original key with the mapped value. Use map_key_values to modify the keys too :param f: Called with a key and value :param dct: :return {dict}: Keyed by the original key, va...
def remove_comment(lines: str) -> str: """remove /*...*/ /.../""" state = 0 ret = [] r""" state: 0: normal text [5/3] [secure/_stdio.h] 1: [/] 2: [/*] [/*sth] [/*sth*sth] block comments 3: [/*sth*] 4: [//] [//sth\] inline comments 5: ['] ['\n] ['\t] etc. char 6: ['\] ...
def hyperlinks_bookmarkDict(bookdict): """returns all hyperlinks from bookmarkDict""" itemlist=[] for item in bookdict: if type(bookdict[item])==dict: #recursive foldercontents=hyperlinks_bookmarkDict(bookdict[item]) itemlist.extend(foldercontents) ...
def get_list_id(list_name, alexa_lists): """Find a list id for the corresponding list name. If none is found, return None.""" # type: (str, list) -> Union[str, None] for alexa_list in alexa_lists: if alexa_list.name == list_name: return alexa_list.list_id return None
def mysplit3(s) -> str: """Do a simple split os numbers and letters.""" head = s.rstrip('0123456789') tail = s[len(head):].zfill(2) return head + tail