content
stringlengths
42
6.51k
def _clamp(low,value,high): """Clamp value to low or high as necessary.""" result = value if value >= low else low result = value if value <= high else high return result
def default(v, d): """Returns d when v is empty (string, list, etc) or false""" if not v: v = d return v
def _version_str(version): """Legacy version string""" return '' if version in (None, 1, '1') else str(version)
def release_string(ecosystem, package, version=None): """Construct a string with ecosystem:package or ecosystem:package:version tuple.""" return "{e}:{p}:{v}".format(e=ecosystem, p=package, v=version)
def str2bool(bool_string: str): """Detects bool type from string""" if not bool_string: return None return bool_string.lower() in ("yes", "true", "1")
def anagram1(S1,S2): """ Checks if the two strings are anagram or not""" S1 = S1.replace(' ', '').lower() S2 = S2.replace(' ', '').lower() if len(S1) != len(S2): return False # Edge case check count = {} for x in S1: if x in count: count[x] += 1 else: ...
def point_interpolation(x_array, fx_array, nStart, nStop, x): """ Interpolation of a single point by the Lagrange method. :param x_array: Array with X coordinates. :param fx_array: Array with Y coordinates. :param nStart: Index of the point at which the interpolation begins :param nStop: Index o...
def strip_charset(content_type): """ Strip charset from the content type string. :param content_type: The Content-Type string (possibly with charset info) :returns: The Content-Type string without the charset information """ return content_type.split(';')[0]
def cards_remaining(card_list): """ this function returns the number of cards that have not been matched yet """ num_remaining = 0 for c in card_list: if c.is_unsolved(): num_remaining += 1 return num_remaining
def annotation_evaluator(input_annotation, evaluation_type): """ The function to evaluate if the annotation type which can be either Class or Property is correct or not""" evaluation = False if evaluation_type == "Class": if "@RdfsClass" in input_annotation: evaluation = True ...
def _partition_(seq1, seq2): """Find a pair of elements in iterables seq1 and seq2 with maximum sum. @param seq1 - iterable with real values @param seq2 - iterable with real values @return pos - such that seq1[pos] + seq2[pos] is maximum """ _sum_ = _max_ = _pos_ = float("-inf") for pos, i...
def compute_mse_decrease(mse_before, mse_after): """Given two mean squared errors, corresponding to the prediction of a target column before and after data augmentation, computes their relative decrease """ return (mse_after - mse_before)/mse_before
def md_table_escape(string): """ Escape markdown special symbols """ to_escape = [ "\\", "`", "*", "_", "{", "}", "[", "]", "(", ")", "#", "|", "+", "-", ".", "!" ] for item in to_escape: string = string.replace(item, f"\\{item}") return string.replace("\n", " ")
def init_aux(face_lines): """initialize animation""" #face_lines = () for k, f in enumerate(face_lines): f.set_data([], []) #line.set_data([], []) #line2.set_data([], []) #line3.set_data([], []) #line4.set_data([], []) #time_text.set_text('') #energy_text.set_te...
def getSoundex(name): """Get the soundex code for the string""" name = name.upper() soundex = "" soundex += name[0] dictionary = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6", "AEIOUHWY":"."} for char in name[1:]: for key in dictionary.keys(): if char in...
def _has_at_least_one_translation(row, prefix, langs): """ Returns true if the given row has at least one translation. >> has_at_least_one_translation( {'default_en': 'Name', 'case_property': 'name'}, 'default', ['en', 'fra'] ) true >> has_at_least_one_translation( {'case_proper...
def to_float_list(a): """ Given an interable, returns a list of its contents converted to floats :param a: interable :return: list of floats """ return [float(i) for i in a]
def sign(x): """Sign function. :return -1 if x < 0, else return 1 """ if x < 0: return -1 else: return 1
def _size_of_dict(dictionary): """ Helper function which returns sum of all used keys and items in the value lists of a dictionary """ size = len(dictionary.keys()) for value in dictionary.values(): size += len(value) return size
def get_fuel_needed(mass: int) -> int: """Calculate fuel needed to launch mass.""" return mass // 3 - 2
def obs_likelihood(obs, freq): """Bernoulli probability of observing binary presence / absence given circulating frequency""" """obs is 0 or 1 binary indicator for absence / presence""" return (1-freq)**(1-obs) * freq**obs
def _to_timestamp_float(timestamp): """Convert timestamp to a pure floating point value None is encoded as inf """ if timestamp is None: return float('inf') else: return float(timestamp)
def is_dlang(syntax): """Returns whether the given syntax corresponds to a D source file""" return syntax == 'Packages/D/D.sublime-syntax'
def signExp(expression, sign): """ Opens the brackets, depending upon the Sign """ arr = list(expression) if sign == "-": for i in range(len(expression)): # Invert the sign if the 'sign' is '-' if arr[i] == "+": arr[i] = "-" elif arr[i] == ...
def percent(numerator, denominator): """Return (numerator/denominator)*100% in string :param numerator: :param denominator: :return: string """ # Notice the / operator is from future as real division, aka same as Py3, return '{}%'.format(numerator * 100 / denominator)
def welcome_text(title="WRF"): """Customizar a Janela de Logon e o Titulo do Dialogo de Seguranca DESCRIPTION Este ajuste permite adicionar textos no titulo da janela de logon padrao e na caixa de dialogo de seguranca do Windows. COMPATIBILITY Windows NT/2000/XP ...
def parse_slice(ds_slice): """ Parse dataset slice Parameters ---------- ds_slice : tuple | int | slice | list Slice to extract from dataset Returns ------- ds_slice : tuple slice for axis (0, 1) """ if not isinstance(ds_slice, tuple): ds_slice = (ds_sli...
def _ve_lt_ ( self , other ) : """Comparison of ValueWithError object with other objects >>> a = VE( ... ) >>> print a < b Attention: comparison by value only! """ return float(self) < float(other)
def fmt_percent(x, total): """ Compute percent as x/total, format for a table cell. """ if total == 0: percent = 0 else: percent = float(x) / total * 100 return str(round(percent, 2)) + '%'
def soft_hash_audio_v0(cv): # type: (Iterable[int]) -> bytes """ Create 256-bit audio similarity hash from a chromaprint vector. :param Iterable[int] cv: Chromaprint vector :return: 256-bit Audio-Hash digest :rtype: bytes """ # Convert chrompaprint vector into list of 4 byte digests ...
def persistence(n): """takes in a positive n and returns the multiplicative persistence""" count = 0 if len(str(n)) == 0: return 0 while len(str(n))> 1: p = 1 for i in str(n): p *= int(i) n, count = p, count + 1 return count
def _prep_behavior(dataset, lag, make_params): """Helper function that makes separate make_params for behavioral data Parameters ---------- dataset : NWBDataset NWBDataset that the make_params are made for lag : int Amount that behavioral data is lagged relative to tria...
def mode(data): """Returns the mode of a unimodal distribution. >>> mode([1,2,3,4,4,4,4]) 4 >>> mode([-10,-10,-10,13,42,256]) -10 >>> mode(['a', 'a', 'b', 'b', 'c', 'c', 'a']) 'a' """ frequencies = {} maximum = 0 mode = None for x in data: try: frequ...
def square_of_sum_minus_sum_of_square(N): """ This function computes, for a given integer N, the difference beetwen the square of the sum and the sum of squares (sum of integer beetwen 1 and N). """ carre_somme = 0 somme_carre = 0 for i in range(1,N+1): somme_carre += i**2 carre_somme += i carre_somme = car...
def fibonacci(n_terms) -> int: """Method that prints the fibonacci sequence until the n-th number""" if n_terms <= 1: return n_terms return (fibonacci(n_terms - 1) + fibonacci(n_terms - 2))
def cardLuhnChecksumIsValid(card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits): digit = int(card_number[count]) if not (( count & 1 ) ^ oddeven ): ...
def _global_unique_search_i(lines): """Remove repeated lines so that the entire file is unique, ignoring whitespace. Returns the unique lines. lines: the lines of the file to deduplicate """ unique_lines = [] _idx = {} for line in lines: try: _idx[line.strip()] ...
def encode_tag(tag, data_type, data): """ Write a SAM tag in the format ``TAG:TYPE:data`` >>> encode_tag('YM', 'Z', '#""9O"1@!J') 'YM:Z:#""9O"1@!J' """ value = ':'.join(list((tag.upper(), data_type.upper(), data))) return value
def ordered_unique_list(in_list): """List unique elements in input list, in order of first occurrence""" out_list = [] for i in in_list: if i not in out_list: out_list.append(i) return out_list
def splitOneListIntoTwo(inputList): """ Function that takes a list, each of whose entries is a list containing two entries, and assembles two separate lists, one for each of these entries """ list1 = [] list2 = [] for entry in inputList: list1.append(entry[0]) list2.appen...
def make_tb_trie(tb_str_list): """ https://stackoverflow.com/a/11016430/2668831 """ root = dict() _end = None for tb in tb_str_list: current_dict = root for key in tb: current_dict = current_dict.setdefault(key, {}) current_dict[_end] = _end return root
def data(object_type: str, subscriber: str) -> str: """Return the db key for subscriber event data. Args: object_type (str): Type of object subscriber (str): Name of the subscriber Returns: str, database key for the event data """ return 'events:{}:{}:data'.format(object...
def decode(to_be_decoded): """ Decodes a run-length encoded string. :param to_be_decoded: run-length encoded string :return: run-length decoded string """ to_be_decoded_list = list(to_be_decoded) decoded_str_as_list = list() num_to_print_as_list = list() for c in to_be_decoded_list:...
def xlate(vname): """Translate""" if vname in ["ws_10m_nw", "ws_40m_nw", "ws_120m_nw"]: return vname + "ht" return vname
def output_passes_filter(data, filter_from, filter_to): """ Check if the data passes the given filter. :param data: The data tuple to check. :param filter_to: Filter to only values starting from this value... :param filter_from: ...Filter to only values ending with this value. :return: True if t...
def _string_to_numeric(choices, val): """Takes a choices tuple and a string and returns the numeric representation as defined in this module . """ for choice in choices: if choice[1] == val: return choice[0] return None
def has_upper_letters(password): """Return True if password has at least one upper letter.""" return any(char.isupper() for char in password)
def _apply_args_and_kwargs(function, args, kwargs): """Apply a tuple of args and a dictionary of kwargs to a function Parameters ---------- function: func function you wish to use args: tuple all args passed to function kwargs: dict all kwargs passed to function """ ...
def consensus12( o_s_aligned, o_p_aligned, t_s_aligned, t_p_aligned, dict_stats1, dict_stats2 ): """ From the aligned strings and probabilities of two results, it generates a consensus result, which can include some undecided characters.""" if len(o_s_aligned) == 0 or len(t_s_aligned) == 0 or len(o_s_aligned) != le...
def parse_str(arg, reverse=False): """Pass in string for forward, string for reverse.""" if reverse: return '%s' % arg else: return str(arg)
def bytes_to_encode_dict(dict_bytes): """Exracts the encode dict when it has been encoded to a file. dict_dict contains the bytes string that is between 'DICT_START' and 'DICT_END' in the file.""" ret = dict() d = dict_bytes.decode("utf-8") pairs = d.split(",") for pair in pairs: key...
def hkey(key): """ >>> hkey('content_type') 'Content-Type' """ if '\n' in key or '\r' in key or '\0' in key: raise ValueError( "Header name must not contain control characters: %r" % key) return key.title().replace('_', '-')
def _calc_instability(ca, ce): """Returns the instability ratio between ca and ce.""" if ca or ce: caf, cef = float(ca), float(ce) instab = cef / (cef + caf) else: instab = 0 return instab
def dict_string(dictionary, ident = '', braces=1): """ Recursively prints nested dictionaries.""" text = [] for key in sorted(dictionary.keys()): value = dictionary[key] if isinstance(value, dict): text.append('%s%s%s%s' %(ident,braces*'[',key,braces*']')) text.append...
def compare_elements(prev_hash_dict, current_hash_dict): """Compare elements that have changed between prev_hash_dict and current_hash_dict. Check if any elements have been added, removed or modified. """ changed = {} for key in prev_hash_dict: elem = current_hash_dict.get(key, '') ...
def ago_msg(hrs): """ Returns a string with "N hours ago" or "N days ago", depending how many hours """ days = int(hrs / 24.0) minutes = int(hrs * 60) hrs = int(hrs) if minutes < 60: return "{} minutes ago".format(minutes) if hrs == 1: return "1 hour ago" if hrs < 24: ...
def mean(values): """returns mean of a list of values :param values: list of values to be evaluated :returns: float: mean of values """ if not values: return 0 return float(sum(values)) / len(values)
def get_occurences(node, root): """ Count occurences of root in node. """ count = 0 for c in node: if c == root: count += 1 return count
def replace(text, replacements): """ Replaces multiple slices of text with new values. This is a convenience method for making code modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is an iterable of ``(start, end, new_text)`` tuples. For example, ``replace("thi...
def addslashes(value): """ Adds slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
def str_list(data_in, mode=0): """ mode 0: splits an ascii string and adds elements to a list. mode 1: converts list elements to ascii characters and joins them. """ if mode == 0: data_out = [] for i in range(len(data_in)): data_out.append(ord(data_in[i])) # chr and ord ...
def load_exemplars(exemplar_pre: dict) -> list: """ Load exemplar in previous cycle. Args: exemplar_pre (dict): Exemplars from previous cycle in the form of {item_id: [session, session,...], ...} Returns: exemplars (list): Exemplars list in the form of [session, session] ...
def is_gif(data): """True if data is the first 4 bytes of a GIF file.""" return data[:4] == 'GIF8'
def get_padding_elem_transposed( L_out: int, L_in: int, stride: int, kernel_size: int, dilation: int, output_padding: int, ): """This function computes the required padding size for transposed convolution Arguments --------- L_out : int L_in : int stride: int kernel_...
def check_type(line): """Check if the line has a url or song name.""" if 'http' in line: return 'url' else: return 'name'
def find_prob(lhs, rhs, rules): """ This function returns the probability of the rule given it's lhs and rhs """ for rule in rules: if len(rule[1])==1 and rule[0]==lhs and rhs==rule[1][0]: return rule[2] return 0
def opt_in_argv_tail(argv_tail, concise, mnemonic): """Say if an optional argument is plainly present""" # Give me a concise "-" dash opt, or a "--" double-dash opt, or both assert concise or mnemonic if concise: assert concise.startswith("-") and not concise.startswith("--") if mnemonic: ...
def list_to_list_two_tuples(values: list): """ Convert a list of values to a list of tuples with for each value twice that same value e.g. [1,2,3] ==> [(1,1),(2,2),(3,3)] Parameters ---------- values : list list of values to convert into tuples Returns ------- list ...
def get_license_refs_dict(license_refs_list): """In SPDX, if the license strings extracted from package metadata is not a license expression it will be listed separately. Given such a list, return a dictionary containing license ref to extracted text""" license_ref_dict = {} if license_refs_list: ...
def two_fer(name): """Return message about sharing. Time and space complexity are both O(1). """ if name is None: name = "you" return f"One for {name}, one for me."
def parse_help(help_str): """ Auto parses the help dialogs provided by developers in the doc strings. This is denoted by helpme - text and then a blank line. e.g. Function doc string helpme - more end user friendly message about what this will do my arguments... """ result = None...
def low_density_generator(block_size): """ This function makes array of low density strings of size block_size """ resp = [bin(0)[2:].zfill(block_size)] for i in range(block_size): if(i>0): for j in range(i): resp.append(bin(1<<i|1<<j)[2:].zfill(block_size)) ...
def is_winner(board): """ Check if the board is a winner (e.g. 1 row or 1 column is full of 0) :param board: :return: True if the board is a winner, False otherwise """ for _, row in enumerate(board): result_sum = 0 for _, val in enumerate(row): result_sum += val ...
def _defaultHeaders(token): """Default headers for GET or POST requests. :param token: token string.""" return {'Accept': '*/*', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token}
def dependants_to_dependencies(graph): """Inverts a dependant's graph to yield a dependency graph. Notes ----- The graph must be directed and acyclic. Parameters ---------- graph: dict(str, list(str)) The graph to invert. Each key in the dictionary represents a node in the graph, a...
def jsEscapeString(s): """ Escape s for use as a Javascript String """ return s.replace('\\','\\\\') \ .replace('\r', '\\r') \ .replace('\n', '\\n') \ .replace('"', '\\"') \ .replace("'", "\\'") \ .replace("&", '\\x26') \ .replace("<", '\\x3C') \ .replace(...
def pad(items, maxlen, paditem=0, paddir='left'): """ Parameters: ----------- items: iterable, an iterable of objects to index maxlen: int, length to which input will be padded paditem: any, element to use for padding paddir: ('left', 'right'), where to add the padding """ n_items = ...
def has_author_view(descriptor): """ Returns True if the xmodule linked to the descriptor supports "author_view". """ return getattr(descriptor, 'has_author_view', False)
def parse_checkpoint(ckpt): """ Parses checkpoint string to get iteration """ assert type(ckpt) == str, ckpt try: i = int(ckpt.split('_')[-1].split('.')[0]) except: print('unknown checkpoint string format %s setting iteration to 0' % ckpt) i = 0 return i
def find_double_newline(s): """Returns the position just after a double newline in the given string.""" pos = s.find(b"\r\n\r\n") if pos >= 0: pos += 4 return pos
def clean_page_path(page_path, sep='#'): """ We want to remove double slashes and replace them with single slashes, and we only want the page_path before a # :param page_path: :param sep: default '#' that we want to get rid of, we use rsplit to take away the right-most part of the string :return: a ...
def json_api_headers(token): """Return standard headers for talking to the metadata service""" return { "Authorization": "Bearer {}".format(token), "Accept": "application/vnd.api+json", "Content-Type": "application/vnd.api+json" }
def data_by_tech(datalines, tech): """ This function takes in a list of datalines and returns a new list of datalines for a specified tech. Parameters: ----------- datalines : list This is a list of datalines output by Temoa. tech : string This is the tech of interest. Curre...
def parse_subcommand(command_text): """ Parse the subcommand from the given COMMAND_TEXT, which is everything that follows `/pickem`. The subcommand is the option passed to the command, e.g. 'pick' in the case of `/pickem pick`. """ return command_text.strip().split()[0].lower()
def compute_agreement_score(arcs1, arcs2, method, average): """Agreement score between two dependency structures Parameters ---------- arcs1: list[(int, int, str)] arcs2: list[(int, int, str)] method: str average: bool Returns ------- float """ assert len(arcs1) == len(...
def has_message_body(status): """ According to the following RFC message body and length SHOULD NOT be included in responses status 1XX, 204 and 304. https://tools.ietf.org/html/rfc2616#section-4.4 https://tools.ietf.org/html/rfc2616#section-4.3 """ return status not in (204, 304) and not (1...
def naive(t: str, w: str) -> list: """ Naive method for string searching. :param t: text to search the word in. :param w: word to be searched. :return: list of start indexes. """ n = len(t) m = len(w) indexes = [] d = 0 i = 0 while d < n - m: if i == m: # If a ...
def doreverse_list(decs, incs): """ calculates the antipode of list of directions """ incs_flipped = [-i for i in incs] decs_flipped = [(dec + 180.) % 360. for dec in decs] return decs_flipped, incs_flipped
def strtype(val): """ :param val: :return: bool """ return isinstance(val, str)
def Matthew_Correlation_Coefficient(TP, TN, FP, FN): """ A correlation coefficient between the observed and predicted classifications Least influenced by imbalanced data. Range: -1 ~ 1 1 = perfect prediction 0 = andom prediction -1 = worst possible prediction. """ num = (TP*TN)-(FP*F...
def convert_date(date_str): """ Convert a date_str in the format 'DD.MM.YYYY' into mysql format 'YYYY-MM-DD'. """ date_li = date_str.split('.') return '-'.join(reversed(date_li))
def filter1(dataList, sigma=5): """ to filter a list of images with the gaussian filter input: list of data = image slides sigma - parameter output: list of filtered data """ return 0 ################################################################################ # ...
def insertion_sort(collection): """Pure implementation of the insertion sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> insertion_sort([0, 5, 3, 2, 2]) [0, 2...
def escape_curly_brackets(url_path): """ Double brackets in regex of url_path for escape string formatting """ return url_path.replace('{', '{{').replace('}', '}}')
def fluence_x_ray_calc(f): """ Return calculated value of FRB's X-ray counterpart fluence, for giant flares occurring within the range of FRB distances. Args: - f: Radio frequency fluence Returns: F FRB X-ray counterpart fluence value in erg/cm^2 """ fluence_x = (f/(2e-5)) return fluence_x
def update_logger(image, model_used, pred_class, pred_conf, correct=False, user_label=None): """ Function for tracking feedback given in app, updates and reutrns logger dictionary. """ logger = { "image": image, "model_used": model_used, "pred_class": pred_class, "pr...
def increment_duplicates(arr): """Increments duplicates in an array until there are no duplicates. Uses a hash set to keep track of which values have been seen in the array. Runs in O(n^2) time worst case (e.g. all elements are equal), O(n) time best case (elements are already unique). """ seen...
def _relative_error(expected_min, expected_max, actual): """ helper method to calculate the relative error """ if expected_min < 0 or expected_max < 0 or actual < 0: raise Exception() if (expected_min <= actual) and (actual <= expected_max): return 0.0 if expected_min == 0 and expected_m...
def generate_span_tag(description: str) -> str: """ Fungsi yang menerima input berupa string dan kemudian mengembalikan string yang berisi tag span dengan class 'active' dan isi yang sama dengan input. Contoh: >>> generate_span_tag("") '<span class="active">HOME</span>' >>> generate_spa...
def icon_url(path, pk, size): """ Explination: https://image.eveonline.com/ """ if path == "Character": filetype = "jpg" else: filetype = "png" return "http://image.eveonline.com/%s/%d_%d.%s" % \ (path, pk, size, filetype)