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: count[x] = 1 for x in S2: if x in count: count[x] -= 1 else: count[x] = 1 for i in count: if count[i] !=0: return False return True
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 of the point at which the interpolation ends :param x: X coordinate for interpolation :return: Y coordinate - the result of the interpolation """ number_type = type(x_array[0]) if x_array else type(fx_array[0]) if fx_array else type(x) ntResult = number_type(0) for i in range(nStart, nStop): ntProduct = fx_array[i] for j in range(nStart, i): ntProduct *= (x - x_array[j]) / (x_array[i] - x_array[j]) for j in range(i + 1, nStop): ntProduct *= (x - x_array[j]) / (x_array[i] - x_array[j]) ntResult += ntProduct return ntResult
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 else: evaluation = False elif evaluation_type == "Property": if "@RdfProperty" in input_annotation: evaluation = True else: evaluation = False return evaluation
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, ij in enumerate(zip(seq1, seq2)): _sum_ = sum(ij) if _sum_ > _max_: _max_ = _sum_ _pos_ = pos return _pos_
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_text('') #beta_text.set_text('') return face_lines
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 key: code = dictionary[key] if code != soundex[-1]: soundex += code soundex = soundex.replace(".", "") soundex = soundex[:4].ljust(4, "0") return soundex
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_property': 'name'}, 'default', ['en', 'fra'] ) false :param row: :param prefix: :param langs: :return: """ return any(row.get(prefix + '_' + l) for l in langs)
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] == "-": arr[i] = "+" # If the first characters is not a sign, it is a '+' and we need to # add it to the subexpression if arr[0] != "+" and arr[0] != "-": arr.insert(0, sign) return "".join(x for x in arr)
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 MODIFIED VALUES Welcome : string : Texto a ser adicionado. """ return '''[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\\ CurrentVersion\\Winlogon] "Welcome"="%s"''' % title
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_slice,) return ds_slice
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 digests = [int_feature.to_bytes(4, "big", signed=True) for int_feature in cv] # Return identity hash if we have 0 digests if not digests: return b"\x00" * 32 # Calculate simhash of digests as first 32-bit chunk of the hash parts = [ic.similarity_hash(digests)] # Calculate separate 32-bit simhashes for each quarter of features (original order) for bucket in divide(4, digests): features = list(bucket) if features: parts.append(ic.similarity_hash(features)) else: parts.append(b"\x00\x00\x00\x00") # Calculate separate simhashes for each third of features (ordered by int value) cvs = sorted(cv) digests = [int_feature.to_bytes(4, "big", signed=True) for int_feature in cvs] for bucket in divide(3, digests): features = list(bucket) if features: parts.append(ic.similarity_hash(features)) else: parts.append(b"\x00\x00\x00\x00") return b"".join(parts)
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 trial alignment in `make_params` make_params : dict Arguments for `NWBDataset.make_trial_data` to extract trialized data Returns ------- dict Arguments for `NWBDataset.make_trial_data` to extract trialized behavior data """ behavior_make_params = make_params.copy() if lag is not None: behavior_make_params['allow_nans'] = True if 'align_range' in behavior_make_params: behavior_make_params['align_range'] = tuple([(t + lag) for t in make_params['align_range']]) else: behavior_make_params['align_range'] = (lag, lag) else: behavior_make_params = None return behavior_make_params
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: frequencies[x] += 1 except KeyError: frequencies[x] = 1 if frequencies[x] > maximum: mode = x maximum = frequencies[x] return mode
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 = carre_somme**2 return carre_somme - somme_carre
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 ): digit = digit * 2 if digit > 9: digit = digit - 9 sum = sum + digit return ( (sum % 10) == 0 )
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()] except KeyError: _idx[line.strip()] = True unique_lines.append(line) return unique_lines
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.append(entry[1]) return list1, list2
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_type, subscriber)
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: if c.isdigit(): num_to_print_as_list.append(c) else: if len(num_to_print_as_list) > 0: num_to_print = int(''.join(num_to_print_as_list)) append = c * num_to_print decoded_str_as_list.append(append) num_to_print_as_list = list() else: decoded_str_as_list.append(c) return ''.join(decoded_str_as_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 the data passes the filter, False otherwise. """ if filter_from is None or filter_to is None: return True return data[1] == filter_from and data[2] == filter_to
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 """ return function(*args, **kwargs)
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) != len(t_s_aligned): return [], [] s12 = [] p12 = [] i = 0 while i<len(o_s_aligned): if o_s_aligned[i] == t_s_aligned[i]: # Consensus reach if o_p_aligned[i] > 1.0 and t_p_aligned[i] > 1.0: # Both in n-grams s12.append( o_s_aligned[i] ) p12.append( 10.0 ) elif o_p_aligned[i] > 1.0 or t_p_aligned[i] > 1.0: # Only one in n-gram s12.append( o_s_aligned[i] ) p12.append( 5.0 ) else: # The character was not recognized in any n-gram (Some risk) # w_c, w_p = getHigherProb( o_s_aligned[i], o_p_aligned[i], t_s_aligned[i], t_p_aligned[i], dict_stats1, dict_stats2 ) s12.append( [t_s_aligned[i], o_s_aligned[i]] ) p12.append( [t_p_aligned[i], o_p_aligned[i]] ) else: # We prefer the Tesseract's output because generates less garbage s12.append( [t_s_aligned[i], o_s_aligned[i]] ) p12.append( [t_p_aligned[i], o_p_aligned[i]] ) i = i + 1 return s12, p12
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, value = pair.strip().split(": ") ret[int(key)] = value.replace("'", "") return ret
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('\n') text.append(dict_string(value, ident+' ', braces+1)) else: if isinstance(value, set) or isinstance(value, frozenset): value = sorted(value) text.append(ident+'%s = %s' %(key, value)) text.append('\n') return ''.join(text)
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, '') if elem == '': changed[key] = 'deleted' elif elem != prev_hash_dict[key]: changed[key] = 'changed' for key in current_hash_dict: elem = prev_hash_dict.get(key, '') if elem == '': changed[key] = 'added' return changed
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: return "{} hours ago".format(hrs) if days == 1: return "1 day ago" return "{} days ago".format(days)
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("this is a test", [(0, 4, "X"), (8, 9, "THE")])`` produces ``"X is THE test"``. """ p = 0 parts = [] for (start, end, new_text) in sorted(replacements): parts.append(text[p:start]) parts.append(new_text) p = end parts.append(text[p:]) return "".join(parts)
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 functions for ascii conversions return data_out data_out = '' for i in range(16): data_out += chr(data_in[i]) return data_out
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] """ exemplars = [] for item in exemplar_pre.values(): if isinstance(item, list): exemplars.extend([i for i in item if i]) return exemplars
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_size : int dilation : int output_padding : int """ padding = -0.5 * ( L_out - (L_in - 1) * stride - dilation * (kernel_size - 1) - output_padding - 1 ) return int(padding)
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: assert mnemonic.startswith("--") and not mnemonic.startswith("---") # Detect the plain use of the concise or mnemonic opts # Drop the ambiguities silently, like see "-xh" always as "-x '-h'" never as "-x -h" for arg in argv_tail: if mnemonic.startswith(arg) and (arg > "--"): return True if arg.startswith(concise) and not arg.startswith("--"): return True return False
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 list of tuples with twice the same value for each tuple """ return [(val, val) for val in values]
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: for ref_dict in license_refs_list: license_ref_dict[ref_dict['licenseId']] = ref_dict['extractedText'] return license_ref_dict
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 if help_str is not None: if 'helpme' in help_str: z = help_str.split('helpme') result = z[-1].split('-')[-1].strip() return result
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)) else: for k in range(block_size): resp.append(bin(1<<k)[2:].zfill(block_size)) # print('-----cycle: %s-----'%(i)) return resp
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 if result_sum == 0: return True for j in range(len(board[0])): result_sum = 0 for i in range(len(board)): result_sum += board[i][j] if result_sum == 0: return True return False
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, and each string in the value list represents a node which depends on the node defined by the key. Returns ------- dict(str, list(str)) The inverted graph. Each key in the dictionary represents a node in the graph, and each string in the value list represents a node which the node defined by the key depends on. """ dependencies = {} for node in graph: if node not in dependencies: dependencies[node] = [] for dependant in graph[node]: if dependant not in dependencies: dependencies[dependant] = [] if node not in dependencies[dependant]: dependencies[dependant].append(node) return dependencies
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(">", '\\x3E') # Note: non-ascii unicode characters do not need to be encoded # Note: previously we encode < as &lt;, etc. However IE6 fail to treat <script> block as CDATA.
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 = len(items) if n_items == maxlen: return items if paddir == 'left': return (maxlen - n_items) * [paditem] + items if paddir == 'right': return items + (maxlen - n_items) * [paditem] else: raise ValueError("Unknown pad direction [%s]" % str(paddir))
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 nice clean page_path, more hope of matching to our content ID mapping """ return page_path.replace('//', '/').rsplit(sep, 1)[0]
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. Currently only interested in V_ActivityByPeriodAndProcess, V_Capacity, and V_EmissionsByPeriodAndProcess Returns: -------- datatech : list This is a list of datalines that only contains data for a particular tech. """ datatech = [] for line in datalines: # print(line) if tech in line: datatech.append(line) return datatech
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(arcs2) if method == "joint": shared_arcs = set(arcs1) & set(arcs2) score = float(len(shared_arcs)) elif method == "independent": score = 0.0 dep2head1 = {d: (h, r) for h, d, r in arcs1} dep2head2 = {d: (h, r) for h, d, r in arcs2} for dep in dep2head1.keys(): head1, rel1 = dep2head1[dep] head2, rel2 = dep2head2[dep] if head1 == head2: score += 0.5 if rel1 == rel2: score += 0.5 else: raise Exception("Never occur.") if average: score = float(score) / len(arcs1) return score
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 (100 <= status < 200)
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 match is found. indexes.append(d) i = 0 d += 1 if t[d + i] == w[i]: i += 1 else: i = 0 d += 1 return indexes
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*FN) denom = ((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))**0.5 if denom != 0: MCC = num / denom else: MCC = None return MCC
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 ################################################################################ # 2. matching """ to match a list of (NWP) images with a template (RADAR) image returning a list of scores for each """ ################################################################################ # 3. selection of models """ based on the matching (or matchings) select the top 8 models """ ################################################################################ # 4. data fusion """ based on the results of matching and selection, perform data fusion """ ################################################################################ # 5. forecasting """ based on the results of fusion and selection of models, make a forecast """ ################################################################################ # 6. monitoring and evaluation """ to evaluate the forecast idea: 1. check the resemblence of the forecast to actual data (if available) 2. if 1 is not available, use human judgement """
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, 2, 3, 5] >>> insertion_sort([]) [] >>> insertion_sort([-2, -5, -45]) [-45, -5, -2] """ for index in range(1, len(collection)): while 0 < index and collection[index] < collection[index - 1]: collection[index], collection[ index - 1] = collection[index - 1], collection[index] index -= 1 return collection
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, "pred_conf": pred_conf, "correct": correct, "user_label": user_label } return logger
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 = set() for i in range(len(arr)): while arr[i] in seen: arr[i] += 1 seen.add(arr[i]) return arr
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_max == 0: return 0.0 if actual == 0 else float("+inf") if actual < expected_min: return (expected_min - actual) / expected_min return (actual - expected_max) / expected_max
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_span_tag("ABOUT") '<span class="active">ABOUT</span>' >>> generate_span_tag("CONTACT US") '<span class="active">CONTACT US</span>' >>> generate_span_tag("SSYPS") '<span class="active">SSYPS</span>' """ if description == "": description = "HOME" return f'<span class="active">{description}</span>'
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)