content
stringlengths
42
6.51k
def migrateattributes(source, target, attributes): """ Function to migrate attributes from one instance (source) of a class to another (target). This function does no checks, so please don't act like 10 year olds with chainsaws. :type source: object :param source: Source object :type target: object :param target: Target object :type attributes: list of str or tuple of str :param attributes: List/tuple of attribute names. """ for attribute in attributes: target.__setattr__(attribute, source.__getattribute__(attribute)) return target
def riemann_sum(f, a, b, h): """Computes the integral of f in [a, b] with step size h.""" assert h > 0, 'Step size must be a positive number!' s = 0 x = a + h / 2 while x < b: s += h * f(x) x += h return s
def format_seconds(time_seconds): """Formats some number of seconds into a string of format d days, x hours, y minutes, z seconds""" seconds = time_seconds hours = 0 minutes = 0 days = 0 while seconds >= 60: if seconds >= 60 * 60 * 24: seconds -= 60 * 60 * 24 days += 1 elif seconds >= 60 * 60: seconds -= 60 * 60 hours += 1 elif seconds >= 60: seconds -= 60 minutes += 1 return f"{days}d {hours}h {minutes}m {seconds}s"
def prox_sum_squares_base(v, t): """Proximal operator of :math:`f(x) = \\sum_i x_i^2`. """ return v / (1.0 + 2*t)
def compute_auto_estimator(transform): """ The default method for estimating the parameters of a parameterized probability trajectory (i.e., this is not the method used for the model selection, only the method used to estimate the amplitudes in the parameterized model). This returns the fastest method that is pretty reliable for that transform, rather than the most statistically well-motivated choice (which is mle in all cases). Parameters ---------- transform : str The type of transform that we are auto-selecting an estimation method for. Returns ------- str The name of the estimator to use. """ if transform == 'dct': auto_estimator = 'filter' elif transform == 'lsp': auto_estimator = 'mle' else: raise ValueError("No auto estimation method available for {} transform!".format(transform)) return auto_estimator
def isdigit(str: str) -> bool: """ Same as `str.isdigit()` except it supports negative numbers (x < 0) """ return str.isdigit() or (str.startswith('-') and str[1:].isdigit())
def dict_updates(old, new): """ This function reports updates to a dict. :param old: A dictionary to compare against. :param new: A dictionary with potential changes. :returns: A dictionary with the updates if any. """ updates = {} for k in set(new.keys()).intersection(set(old.keys())): if old[k] != new[k]: updates.update({k: new[k]}) return updates
def odict_to_attributes_gff(attributes): """ Parse the GFF attribute column and return a dict """ if attributes: atts = [] for k, v in attributes.items(): atts.append('{}={}'.format(k, v)) temp_atts = ";".join(atts) return temp_atts.rstrip() return '.'
def backend_name(name): """Human readable mapping for the social auth backend""" return { 'google-oauth': 'Google OAuth', 'google-oauth2': 'Google OAuth', 'google-openidconnect': 'Google OpenId', }.get(name, name)
def to_label(f): """ convert a float to a label that makes sense """ if f < 0.1: return "%.3f" % f elif f < 1.0: return "%.2f" % f elif f < 10.0: return "%.1f" % f else: return "%d" % int(f)
def heap_sort(array): """ Input : list of values Note: Builds a max heap of given array. Then swaps first element (which is largest) of the array with the last, and heapifys w.r.t new first element (array excluding the last element). It reapeats this procedure till array is sorted. Returns : sorted list of values """ def max_heap(array): """ Input : list of values Note: Builds max_heap by calling heapify function on all parent nodes. Returns : max_heap list of values """ n = len(array) for i in range(int(n/2)-1,-1,-1): # We need to heapify parents only. # int(n/2) - 1 is highest index a parent node can have. array[:] = heapify(array, i) return array def heapify(array, index): """ Input : list of values, index Note : element at given index is placed in the heap such that its parent is greater than or equal to it and its children are less than or equal to it. Returns : list of values """ n = len(array) right_child_index = 2*(index+1) left_child_index = right_child_index - 1 if right_child_index < n: max_child_index = right_child_index if array[left_child_index] > array[right_child_index]: max_child_index = left_child_index if array[index] < array[max_child_index]: array[index], array[max_child_index] = array[max_child_index], array[index] # If given element, in its new position, still has children, then we need to heapify again. if max_child_index <= int(n/2) - 1: # given number is highest possible index a parent can have. array[:] = heapify(array, max_child_index) return array elif left_child_index == n - 1: if array[index] < array[left_child_index]: array[index], array[left_child_index] = array[left_child_index], array[index] return array return array array[:] = max_heap(array) n = len(array) for i in range(n-1): array[0], array[n-1-i] = array[n-1-i], array[0] array[:n-1-i] = heapify(array[:n-1-i],0) return array
def strip_newlines(text): """strip any newlines from a string""" return text.replace('\n', ' ').replace('\r', '').rstrip()
def bubble_sort(m): """ Bubble sort impl O(n^2) @param m: sort collection @return sorted(@m) """ for i in range(len(m) - 1): for j in range(len(m) - i - 1): if m[j] > m[j + 1]: m[j], m[j + 1] = m[j + 1], m[j] return m
def getAbunFromDict(dict, tag): """Get the abundance of the tag from a dictionary Args: tag: The tag to be queried from the dictionary dict: The dictionary of tags and their abundances in ech library libList: The list of libraries as provided by the user Returns: Three separate elements. The first is the tag, the second is the summed abundance across all libraries, and the final is a list of the individual library abundances """ # Pull the library index from the dictionary index = list(dict.keys())[0] # Try to abundance of tag. If it doesn't exist in this library, # return 0 for the abundance try: return([index, dict[index][tag]]) # Tag doesn't exist in this dictionary so return 0 except KeyError: return([index,0])
def round_down(x,step): """Rounds x down to the next multiple of step.""" from math import floor if step == 0: return x return floor(float(x)/float(step))*step
def load(file, width, height, data_start, colors, color_depth, *, bitmap=None, palette=None): """Loads indexed bitmap data into bitmap and palette objects. :param file file: The open bmp file :param int width: Image width in pixels :param int height: Image height in pixels :param int data_start: Byte location where the data starts (after headers) :param int colors: Number of distinct colors in the image :param int color_depth: Number of bits used to store a value""" # pylint: disable=too-many-arguments,too-many-locals if palette: palette = palette(colors) file.seek(data_start - colors * 4) for value in range(colors): c_bytes = file.read(4) # Need to swap red & blue bytes (bytes 0 and 2) palette[value] = bytes(b''.join([c_bytes[2:3], c_bytes[1:2], c_bytes[0:1], c_bytes[3:1]])) if bitmap: minimum_color_depth = 1 while colors > 2 ** minimum_color_depth: minimum_color_depth *= 2 bitmap = bitmap(width, height, colors) file.seek(data_start) line_size = width // (8 // color_depth) if width % (8 // color_depth) != 0: line_size += 1 if line_size % 4 != 0: line_size += (4 - line_size % 4) chunk = bytearray(line_size) mask = (1 << minimum_color_depth) - 1 for y in range(height - 1, -1, -1): file.readinto(chunk) pixels_per_byte = 8 // color_depth offset = y * width for x in range(width): i = x // pixels_per_byte pixel = (chunk[i] >> (8 - color_depth*(x % pixels_per_byte + 1))) & mask bitmap[offset + x] = pixel return bitmap, palette
def af_subtraction(ch1, ch2, m, c): """ Subtract ch2 from ch1 ch2 is first adjusted to m * ch2 + c :param ch1: :param ch2: :param m: :param c: :return: """ af = m * ch2 + c signal = ch1 - af return signal
def selection(list): """Selection sort for an unordered list.""" if len(list) < 2: return list for i in range(len(list)): current = i for n in range(i + 1, len(list)): if list[current] > list[n]: current = n list[i], list[current] = list[current], list[i] return list
def payload_to_list(alias_payload): """ Unboxes a JSON payload object expected by the server into a list of alias names. """ return [record["value"] for record in alias_payload["aliases"]]
def binary_search(array, search_term): """ Binary search algorithm for finding an int in an array. Returns index of first instance of search_term or None. """ p = 0 r = len(array) - 1 while p <= r: q = (p + r) // 2 value = array[q] if value == search_term: return q elif value > search_term: r = q - 1 else: # value < search_term p = q + 1 return None
def are_configurations_equal(configuration1, configuration2, keys): """ Compare two configurations. They are considered equal if they hold the same values for all keys. :param configuration1: the first configuration in the comparison :param configuration2: the second configuration in the comparison :param keys: the keys to use for comparison :return: boolean indicating if configurations are equal or not """ for key in keys: if configuration1[key] != configuration2[key]: return False return True
def common_languages(programmers): """Receive a dict of keys -> names and values -> a sequence of of programming languages, return the common languages""" # create a list of sets with the languages. languages = [set(language) for language in programmers.values()] # return the intersection unpacking all the languages return set.intersection(*languages)
def health(): """Used to test if this service is alive""" return {"status": "OK"}
def singularize(args, premise): """Return singular equivalent POS-tag for given POS-tag.""" pos = args[0] # Singularize dict singularize_dict = {'NNS':'NN', 'NN':'NN', 'NNPS':'NNP', 'VBP':'VBZ', 'VBD':'VBD', 'VB':'VB', 'VBZ':'VBZ', 'VBN':'VBN', 'MD':'MD' } # Test whether pos is in dict, otherwise return unaltered pos try: sing_pos = singularize_dict[pos] except KeyError: return pos return sing_pos
def usub(x): """Implementation of `usub`.""" return x.__neg__()
def _get_labels_from_sample(labels, classes): """Translate string labels to int.""" sorted_labels = sorted(list(classes)) return [sorted_labels.index(item) for item in labels] if isinstance(labels, list) else sorted_labels.index(labels)
def summarize_cag_taxa(cag_id, cag_tax_df, taxa_rank): """Helper function to summarize the top hit at a given rank.""" # If there are no hits at this level, return None if cag_tax_df is None: return { "CAG": cag_id, "name": 'none', "label": "No genes assigned at this level" } # Return the top hit return { "CAG": cag_id, "name": cag_tax_df["name"].values[0], "label": "{}<br>{:,} genes assigned".format( cag_tax_df["name"].values[0], int(cag_tax_df["count"].values[0]) ) }
def has_tag(method, tag: str) -> bool: """ Checks if the given method has the given tag. :param method: The method to check. :param tag: The tag to check for. :return: True if the tag exists on the method, False if not. """ return hasattr(method, '__tags') and tag in method.__tags
def _is_cluster_bootstrapping(cluster_summary): """Return ``True`` if *cluster_summary* is currently bootstrapping.""" return (cluster_summary['Status']['State'] != 'STARTING' and not cluster_summary['Status']['Timeline'].get('ReadyDateTime'))
def estimate(difficulty, format=False): # pylint: disable=redefined-builtin """ .. todo: fix unused variable """ ret = difficulty / 10 if ret < 1: ret = 1 if format: # pylint: disable=unused-variable out = str(int(ret)) + " seconds" if ret > 60: ret /= 60 out = str(int(ret)) + " minutes" if ret > 60: ret /= 60 out = str(int(ret)) + " hours" if ret > 24: ret /= 24 out = str(int(ret)) + " days" if ret > 7: out = str(int(ret)) + " weeks" if ret > 31: out = str(int(ret)) + " months" if ret > 366: ret /= 366 out = str(int(ret)) + " years" ret = None # Ensure legacy behaviour return ret
def remove_paren(v): """remove first occurance of trailing parentheses from a string""" idx = v.find('(') if idx != -1: return v[0:idx] return v
def strip_comments(string, markers): """ Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. :param string: a string input. :param markers: list of characters. :return: a new string with whitespace and comment markers removed. """ parts = string.split("\n") for v in markers: parts = [x.split(v)[0].rstrip() for x in parts] return "\n".join(parts)
def avg(arr): """ Return an average """ return sum(arr) * 1.0 / len(arr)
def get_as_list(somestring): """ Input : a string like this : 'a, g, f,w' Output : a list like this : ['a', 'g', 'f', 'w'] """ return somestring.replace(' ', '').split(',')
def find_text(text): """ Find string inside double quotes """ import re matches = re.findall(r'\"(.+?)\"', text) return matches[0]
def _quant_zoom(z): """Return the zoom level as a positive or negative integer.""" if z == 0: return 0 # pragma: no cover return int(z) if z >= 1 else -int(1. / z)
def format_omniglot(data): """Formats an Omniglot input into a standard format. The formatted sample will have two keys: 'image', containing the input image, and 'label' containing the label. Args: data: dict, a sample from the Omniglot dataset. Contains keys: 'image', 'alphabet' and 'alphabet_char_id'. Returns: Formatted `data` dict. """ data['label'] = data['alphabet_char_id'] del data['alphabet_char_id'] del data['alphabet'] return data
def parse_line(line): """<line> ::= <color> contain <contents>""" tokens = line.replace(",", " COMMA").replace(".", " PERIOD").split() tokens = list(reversed(tokens)) # it's a stack def eat(*expected): assert tokens.pop() in expected def parse_color(): """<color> ::= <word> <word> (bag|bags)""" res = "{} {}".format(tokens.pop(), tokens.pop()) eat("bag", "bags") return res def parse_contents(): """<contents> ::= contain (no other bags|<bag-amount-list>) PERIOD""" assert tokens.pop() == "contain" if tokens[-1] == "no": eat("no") eat("other") eat("bags") res = [(0, None)] else: res = parse_bag_amount_list() eat("PERIOD") return res def parse_bag_amount_list(): """<bag-amount-list> ::= <integer> <color> (COMMA <integer> <color>)*""" res = [] am = int(tokens.pop()) col = parse_color() res.append((am, col)) while tokens[-1] == "COMMA": eat("COMMA") am = int(tokens.pop()) col = parse_color() res.append((am, col)) return res col = parse_color() contents = parse_contents() assert not tokens return (col, contents)
def num(s): """This function is used to convert string to int or float.""" try: return int(s) except ValueError: return float(s)
def get_provenance_record(ancestor_files, caption, statistics, domains, plot_type='other'): """Get Provenance record.""" record = { 'caption': caption, 'statistics': statistics, 'domains': domains, 'plot_type': plot_type, 'themes': ['phys'], 'authors': [ 'weigel_katja', ], 'references': [ 'deangelis15nat', ], 'ancestors': ancestor_files, } return record
def rc(dna): """ Reverse complement a DNA sequence :param dna: The DNA sequence :type dna: str :return: The reverse complement of the DNA sequence :rtype: str """ complements = str.maketrans('acgtrymkbdhvACGTRYMKBDHV', 'tgcayrkmvhdbTGCAYRKMVHDB') rcseq = dna.translate(complements)[::-1] return rcseq
def isvector_or_scalar_(a): """ one-dimensional arrays having shape [N], row and column matrices having shape [1 N] and [N 1] correspondingly, and their generalizations having shape [1 1 ... N ... 1 1 1]. Scalars have shape [1 1 ... 1]. Empty arrays dont count """ try: return a.size and a.ndim-a.shape.count(1) <= 1 except: return False
def normalized_thread_name(thread_name): """ Simplifies a long names of thread (for Zafira UI), e.g. MainThread -> MT, ThreadPoolExecutor -> TPE, etc. :param thread_name: thread name from Log Record object :return: simplified thread name """ normalized = '' for symb in thread_name: if symb.isupper(): normalized += symb return normalized
def file_exists(filepath): """ Returns true if file exists, false otherwise """ try: f = open(filepath, 'r') exists = True f.close() except: exists = False return exists
def is_anagram(word1, word2): """Receives two words and returns True/False (boolean) if word2 is an anagram of word1, ignore case and spacing. About anagrams: https://en.wikipedia.org/wiki/Anagram""" # short way # word1 = word1.strip().replace(' ', '').lower() # word2 = word2.strip().replace(' ', '').lower() # return sorted(word1) == sorted(word2) # longer way word1 = word1.strip().replace(' ', '').lower() word2 = word2.strip().replace(' ', '').lower() if len(word1) != len(word2): return False count = {} for letter in word1: if letter in count: count[letter] += 1 else: count[letter] = 1 for letter in word2: if letter in count: count[letter] -= 1 else: count[letter] = 1 for c in count: if count[c] != 0: return False return True
def remove_ver_suffix(version): """Remove the codename suffix from version value""" import re pattern = re.compile(r'\+\w+\.\d$') # Example: +matrix.1 return re.sub(pattern, '', version)
def _anchors(config, dataset): """ An anchor is the top left key of a square group of elements """ scale = config['scale'] def is_anchor_index(index): return index % scale == 0 return set( (x, y) for x, y in dataset.keys() if is_anchor_index(x) and is_anchor_index(y) )
def reprsort(li): """ sometimes, we need a way to get an unique ordering of any Python objects so here it is! (not quite "any" Python objects, but let's hope we'll never deal with that) """ extli = list(zip(map(repr, li), range(len(li)))) extli.sort() return [li[i[1]] for i in extli]
def hex2rgb(hex_str): """ #123456 -> (18, 52, 86) """ h = hex_str[hex_str.find('#') + 1:] l = len(h) if l == 6: return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16) elif l == 3: return int(h[0], 16), int(h[1], 16), int(h[2], 16) else: raise TypeError("hex_str not recognized:" + str(hex_str))
def sloppyUnique(t, thresholdSeconds): """ Takes a list of numbers and returns a list of unique values, subject to a threshold difference. """ # start with the first entry, and only add a new entry if it is more than the threshold from prior sloppyList = [t[0]] for i in range(1,len(t)): keepit = True for j in range(0,i): if (abs(t[i]-t[j]) < thresholdSeconds): keepit = False if (keepit): sloppyList.append(t[i]) # print "sloppyUnique returns %d values from the original %d" % (len(sloppyList), len(t)) return(sloppyList)
def start_cluster_endpoint(host): """ Utility function to generate the get run endpoint given the host. """ return f'https://{host}/api/2.0/clusters/start'
def concat_name(prefix, name): """ Returns the concatenation of `prefix` and `name`. """ return prefix + "_" + name
def largest(min_factor, max_factor): """Given a range of numbers, find the largest palindromes which are products of two numbers within that range. :param min_factor: int with a default value of 0 :param max_factor: int :return: tuple of (palindrome, iterable). Iterable should contain both factors of the palindrome in an arbitrary order. """ if min_factor > max_factor: raise ValueError("min must be <= max") for product in range(max_factor ** 2, min_factor ** 2 - 1, -1): if str(product) == str(product)[::-1]: factors = [] for j in range(min_factor, max_factor + 1): if product % j == 0 and min_factor <= (product // j) <= max_factor: factors.append(sorted([j, product // j])) if factors: return product, factors return None, []
def normalize(vector): """ calculates the unit-length vector of a given vector :param vector: an iterable of integers :return: a list of integers """ return [int/sum(vector) for int in vector]
def signum(x): """ >>> signum(0) 0 >>> signum(42) 1 >>> signum(-23) -1 """ return 0 if x == 0 else x / abs(x)
def gcd(a, b): """Greatest Common Divisor by Euclid""" a = abs(a) b = abs(b) if a == 0 and b == 0: return 1 if a == 0: return b if b == 0: return a if a < b: a, b = b, a r = 1 while r: r = a % b if r: a = b b = r return b
def all_elements_are_identical(iterator): """Check all elements in iterable like list are identical.""" iterator = iter(iterator) try: first = next(iterator) except StopIteration: return True return all(first == rest for rest in iterator)
def getid(obj): """Get object's ID or object. Abstracts the common pattern of allowing both an object or an object's ID as a parameter when dealing with relationships. """ try: return obj.id except AttributeError: return obj
def div(item): """ HTML <pre> tag """ return '<div style="margin-top:-8px;margin-bottom:-8px;">{0}</div>'.format(item)
def residual(qdot, q): """ Residual of the ODE """ return qdot - 9.8 + 0.196*q
def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits)
def remote_error_unknown(): """Return a remote "error" code.""" return {"errorType": 999}
def _resolve(name): """Resolve a dotted name to a global object.""" name = name.split('.') used = name.pop(0) found = __import__(used) for n in name: used = used + '.' + n try: found = getattr(found, n) except AttributeError: __import__(used) found = getattr(found, n) return found
def task_po(): """Update translations.""" return { 'actions': ['pybabel update -D telbot -d localization -i localization/telbot.pot'], 'file_dep': ['localization/telbot.pot'], 'targets': ['localization/en/LC_MESSAGES/telbot.po'], }
def percent_of(percent, whole): """Calculates the value of a percent of a number ie: 5% of 20 is what --> 1 Args: percent (float): The percent of a number whole (float): The whole of the number Returns: float: The value of a percent Example: >>> percent_of(25, 100) 25.0 >>> percent_of(5, 20) 1.0 """ percent = float(percent) whole = float(whole) return (percent * whole) / 100
def get_title_from_vuln(vuln): """ Returns CVE ID from vulnerability document When there is no title, returns "No-title" string """ return vuln.get('title', "No-Title")
def get_or_else(hashmap, key, default_value=None): """ Get value or default value It differs from the standard dict ``get`` method in its behaviour when `key` is present but has a value that is an empty string or a string of only spaces. Args: hashmap (dict): target key (Any): key default_value (Any): default value Example: >>> get_or_else({'k': 'nonspace'}, 'k', 'default') 'nonspace' >>> get_or_else({'k': ''}, 'k', 'default') 'default' >>> get_or_else({'k': ' '}, 'k', 'default') 'default' Returns: The value of `key` or `default_value` """ value = hashmap.get(key) if value is None: return default_value else: if 0 < len(value.strip()): return value else: return default_value
def circ_ave(a0, a1): """see http://stackoverflow.com/a/1416826/113195""" r = (a0+a1)/2., ((a0+a1+360)/2.)%360 if min(abs(a1-r[0]), abs(a0-r[0])) < min(abs(a0-r[1]), abs(a1-r[1])): return r[0] else: return r[1]
def type_fmt(type_): """Return the Python struct marker for the type""" if type_ == 'INT_TYPE': return 'i' elif type_ == 'LONG_TYPE': return 'q' elif type_ == 'FLOAT_TYPE': return 'f' elif type_ == 'DOUBLE_TYPE': return 'd' raise NotImplementedError('type {} is not supported'.format(type_))
def escape_char(string): """ Escape special characters from string before passing to makefile. Maybe more characters will need to be added. """ string = string.replace("'", "\\'") # escape ' string = string.replace('"', '\\"') # escape " string = string.replace("\n", "\\n") # escape \n return string
def compact2(sequence): """ Bonus 1: This version accepts any iterable, not just a sequence. """ if type(sequence) == list and len(sequence) == 0: return sequence first, *rest = sequence output = [first] for el in rest: if el != output[-1]: output.append(el) return output
def legalize_cromwell_labels(label): """Legalize invalid labels so that they can be accepted by Cromwell. Note: Cromwell v32 and later versions are permissive and accepting all sort of valid JSON strings, but with a length limitation of 255. This function will subset the first 255 characters for too long string values. Args: label (str | list | None): A string or a list of a string of key/value of labels need to be legalized. Returns: str: A string of label with no more than 255 characters. Raises: ValueError: This will happen if the value of the label is a list, and the length of it is not equal to 1. """ cromwell_label_maximum_length = 255 if isinstance(label, list): if len(label) != 1: raise ValueError(f"{label} should contain exactly one element!") label = label[0] return str(label)[:cromwell_label_maximum_length]
def bounded_aitken(f, x0, x1, y0, y1, x, yval, xtol, ytol): """False position solver with Aitken acceleration.""" _abs = abs if y1 < 0.: x0, y0, x1, y1 = x1, y1, x0, y0 dx1 = x1-x0 dy = yval-y0 if not (x0 < x < x1 or x1 < x < x0): x = x0 + dy*dx1/(y1-y0) yval_ub = yval + ytol yval_lb = yval - ytol while _abs(dx1) > xtol: y = f(x) if y > yval_ub: x1 = x y1 = y elif y < yval_lb: x0 = x y0 = y dy = yval-y else: return x dx0 = x1-x0 g = x0 + dy*dx0/(y1-y0) if _abs(dx0) < xtol: return g y = f(g) if y > yval_ub: x1 = g y1 = y elif y < yval_lb: x0 = g y0 = y dy = yval-y else: return g dx1 = x1-x0 gg = x0 + dy*dx1/(y1-y0) dxg = x - g try: x = x - dxg**2./(gg + dxg - g) except: # Add overshoot to prevent getting stuck x = gg + 0.1*(x1+x0-2*gg)*(dx1/dx0)**3. else: if not (x0 < x < x1 or x1 < x < x0): x = gg + 0.1*(x1+x0-2*gg)*(dx1/dx0)**3. return x
def find(predicate, seq): """A helper to return the first element found in the sequence that meets the predicate. For example: :: member = find(lambda m: m.name == 'Mighty', channel.server.members) would find the first :class:`Member` whose name is 'Mighty' and return it. If an entry is not found, then ``None`` is returned. This is different from `filter`_ due to the fact it stops the moment it finds a valid entry. .. _filter: https://docs.python.org/3.6/library/functions.html#filter Parameters ----------- predicate A function that returns a boolean-like result. seq : iterable The iterable to search through. """ for element in seq: if predicate(element): return element return None
def ordered_unique(seq): """ Return unique items in a sequence ``seq`` preserving their original order. """ if not seq: return [] uniques = [] for item in seq: if item in uniques: continue uniques.append(item) return uniques
def cdo(string): """ Takes a string, sortes it and then returns a sorted string. """ temp = sorted(string.split()) return ' '.join(temp)
def preprocess(text): """ Pre-process text for use in the model. This includes lower-casing, standardizing newlines, removing junk. :param text: a string :return: cleaner string """ if isinstance(text, float): return '' return text.lower().replace('<br />', '\n').replace('<br>', '\n').replace('\\n', '\n').replace('&#xd;', '\n')
def get_latest(dir_list): """Returns the newest month or year from a list of directories""" int_list = [] for directory in dir_list: try: int_list.append(int(directory)) except ValueError: pass if not int_list: return None return max(int_list)
def himmelblau(args): """ Name: Himmelblau Local minimum: f(3.0,2.0) = 0.0 Local minimum: f(-2.805118,3.131312) = 0.0 Local minimum: f(-3.779310,-3.283186) = 0.0 Local minimum: f(3.584428,-1.848126) = 0.0 Search domain: -5.0 <= x, y <= 5.0 """ x = args[0] y = args[1] return (x ** 2 + y - 11) ** 2 + (x + y ** 2 - 7.0) ** 2
def triangle_shape(height): """ Display a traingle shape made of x with a certain height Args: height ([int]): The desired height for the shape Returns: [str]: A triangle shape made of x """ triangle = "" nbEspaces = height - 1 for indice in range(height): triangle += nbEspaces * " " triangle += "x" * (indice * 2 + 1) triangle += nbEspaces * " " if indice < (height - 1): triangle += "\n" nbEspaces += -1 return triangle
def attribute_type_validator(x): """ Property: AttributeDefinition.AttributeType """ valid_types = ["S", "N", "B"] if x not in valid_types: raise ValueError("AttributeType must be one of: %s" % ", ".join(valid_types)) return x
def get_hms_for_seconds(seconds): """ prints number of seconds in hours:minutes:seconds format""" m, s = divmod(seconds, 60) h, m = divmod(m, 60) hms = "%d hours: %02d min: %02d sec" % (h, m, s) return hms
def metalicity_jk_v_band(period, phi31_v): """ Returns the JK96 caclulated metalicity of the given RRab RR Lyrae. (Jurcsik and Kovacs, 1996) (3) (Szczygiel et al., 2009) (6) (Skowron et al., 2016) (1) Parameters ---------- period : float64 The period of the star. phi31_v : float64 The V band phi31 of the star. Returns ------- metalicity_jk_v : float64 The JK96 metalicity of the star. """ return -5.038 - 5.394 * period + 1.345 * phi31_v
def fix_saints(report_city): """ Changes St. -> Saint """ city_components = report_city.split(" ") if city_components[0].strip().lower() == "st.": city_components[0] = "Saint" return " ".join(city_components)
def get_sorted_index(l, reverse=True): """ Get the sorted index of the original list. """ return sorted(range(len(l)), key=lambda k: l[k], reverse=reverse)
def sign(number: int) -> int: """ Maps the sign of the number to -1 or 1""" if number < 0: return -1 else: return 1
def init_table(code_size,char_size): """code_size - bits per code, maximum length of string_table char_size - how many bits for a character (ie, 256 for ascii)""" string_table = [] for i in range(char_size): string_table.append(chr(i)) return string_table
def format_record(record, event): """ Format record value to formatted string suitable for the event. """ if event == '333fm': return str(record)[0:2] + '.' + str(record)[2:] elif event == '333mbf': # Skip old multiple-bf format if 1000000000 < record: return str(record) else: record = str(record) diff = 99 - int(record[0:2]) sec = int(record[2:7]) miss = int(record[7:9]) solved = diff + miss attempted = solved + miss return '%d/%d (%d:%02d)' % (solved, attempted, sec / 60, sec % 60) else: msec, _sec = record % 100, record / 100 sec, min = _sec % 60, _sec / 60 if 0 < min: return '%d:%02d.%02d' % (min, sec, msec) else: return '%d.%02d' % (sec, msec)
def validate_budget_savings(savings): """Validate budget savings input.""" errors = [] if savings is None: errors.append("Savings can not be empty.") return errors if not isinstance(savings, int): errors.append("Savings must be integer type.") return errors if not 0 <= savings <= 100: errors.append("Savings is out of range (0-100).") return errors
def get_cog_name(path: str) -> str: """ Auxiliary function, gets a cog path and returns the name of the file without the '.py' """ return path.split("\\")[-1][:-3]
def intstrtuple(s): """Get (int, string) tuple from int:str strings.""" parts = [p.strip() for p in s.split(":", 1)] if len(parts) == 2: return int(parts[0]), parts[1] else: return None, parts[0]
def getYear(orig_date_arr): """ return an integer specifying the previous Year """ if orig_date_arr[1] == orig_date_arr[2] == 1: return orig_date_arr[0] - 1 else: return orig_date_arr[0]
def endswith_whitespace(text): """Check if text ends with a whitespace If text is not a string return False """ if not isinstance(text, str): return False return text[-1:].isspace()
def _get_param_type(name: str, value: str) -> type: """Map parameter type to Python type. :param name: parameter name :param value: parameter type :return: Python type """ t = {"str": str, "int": int}.get(value, None) if not t: raise Exception(f"unknown type {value} for param {name}") return t
def convert2Frequency(featureDict): """ Converts the count values of the feature dictionary to frequencies. Arguments --------- featureDict : dict dictionary of document with the respective values Returns ------- featureDict : dict containing the corresponding frequencies converted to absolute numbers """ if sum(featureDict.values()) != 0: invTotalNumber = 1.0 / sum(featureDict.values()) else: invTotalNumber = 1.0 featureDict.update((k, invTotalNumber*v) for k,v in featureDict.items()) return featureDict
def should_ensure_cfn_bucket(outline: bool, dump: bool) -> bool: """Test whether access to the cloudformation template bucket is required. Args: outline: The outline action. dump: The dump action. Returns: If access to CF bucket is needed, return True. """ return not outline and not dump
def parse_prodtype(prodtype): """ From a prodtype line, returns the set of products listed. """ return set(map(lambda x: x.strip(), prodtype.split(',')))
def collapse(array): """ Collapse a homogeneous array into a scalar; do nothing if the array is not homogenous """ if len(set(a for a in array)) == 1: # homogenous array return array[0] return array
def key_for_projects(project): """Generate a string search key for a Jira projects.""" return u' '.join([ project['key'], project['name']])
def grid_changing(rows, cols, grid, next_grid): """ Checks to see if the current generation Game of Life grid is the same as the next generation Game of Life grid. :param rows: Int - The number of rows that the Game of Life grid has :param cols: Int - The number of columns that the Game of Life grid has :param grid: Int[][] - The list of lists that will be used to represent the current generation Game of Life grid :param next_grid: Int[][] - The list of lists that will be used to represent the next generation of the Game of Life grid :return: Boolean - Whether the current generation grid is the same as the next generation grid """ for row in range(rows): for col in range(cols): # If the cell at grid[row][col] is not equal to next_grid[row][col] if not grid[row][col] == next_grid[row][col]: return True return False