content
stringlengths
42
6.51k
def unique(elements): """ Returns a list of unique elements from the `elements`. :param elements: the input elements. :type elements: list :return: the list of unique elements :rtype: list """ element_set = set() unique_list = [] for element in elements: if isinstance(element, dict): key = frozenset(element) else: key = element if key in element_set: continue unique_list.append(element) element_set.add(key) return unique_list
def label_given_method_str(method): """Get method labels for bar charts and tables.""" # get label label = '' if method.split('_')[0] == 'True': label += 'adaptive' else: assert method.split('_')[0] == 'False', method label += 'vanilla' if method.split('_')[1] != 'None': label = 'dynamic ' + label return label
def clamp(value: float, minimum: int = 0, maximum: int = 255) -> float: """Clamps `value` between `minimum` and `maximum`.""" return max(minimum, min(value, maximum))
def duplicate_encode(word): """ Apply dict. Time complexity: O(n). Space complexity: O(n). """ from collections import defaultdict # Convert word to lower case. word_lower = word.lower() # Create a dict to accumulate char numbers. char_nums = defaultdict(int) for c in word_lower: char_nums[c] += 1 # Create a duplicate encoder based on char number dict. encoder = [''] * len(word) for i, c in enumerate(word_lower): # There are duplicates in char c. if char_nums[c] > 1: encoder[i] = ')' else: encoder[i] = '(' return ''.join(encoder)
def _check_axis_in_range(axis, ndim): """Checks axes are with the bounds of ndim""" if -ndim <= axis < ndim: return True raise ValueError( f'axis {axis} is out of bounds for array of dimension {ndim}')
def fill_zeros(number): """ Fills zeros before the number to make digits with length of 5 Parameters ---------- number : str digits in string Returns ------- number : str digits in string with length of 5 """ d = 5 - len(number) return '0' * d + number
def getTemperature( U_code, helium_mass_fraction=None, ElectronAbundance=None, mu = None): """U_code = snapdict['InternalEnergy'] INTERNAL ENERGY_code = VELOCITY_code^2 = (params.txt default = (km/s)^2) helium_mass_fraction = snapdict['Metallicity'][:,1] ElectronAbundance= snapdict['ElectronAbundance']""" U_cgs = U_code*1e10 ## to convert from (km/s)^2 -> (cm/s)^2 gamma=5/3. kB=1.38e-16 #erg /K m_proton=1.67e-24 # g if mu is None: ## not provided from chimes, hopefully you sent me helium_mass_fraction and ## electron abundance! try: assert helium_mass_fraction is not None assert ElectronAbundance is not None except AssertionError: raise ValueError( "You need to either provide mu or send helium mass fractions and electron abundances to calculate it!") y_helium = helium_mass_fraction / (4*(1-helium_mass_fraction)) ## is this really Y -> Y/4X mu = (1.0 + 4*y_helium) / (1+y_helium+ElectronAbundance) mean_molecular_weight=mu*m_proton return mean_molecular_weight * (gamma-1) * U_cgs / kB
def get_key(item, key_length): """ key + value = item number of words of key = key_length function returns key """ word = item.strip().split() if key_length == 0: # fix return item elif len(word) == key_length: return item else: return ' '.join(word[0:key_length])
def isfloat(string): """Returns True if string is a float""" try: float(string) except: return False return True
def batch_matmul_legalize(attrs, inputs, types): """Legalizes batch_matmul op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current batch_matmul inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ # not to change by default # pylint: disable=unused-argument return None
def package(x): """ Get the package in which x was first defined, or return None if that cannot be determined. """ return getattr(x, "__package__", None) or getattr(x, "__module__", None)
def easeInOutCubic(currentTime, start, end, totalTime): """ Args: currentTime (float): is the current time (or position) of the tween. start (float): is the beginning value of the property. end (float): is the change between the beginning and destination value of the property. totalTime (float): is the total time of the tween. Returns: float: normalized interpoltion value """ currentTime /= totalTime/2 if currentTime < 1: return end/2*currentTime*currentTime*currentTime + start currentTime -= 2 return end/2*(currentTime*currentTime*currentTime + 2) + start
def is_numeric(value): """ Test if a value is numeric. PARAMETERS ========== value The value whose datatype is to be determined. RETURNS ======= Boolean true if the value is numeric, else boolean false. """ return isinstance(value, int) or isinstance(value, float)
def cvi(b3, b4, b8): """ Chlorophyll Vegetation Index (Hunt et al., 2011). .. math:: CVI = (b8/b3) * (b4/b3) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns CVI: Index value .. Tip:: Hunt, E. R., Daughtry, C. S. T., Eitel, J. U. H., Long, D. S. 2011. \ Remote sensing leaf chlorophyll content using a visible Band index. \ Agronomy Journal 103, 1090-1099. doi:10.2134/agronj2010.0395. """ CVI = (b8/b3) * (b4/b3) return CVI
def _ewc_buffer_names(task_id, param_id, online): """The names of the buffers used to store EWC variables. Args: task_id: ID of task (only used of `online` is False). param_id: Identifier of parameter tensor. online: Whether the online EWC algorithm is used. Returns: (tuple): Tuple containing: - **weight_buffer_name** - **fisher_estimate_buffer_name** """ task_ident = '' if online else '_task_%d' % task_id weight_name = 'ewc_prev{}_weights_{}'.format(task_ident, param_id) fisher_name = 'ewc_fisher_estimate{}_weights_{}'.format(task_ident, param_id) return weight_name, fisher_name
def str_to_hex(value: str) -> str: """Convert a string to a variable-length ASCII hex string.""" return "".join(f"{ord(x):02X}" for x in value) # return value.encode().hex()
def display_mal_list(value): """ Function that either displays the list of malicious domains or hides them depending on the position of the toggle switch. Args: value: Contains the value of the toggle switch. Returns: A dictionary that communicates with the Dash interface whether to display the list of malicious domains or hide them. """ if value is False: return {'display': 'none'} else: return {'display': 'unset'}
def _get_bounds_as_str(bounds): """ returns a string representation of bounds. """ bounds_list = [list(b) for b in bounds] return str(bounds_list)
def _find_clusters(mst_graph, vertices): """Find the cluster class for each vertex of the MST graph. It uses the DFS-like algorithm to find clusters. Args: mst_graph (dict): A non-empty graph representing the MST. vertices (list): A list of unique vertices. Returns: A list containing the group id of each vertex. """ cluster_id = 0 classes = [-1] * len(vertices) unexplored = vertices.copy() while unexplored: start = unexplored.pop() classes[start] = cluster_id explored, stack = set(), [start] while stack: v = stack.pop() if v in explored: continue if v != start: unexplored.remove(v) explored.add(v) classes[v] = cluster_id if v not in mst_graph: continue for adj in mst_graph[v]: if adj in explored: continue stack.append(adj) cluster_id += 1 return classes, cluster_id
def local_name(name): """Return a name with all namespace prefixes stripped.""" return name[name.rindex("::") + 2 :] if "::" in name else name
def largest_sum(int_list): """Return the maximum sum of of all the possible contiguous subarrays. Input is an array of integers. All possible summations of contiguous subarrays are calulated and the maximum is updated whenever a sum is greater than the current maximum. Args: int_list: A list of integers Returns: max_sum: An integer that is the maximum sum found. """ max_sum = float("-inf") for i in range(len(int_list)): for j in range(i + 1, len(int_list) + 1): current_sum = sum(int_list[i:j]) # print(int_list[i:j]) if current_sum > max_sum: max_sum = current_sum return max_sum
def make_price(price): """ Convert an ISK price (float) to a format acceptable by Excel :param price: Float ISK price :return: ISK price as Excel string """ return ('%s' % price).replace('.', ',')
def nii_to_json(nii_fname): """ Replace Nifti extension ('.nii.gz' or '.nii') with '.json' :param nii_fname: :return: json_fname """ if '.nii.gz' in nii_fname: json_fname = nii_fname.replace('.nii.gz', '.json') elif 'nii' in nii_fname: json_fname = nii_fname.replace('.nii', '.json') else: print('* Unknown extension for %s' % nii_fname) json_fname = nii_fname + '.json' return json_fname
def argmax(seq, func): """ Return an element with highest func(seq[i]) score; tie goes to first one. >>> argmax(['one', 'to', 'three'], len) 'three' """ return max(seq, key=func)
def find_min(L, b): """(list, int) -> int Precondition: L[b:] is not empty. Return the index of the smallest value in L[b:]. >>> find_min([3, -1, 7, 5], 0) 1 """ smallest = b i = b + 1 while i != len(L): if L[i] < L[smallest]: smallest = i i = i + 1 return smallest
def py_non_decreasing(L): """test series""" return all(x <= y for x, y in zip(L[:-1], L[1:]))
def sanitize_path(ctx, param, value): """ remove leading/trailing dots on a path if there are any can be modified to do additional sanitizations """ return value.strip('.')
def getProbability(value, distribution, values): """ Gives the probability of a value under a discrete distribution defined by (distributions, values). """ total = 0.0 for prob, val in zip(distribution, values): if val == value: total += prob return total
def getPermutation(perm, numberOfQubits): """ Returns the permutation as a list of tuples. [(logical,physical),(log,phys),...] """ res = [] res.append(("log", "phy")) for i in range(numberOfQubits): res.append((perm[i], i)) return res
def _excess_demand(price, D, S, a, b, gamma, p_bar): """Excess demand function.""" return D(price, a, b) - S(price, gamma, p_bar)
def _try_make_number(value): """Convert a string into an int or float if possible, otherwise do nothing.""" try: return int(value) except ValueError: try: return float(value) except ValueError: return value raise ValueError()
def step(x): """ Unit Step Function x < 0 --> y = 0 y = step(x): x > 0 --> y = 1 :param x: :return: """ if x < 0: return 0 return 1
def Main(a, b, c, d): """ :param a: :param b: :param c: :param d: :return: """ m = 0 if a > b: if c > d: m = 3 else: if b > c: return 8 else: return 10 else: if c > d: m = 1 else: if b < c: return 11 else: m = 22 return m
def _matrix_from_shorthand(shorthand): """Convert from PDF matrix shorthand to full matrix PDF 1.7 spec defines a shorthand for describing the entries of a matrix since the last column is always (0, 0, 1). """ a, b, c, d, e, f = map(float, shorthand) return ((a, b, 0), (c, d, 0), (e, f, 1))
def is_haploid(chromo, is_male): """ Is this chromosome haploid (one allele per person) :param chromo: chromosome letter or number (X, Y, MT or 1-22) :param is_male: boolean if male :return: """ return (chromo == 'X' and is_male) or chromo == 'MT' or chromo == 'Y'
def getBaseEntity(entity): """ Remove extra information from an entity dict keeping only type and id """ if entity is None: return entity return dict([(k, v) for k, v in entity.items() if k in ['id', 'type']])
def check_requirements(program): """ Check if required programs are installed """ # From https://stackoverflow.com/a/34177358 from shutil import which return which(program) is not None
def hexdump(data): """Print string as hexdecimal numbers data: string""" s = "" for x in data: s += "%02X " % ord(x) return s
def convertIDToPublication(db_id, db_name): """ Takes a Solr ID and spits out the publication""" if 'AGW' in db_id: ## AGW-XXX-ENG_YYYYMMDD.NNNN r = db_id.split("_")[1] elif 'NYT' in db_id: r = 'NYT' else: r = db_id.split("_")[0] ## replace - with space r = r.replace('-', ' ') ## add (87-95) to WaPo and USATODAY if 'LN' in db_name: r += " (87-95)" return r
def replace_num(phrase, val): """ Add a numerical value to a string. """ if val == 1: return phrase.replace("(^)", "one") elif val == 2: return phrase.replace("(^)", "two") else: return phrase.replace("(^)", "several")
def load(data): """Load graph and costs of edges from serialized data string""" lines = data.splitlines() graph = {} costs = {} for line in lines: source, dest, cost = map(int, line.split()) if source not in graph: graph[source] = set() if dest not in graph: graph[dest] = set() graph[source].add(dest) graph[dest].add(source) costs[(source, dest)] = cost costs[(dest, source)] = cost return graph, costs
def _xctoolrunner_path(path): """Prefix paths with a token. We prefix paths with a token to indicate that certain arguments are paths, so they can be processed accordingly. This prefix must match the prefix used here: rules_apple/tools/xctoolrunner/xctoolrunner.py Args: path: A string of the path to be prefixed. Returns: A string of the path with the prefix added to the front. """ prefix = "[ABSOLUTE]" return prefix + path
def toggle_navbar_collapse(n, is_open): """ This overall callback on the navigation bar allows to toggle the collapse on small screens. """ if n: return not is_open return is_open
def twos_complement(hexstr,bits): """ twos_complement(hexstr,bits) Converts a hex string of a two's complement number to an integer Args: hexstr (str): The number in hex bits (int): The number of bits in hexstr Returns: int: An integer containing the number """ value = int(hexstr,16) if value & (1 << (bits-1)): value -= 1 << bits return value
def vset(seq,idfun=None,as_list=True): """ order preserving >>> vset([[11,2],1, [10,['9',1]],2, 1, [11,2],[3,3],[10,99],1,[10,['9',1]]],idfun=repr) [[11, 2], 1, [10, ['9', 1]], 2, [3, 3], [10, 99]] """ def _uniq_normal(seq): d_ = {} for s in seq: if s not in d_: d_[s] = None yield s def _uniq_idfun(seq,idfun): d_ = {} for s in seq: h_ = idfun(s) if h_ not in d_: d_[h_] = None yield s if idfun is None: res = _uniq_normal(seq) else: res = _uniq_idfun(seq,idfun) return list(res) if as_list else res
def absolute_min(array): """ Returns absolute min value of a array. :param array: the array. :return: absolute min value >>> absolute_min([1, -2, 5, -8, 7]) 1 >>> absolute_min([1, -2, 3, -4, 5]) 1 """ return min(array, key=abs)
def next_p2(n): """Returns the smallest integer, greater than n (n positive and >= 1) which can be obtained as power of 2. """ if n < 1: raise ValueError("n must be >= 1") v = 2 while v <= n: v = v * 2 return v
def load_file(filename): """Load a file into the editor""" if not filename: return '', 0, 0 with open(filename, 'r') as f: contents = f.read() return contents, len(contents), hash(contents)
def variable_mapping(value, from_low, from_high, to_low, to_high): """ maps a variables values based on old range and new range linearly source: https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio :param value: the desired value to map to the range :param from_low: the previous range low :param from_high: the previous range high :param to_low: the desired range low :param to_high: the desired range high :return: """ new_range = (to_high - to_low) old_range = (from_high - from_low) new_value = (((value - from_low) * new_range) / old_range) + to_low return new_value
def mpe_limits_cont_uncont_mwcm2(mhz: float) -> list: """Determine maximum permissible exposure limits for RF, from FCC references. :param mhz: The radio frequency of interest (megahertz) :return: MPE limits (mW/cm^2) for controlled & uncontrolled environments, respectively :raises ValueError: if mhz is out of range (cannot be found in the FCC lookup table) """ if mhz <= 0: raise ValueError("frequency out of range: %s MHz" % str(mhz)) elif mhz <= 1.34: return [100, 100] elif mhz < 3: return [100, 180 / (mhz ** 2)] elif mhz < 30: return [900 / (mhz ** 2), 180 / (mhz ** 2)] elif mhz < 300: return [1.0, 0.2] elif mhz < 1500: return [mhz / 300, mhz / 1500] elif mhz < 100000: return [5.0, 1.0] else: raise ValueError("frequency out of range: %s MHz" % str(mhz))
def sort_dict(d, reverse=True): """Return the dictionary sorted by value.""" return {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=reverse)}
def repeated_string(string: str, n: int, char: str = "a") -> int: """ >>> repeated_string("aba", 10) 7 >>> repeated_string("a", 1000000000000) 1000000000000 """ string_size = len(string) if string_size == 1: return n if string == char else 0 whole, remainder = divmod(n, string_size) char_count = string.count(char), string[:remainder].count(char) ret = (whole * char_count[0]) + char_count[1] return ret
def solution_1(A): # O(N) """ Write a function to find the 2nd smallest number in a list. >>> solution_1([4, 4, -5, 3, 2, 3, 7, 7, 8, 8]) 2 >>> solution_1([-1, -2, -15, -1, -2, -1, -2]) -2 >>> solution_1([1, 1, 1, 1]) """ min_1 = None # O(1) min_2 = None # O(1) for value in A: # O(N) if not min_1: # O(1) min_1 = value # O(1) elif value < min_1: # O(1) min_1, min_2 = value, min_1 # O(1) elif value > min_1: # O(1) if not min_2 or value < min_2: # O(1) min_2 = value # O(1) return min_2 # O(1)
def parse_data_name(line): """ Parses the name of a data item line, which will be used as an attribute name """ first = line.index("<") + 1 last = line.rindex(">") return line[first:last]
def get_article_info(response: dict): """Create a list of articles containing the: Source name, title, description, url and author :param response: :return: a list of articles """ article_info = [] if response: for article_number in range(response["totalResults"]): source_name = response["articles"][article_number]["source"]["name"] title = response["articles"][article_number]["title"] description = response["articles"][article_number]["description"] url = response["articles"][article_number]["url"] article_info.append([title, description, url, source_name]) return article_info return None
def symmetric_mod(x, m): """ Computes the symmetric modular reduction. :param x: the number to reduce :param m: the modulus :return: x reduced in the interval [-m/2, m/2] """ return int((x + m + m // 2) % m) - int(m // 2)
def unique_labels(list_of_labels): """Extract an ordered integer array of unique labels This implementation ignores any occurrence of NaNs. """ list_of_labels = [idx for idx, labels in enumerate(list_of_labels)] return list_of_labels
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Credit goes to Aaron Hall of stackoverflow: https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def is_empty(dictionary) -> bool: """Determine if the dictionary is empty.""" return not(bool(dictionary))
def claims_match(value, claimspec): """ Implements matching according to section 5.5.1 of http://openid.net/specs/openid-connect-core-1_0.html The lack of value is not checked here. Also the text doesn't prohibit claims specification having both 'value' and 'values'. :param value: single value :param claimspec: None or a dictionary with 'essential', 'value' or 'values' as keys :return: Boolean """ if claimspec is None: # match anything return True matched = False for key, val in claimspec.items(): if key == "value": if value == val: matched = True elif key == "values": if value in val: matched = True elif key == "essential": # Whether it's essential or not doesn't change anything here continue if matched: break # No values to test against so it's just about being there or not if list(claimspec.keys()) == ["essential"]: return True return matched
def maxSubArray2(nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 sums = [] sums.append(nums[0]) mini = maxi = 0 for i in range(1, len(nums)): sums.append(sums[-1] + nums[i]) mini = i if sums[mini] > sums[-1] else mini maxi = i if sums[maxi] < sums[-1] else maxi return max(nums[mini], nums[maxi]) if maxi <= mini else sums[maxi] - sums[mini]
def remove_all(alist,k): """Removes all occurrences of k from alist.""" retval = [] for x in alist: if x != k: retval.append(x) return retval
def get_sentid_from_offset(doc_start_char, doc_end_char, offset2sentid): """ This function gets the sent index given the character offset of an entity in the document Args: doc_start_char: starting character offset of the entity in the document doc_end_char: ending character offset of the entity in the document offset2sentid: a mapping from character offset to sent index in the document """ sentid = None for offset in offset2sentid: if offset[0] <= doc_start_char < doc_end_char <= offset[1]: return offset2sentid[offset] return sentid
def convert_fmask_codes(flags): """Takes a list of arcgis dea aws satellite data fmask flags (e.g., Water, Valid) and converts them into their DEA AWS numeric code equivalent.""" out_flags = [] for flag in flags: if flag == 'NoData': out_flags.append(0) elif flag == 'Valid': out_flags.append(1) elif flag == 'Cloud': out_flags.append(2) elif flag == 'Shadow': out_flags.append(3) elif flag == 'Snow': out_flags.append(4) elif flag == 'Water': out_flags.append(5) return out_flags
def conllify(sentences): """ return string in conll format """ # sentences = resentify(file) conll = [] for sent_id, s in enumerate(sentences, 1): for token_id, tuple in enumerate(s, 1): token = str(tuple[0]) tag = str(tuple[1]) # add tab separated conll row row = '\t'.join([str(token_id), token, tag]) conll += [row] # add empty line between sentences as per conll convention conll += [''] conll = '\n'.join(conll) return conll
def listify(obj): """ Ensure that `obj` is a list. """ return [obj] if not isinstance(obj, list) else obj
def file_to_class_name(f_name: str) -> str: """ Take the file name of a scan and return the name of it as a class: snake to camel case """ return "".join(word.title() for word in f_name.split('_'))
def calc_time(since, until): """ simple function to calculate time passage :param since: the start of the moment :type since: time.struct_time :param until: the end of the moment :type until: time.struct_time :return: the length of the calculated moment in seconds :rtype: int or long """ years = until[0] - since[0] months = until[1] - since[1] days = until[2] - since[2] hours = until[3] - since[3] minutes = until[4] - since[4] seconds = until[5] - since[5] result = seconds + minutes * 60 + hours * 3600 + days * 86400 + months * 2592000 + years * 946080000 return result
def rreplace(word, old_suffix, new_suffix): """Helper for right-replacing suffixes""" return new_suffix.join(word.rsplit(old_suffix, 1))
def truncate(text, max_len=350, end='...'): """Truncate the supplied text for display. Arguments: text (:py:class:`str`): The text to truncate. max_len (:py:class:`int`, optional): The maximum length of the text before truncation (defaults to 350 characters). end (:py:class:`str`, optional): The ending to use to show that the text was truncated (defaults to ``'...'``). Returns: :py:class:`str`: The truncated text. """ if len(text) <= max_len: return text return text[:max_len].rsplit(' ', maxsplit=1)[0] + end
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box): """ Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box """ precision = 0 recall = 0 for feature_employe in features_employed_by_explainer: if feature_employe in features_employed_black_box: precision += 1 for feature_employe in features_employed_black_box: if feature_employe in features_employed_by_explainer: recall += 1 return precision/len(features_employed_by_explainer), recall/len(features_employed_black_box)
def _count_nonempty(row): """ Returns the count of cells in row, ignoring trailing empty cells. """ count = 0 for i, c in enumerate(row): if not c.empty: count = i + 1 return count
def get_complete_loss_dict(list_of_support_loss_dicts, query_loss_dict): """ Merge the dictionaries containing the losses on the support set and on the query set Args: list_of_support_loss_dicts (list): element of index i contains the losses of the model on the support set after i weight updates query_loss_dict (dict): contains the losses of the model on the query set Returns: dict: merged dictionary with modified keys that say whether the loss was from the support or query set """ complete_loss_dict = {} for task_step, support_loss_dict in enumerate(list_of_support_loss_dicts): for key, value in support_loss_dict.items(): complete_loss_dict['support_' + str(key) + '_' + str(task_step)] = value for key, value in query_loss_dict.items(): complete_loss_dict['query_' + str(key)] = value return complete_loss_dict
def isValidPositiveInteger(number): """ Check if number is valid positive integer Parameters ---------- number : int Returns ------- bool Author ------ Prabodh M Date ------ 29 Nov 2017 """ if isinstance(number, int) and number > 0: return True return False
def calc_det_dzb(theta): """Calculate detector vertical offset of the bottom raw .. note:: formula taken from Table 2 on pag. 68 of CE document vol. 3 (Olivier Proux et al.), theta in deg """ return -677.96 + 19.121 * theta - 0.17315 * theta ** 2 + 0.00049335 * theta ** 3
def get_book_url(tool_name, category): """Get the link to the help documentation of the tool. Args: tool_name (str): The name of the tool. category (str): The category of the tool. Returns: str: The URL to help documentation. """ prefix = "https://jblindsay.github.io/wbt_book/available_tools" url = "{}/{}.html#{}".format(prefix, category, tool_name) return url
def conv(x, y): """ Convolution of 2 causal signals, x(t<0) = y(t<0) = 0, using discrete summation. x*y(t) = \int_{u=0}^t x(u) y(t-u) du = y*x(t) where the size of x[], y[], x*y[] are P, Q, N=P+Q-1 respectively. """ P, Q, N = len(x), len(y), len(x)+len(y)-1 z = [] for k in range(N): lower, upper = max(0, k-(Q-1)), min(P-1, k) z.append(sum(x[i] * y[k-i] for i in range(lower, upper+1))) return z
def _parse_cubehelix_args(argstr): """Turn stringified cubehelix params into args/kwargs.""" if argstr.startswith("ch:"): argstr = argstr[3:] if argstr.endswith("_r"): reverse = True argstr = argstr[:-2] else: reverse = False if not argstr: return [], {"reverse": reverse} all_args = argstr.split(",") args = [float(a.strip(" ")) for a in all_args if "=" not in a] kwargs = [a.split("=") for a in all_args if "=" in a] kwargs = {k.strip(" "): float(v.strip(" ")) for k, v in kwargs} kwarg_map = dict( s="start", r="rot", g="gamma", h="hue", l="light", d="dark", # noqa: E741 ) kwargs = {kwarg_map.get(k, k): v for k, v in kwargs.items()} if reverse: kwargs["reverse"] = True return args, kwargs
def is_whiten_dataset(dataset_name: str): """ Returns if the dataset specified has name "whitening". User can use any dataset they want for whitening. """ if dataset_name == "whitening": return True return False
def npf(number): """function which will return the number of prime factors""" i = 2 a = set() while i < number**0.5 or number == 1: if number % i == 0: number = number/i a.add(i) i -= 1 i += 1 return (len(a)+1)
def kernel_primitive_zhao(x, s0=0.08333, theta=0.242): """ Calculates the primitive of the Zhao kernel for given values. :param x: point to evaluate :param s0: initial reaction time :param theta: empirically determined constant :return: primitive evaluated at x """ c0 = 1.0 / s0 / (1 - 1.0 / -theta) if x < 0: return 0 elif x <= s0: return c0 * x else: return c0 * (s0 + (s0 * (1 - (x / s0)**-theta)) / theta)
def computeDerivatives(oldEntry, newEntry): """ Computes first-order derivatives between two corresponding sets of metrics :param oldEntry: Dictionary of metrics at time t - 1 :param newEntry: Dictionary of metrics at time t :return: Dictionary of first-order derivatives """ diff = {k: v - oldEntry[k] for k, v in newEntry.items()} return diff
def UC_Q(Q_mmd, A_catch): """Convert discharge from units of mm/day to m3/day""" Q_m3d = Q_mmd*1000*A_catch return Q_m3d
def get_cam_name(i, min_chars=7): """Create formatted camera name from index.""" format_str = '{:0' + str(min_chars) + 'd}' return 'cam_' + format_str.format(i)
def product(xs): """Multiplies together all the elements of a list""" result = xs[0] for x in xs[1:]: result *= x return result
def cols(matrix): """ Returns the no. of columns of a matrix """ if type(matrix[0]) != list: return 1 return len(matrix[0])
def compare_fuzz(song, best_matches, best_fuzz_ratio, fuzz_value): """ compare_fuzz: A helper function to compare fuzz values then add it to the best_matches array, if needed :param song: The song to potentially add :param best_matches: A list of best matches :param best_fuzz_ratio: The currently best fuzz ratio :param fuzz_value: Fuzz ratio of the song compared to user's query :return: True if the fuzz_ratio was better and needs to be updated False if the fuzz_ratio does not need to be modified """ # If fuzz_value is greater than best_fuzz ratio, set best to fuzz_value and set best_matches to only that song if fuzz_value > best_fuzz_ratio: best_matches.clear() best_matches.append(song) return True # Otherwise, if fuzz and best are equal, add the song to the list elif fuzz_value == best_fuzz_ratio: best_matches.append(song) return False return False
def pdf(kernel, x, min_x, max_x, int_k): """possibility distribution function Returns: p (array-like): probability """ if x < min_x or x > max_x: return 0 else: return kernel(x) / int_k
def fib(n): """Return the n'th fibonacci number""" a, b = 1, 1 while n: a, b = b, a + b n -= 1 return a
def _valid_result(res): """Validate results returned by find_players""" (HEADER, RESULTS) = [0, 1] ok = (isinstance(res, (tuple, list)) and len(res) == 2 and isinstance(res[HEADER], (tuple, list)) and isinstance(res[RESULTS], (tuple, list))) if not ok: return False else: return True
def fac(n): """Returns the factorial of n""" if n < 2: return 1 else: return n * fac(n - 1)
def check_both_lists(final_sj_coordinate_dict,single_exon_reads_transcripts,transcript_coordinate_dict,transiddict,posdict,single_exon_dict): """Check if read is present in both lists. if it is, it is a hidden case of multimapping""" not_single = set() #these reads are not to be outputted as they already have a map position not_multi = set() #these keys are to be ignored as well extra_multimaps = set() #Combined list of all extra multimapped reads for key in final_sj_coordinate_dict.keys(): read = "_".join(key.split("_")[:-1]) if read in single_exon_reads_transcripts.keys(): extra_multimaps.add(read) first_match = posdict[key] second_match = single_exon_dict[read] actual_match = transcript_coordinate_dict[transiddict[read]] if first_match == actual_match: not_single.add(read) elif second_match == actual_match: not_multi.add(key) else: print("This read/key has more than two matches or there is a fatal error!") print(read) return not_single, not_multi, extra_multimaps
def isfunction(obj, func) -> bool: """Checks if the given object has a function with the given name""" if obj is None or not func: return False func_ref = getattr(obj, func, None) return callable(func_ref)
def strhash(string): """ Old python hash function as described in PEP 456, excluding prefix, suffix and mask. :param string: string to hash :return: hash """ if string == "": return 0 x = ord(string[0]) << 7 for c in string[1:]: x = ((1000003 * x) ^ ord(c)) & (1 << 32) x = (x ^ len(string)) return x
def join(items): """ Shortcut to join collection of strings. """ return b''.join(items)
def six_hump_camel_func(x, y): """ Definition of the six-hump camel """ x1 = x x2 = y term1 = (4-2.1*x1**2+(x1**4)/3) * x1**2 term2 = x1*x2 term3 = (-4+4*x2**2) * x2**2 return term1 + term2 + term3
def _random_big_data(bytes=65536, path="/dev/random"): """ Returns a random string with the number of bytes requested. Due to xar implementation details, this should be greater than 4096 (32768 for compressed heap testing). """ with open(path, "r") as f: return f.read(bytes)
def permute(list, index): """ Return index-th permutation of a list. Keyword arguments: list --- the list to be permuted index --- index in range (0, factorial(len(list))) """ if len(list) < 2: return list (rest, choice) = divmod(index, len(list)) return [list[choice]] + permute(list[0:choice] + list[choice + 1:len(list)], rest)
def get_pydantic_error_value(data: dict, loc: tuple): """Get the actual value that caused the error in pydantic""" try: obj = data for item in loc: obj = obj[item] except KeyError: return None else: return obj
def set_objective(x, a, b): """ return the objective function """ #To-Do set the objective equation return a*x+b