content
stringlengths
42
6.51k
def tanh_d(x: float) -> float: """ The gradient of the Hyperbolic Tangent activation function Args: x: The point at which to take the gradient Returns: The gradient of the tanh activation function """ return 1 - x ** 2
def http_header(value): """Converts Django HTTP headers to standard format e.g. HTTP_ACCEPT -> Accept HTTP_CACHE_CONTROL -> Cache-Control """ parts = value.split('_') header_parts = [part.title() for part in parts[1:]] formatted = '-'.join(header_parts) return formatted
def insertionSort(array): """Apply insertion sort to an array. Returns a sorted array.""" for i in range(1, len(array)): key = array[i] j = i-1 while j >= 0 and key < array[j]: array[j+1] = array[j] j -= 1 array[j+1] = key return array
def convert_quality_filter(quality): """Jinja2 Filter to convert quality score.""" quality_map = { "A01": "Poor", "A02": "OK", "A03": "Moderate", "A04": "Good", } if quality not in quality_map: raise ValueError("The quality is not a valid value. It must be A01 - ...
def _fixup_find_links(find_links): """Ensure find-links option end-up being a list of strings.""" if isinstance(find_links, str): return find_links.split() assert isinstance(find_links, (tuple, list)) return find_links
def hex_byte_str(value: int) -> str: """ Convert a "char" to a hexadecimal number. """ if not (0 <= value <= 0xFF): raise ValueError(f"value must be between 0 and 255: {value}") hex_value = hex(value)[2:] if value < 0x10: hex_value = "0" + hex_value return hex_value
def get_dict_values(dic: dict) -> list: """ Insert the dictionary values into the list :param dic: The desired dictionary to be converted :return :list will be returned with the dictionary values """ return list(dic.values())
def is_str(value): """Must be of type `str`""" return isinstance(value, str)
def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for i in range(n-1): ...
def first_occurrence_index(l, val, after_index=None): """ Find the first occurrence of some value, after_index will not be included in the possible return value :param l: :param val: value to look for :param after_index: exclusive beginning of the range :return: zero-based index ""...
def get_jsonpath(obj: dict, jsonpath): """ Gets a value from a dictionary based on a jsonpath. It will only return one result, and if a key does not exist it will return an empty string as template tags should not raise errors. :param obj: The dictionary to query :param jsonpath: The path to th...
def disable_tc_type_selector_dropdowns(acq_state, div_style): # pylint: disable=invalid-name """ A callback function to disable all TC Type selector dropdowns when the application status changes to configured or running. """ div_style['pointer-events'] = 'auto' div_style['opacity'] = 1.0 ...
def get_nested_labels(flattened_labs, len_list): """ Given an utterance-level flattened list of labels, and the lengths (in utterance) of each sessions, get a session-level nested list of labels. Parameters ---------- flattened_labs : list[int] or np.array[int] 1-d list or np.array with...
def format_ft_comp(q, a1, a2, context=False): """Formats prompt for fine-tuned semantic similarity with GPT-3""" if context: prompt = '{0}\n1: {1}\n2: {2}\nEqual:'.format(q.strip(), a1.strip(), a2.strip()) else: prompt = '1: {0}\n2: {1}\nEqual:'.format(a1, a2) return prompt
def normalize(testURL): """Normalize the URL.""" testURL = testURL.split('//', 1)[1] # testURL = re.sub("^http(s)?://", "", testURL) if testURL.endswith('/'): testURL = testURL[:-1] # testURL = re.sub("/$", "", testURL) components = testURL.split('/') return components
def is_function(var): """ Test if variable is function (has a __call__ attribute) :return: True if var is function, False otherwise. :rtype: bol """ return hasattr(var, '__call__')
def pixel_sum(position): """ Sums up the total count of pixels in the area limited by the coordinate points in position. """ if (position != None): return position.get("width", 0) * position.get("height", 0) else: return 0
def pointing_tuple2str(dirtuple): """ Convert a direction tuple to a string Inverse of pointing_str2tuple(). Parameters ---------- dirtuple : tuple or None Direction tuple defined as (angle1: float, angle2: float, refsys: str) or None if beamctldirarg was not correct format...
def head(sequence): """ Returns first item from `sequence` or :const:`None` if sequence is empty. >>> head([1]) 1 >>> head([2, 3]) 2 >>> head([(1, 2), (3, 4)]) (1, 2) >>> head() """ try: return next(iter(sequence)) except StopIteratio...
def is_curious_fraction(numerator, denominator): """ Determine if two numbers form a curious fraction. A curious fraction is where removing a number common to the numerator and denominator is equal to the original fraction. :param numerator: The numerator of the fraction as an int. :param den...
def extractAliasFromContainerName(containerName): """ Take a compose created container name and extract the alias to which it will be refered. For example bddtests_vp1_0 will return vp0 """ return containerName.split("_")[1]
def edges_index(edges): """Edges are given as (v1,v2) Return the indexes of those vertices (v1-1, v2-1)""" edges_idx = [(e[0] - 1, e[1] - 1) for e in edges] return edges_idx
def validate_description(value): """Raise exception if description exceeds length.""" if value and len(value) > 128: return "have length less than or equal to 128" return ""
def is_hex(s): """ Explicit name, used to detect errors in to be sent hashes """ try: int(s, 16) return True except ValueError: return False
def find_peak(list_of_integers): """ Args: list_of_integers(int): list of integers to find peak of Returns: peak of list_of_integers or None """ size = len(list_of_integers) mid_e = size mid = size // 2 if size == 0: return None while True: mid_e = mid_e // ...
def get_label_name(node, dialogue_list): """ Takes a node and returns the name for its label """ for dialogue in dialogue_list: if dialogue["Id"] == node["Parent"]: label_name = "{}_{}".format(dialogue["DisplayName"], node["Id"]) return label_name
def source_peer(peer): """Sets environment variables for that peer""" return "source /etc/hyperledger/crypto-config/tools/set_env." + peer+".sh"
def bytesToSigned32(bytearr): """ converts the last 4 bytes of a 5 byte array to a signed integer """ unsigned=(bytearr[1]<<24)+(bytearr[2]<<16)+(bytearr[3]<<8)+bytearr[4] return unsigned-4294967296 if bytearr[1]&128 else unsigned
def masked(supported_resource_type_control=None): """ check if force_url_override is set in SupportedResourceType """ mask = False if supported_resource_type_control: if supported_resource_type_control.override_url_id: mask = True return mask
def split_list(input_list): """ Splits a list in half (assumes even length) :param input_list: :return: Tuple of the first and second halves of the list """ if len(input_list) % 2 == 0: half = len(input_list) // 2 return input_list[:half], input_list[half:] else: rais...
def retry_if_Index_Exception(exception): """ There is a bug when importing pybel that triggers this error: https://github.com/MD-Studio/MDStudio/issues/29 """ return isinstance(exception, IndexError)
def makeProperMAC(s): """ create a MAC address string in SNIPEIT format (eg XX:XX:...)""" #option one: this is already XX:XX:XX:XX:XX:XX if len(s.split(':')) ==6: return s if len(s)==12: #option 2 aabbccddeeff return ":".join([s[i:i+2] for i in range(0, len(s), 2)]) # option 3: aa-bb-cc-...
def write_codelist_to_xls(worksheet, rows, header, row_nbr=0): """ write code list, value level, or where clause rows to the odmlib worksheet :param worksheet: odmlib worksheet object to write to :param rows: a list of dictionaries (rows) to write to the worksheet :param row_nbr: integer row number ...
def follow_wall(front, left, right): """Simple follow wall controller.""" change_direction = 0 F = (0 < front < 4) L = (0 < left < 4) R = (0 < right < 4) if 0 < front < 3: change_direction = -10 elif 1.0 <= left <= 2.0: # we're good change_direction = 0 elif 0 <...
def colordiff(diff): """convert git diff data to html/bootstrap color code""" if diff == '': return '' diff = diff.strip() diff = diff.replace('\n', '&nbsp;\n') diffData = diff.split('\n') openTag = '<tr><td class="' openTagEnd = '">' nbsp = '&nbsp;&nbsp;&nbsp;&nbsp;' data = ...
def str_true(v): """The string representation of a true value will be 'TRUE'. False will be the empty string. """ if v: return "TRUE" else: return ""
def _rlz(s: str) -> str: """ Removes the leading zeroes from a number in string form. """ x = 0 while s[x] == '0' and x < len(s) - 1: x += 1 return s[x:]
def get_min_taxa(num_taxa,max_missing=1): """ often lots of clusters with full taxon occupancy when num_taxa is small don't want to print out too many clusters for a test run""" return num_taxa - int(max_missing) if num_taxa >= 10 else num_taxa
def merge_logs(bet_logs, bet_results_logs): """Merges bet logs (LogBet) with bet results logs (LogResult).""" merged_logs = () # per bet ID dictionary bet_results_dict = {} for bet_result in bet_results_logs: bet_id = bet_result["bet_id"] bet_results_dict = dict(bet_results_dict, **{...
def make_stat(opt_fp, opt_tp, max_fp, len_df): """ Called by loanpy.sanity.postprocess2. Calculates statistics from optimum, max nr of guesses and length \ of input data frame. :param opt_fp: The optimal false positive rate as a fraction of the \ maximal false positive rate, i.e. last (=highes...
def get_exec_log_name(execname, comp_opts_count=None, exec_opts_count=None): """Returns the execution output log name based on number of comp and exec opts.""" suffix = '.exec.out.tmp' if comp_opts_count is None and exec_opts_count is None: return '{0}{1}'.format(execname, suffix) else: ...
def pagodaValue(gameState): ################################################# # # A function evaluating the board state, whose # value is non-increasing with every move. When # we reach a game state, not the goal, whose # Pagoda Value is less than the goal state, we ...
def int_to_string(value, dp=0): """Converts a python int to a homie string""" return str(round(value, dp))
def get_status(scores, expected, status_match, status_not_match): """ Simple status helper. """ if scores == expected: return status_match else: return status_not_match
def array_equal(current_arr: list, new_arr: list) -> bool: """Test whether two seating arrangements are equal :param current_arr: Current seating arrangement :param new_arr: New seating arrangement :return: True if arrays are equal, False otherwise """ for i in range(len(current_arr)): ...
def _set_default_stats_options(stats_options): """Define some default summary statistics to display in estimation table.""" if stats_options is None: stats_options = { "n_obs": "Observations", "rsquared": "R$^2$", "rsquared_adj": "Adj. R$^2$", "resid_std_e...
def combine_lists(one_list): """ Combine a set of lists into one list. """ final_list = [] for l in one_list: final_list += l return final_list
def formatExc(exc): """ format the exception for printing """ try: return f"<{exc.__class__.__name__}>: {exc}" except: return "<Non-recognized Exception>"
def leaky_ReLU_1d(d, negSlope): """ one dimensional implementation of leaky ReLU """ if d > 0: return d else: return d * negSlope
def interval_overlap(a: int, b: int, x: int, y: int) -> int: """Returns by how much two intervals overlap assumed that a <= b and x <= y""" if b <= x or a >= y: return 0 elif x <= a <= y: return min(b, y) - a elif x <= b <= y: return b - max(a, x) elif a >= x and b <= y:...
def intervalComparison(x, lowerBound, upperBound): """ classify a value relative to the interval between two bounds: returns -1 when below the lower bound returns 0 when between the bounds (inside the interval) returns +1 when above the upper bound """ if (x < lowerBound): return -1 if (x > upperBound): return...
def get_finalscore(score, counter): """ sent when quiz completed and give final score """ return "Your final score is " +str(score) +" out of " +str(counter) + ". "
def partition(seq): """ pick the first element in seq as the pivot elements <= pivot goes to the left elements > pivot goest to the right return the left, pivot, right """ pivot, seq = seq[0], seq[1:] low = [x for x in seq if x <= pivot] high = [x for x in seq if x > pivot] retu...
def set(list, index, item): """ Return a list with the item at the specified index replaced with the given item. If the index is out of bounds, return the list unmodified. """ if list == () or index < 0: return list else: head, tail = list if index == 0: retu...
def quote(s, unsafe="/"): """Pass in a dictionary that has unsafe characters as the keys, and the percent encoded value as the value.""" res = s.replace("%", "%25") for c in unsafe: res = res.replace(c, "%" + (hex(ord(c)).upper())[2:]) return res
def firstLetter(text: str): """ Returns the first letter of every word in the `text`. """ return "".join(letter[0] for letter in text.split())
def pow(A, B, C): """pow(x, n) % d""" res = 1 % C while B > 0: if B & 1: # Odd res = (res * A) % C A = A**2 % C B >>= 1 return res
def none2Empty(value): """Answers an empty string if value is None, otherwise pass it through To make sure that 0 empty objects show as result.""" if value is None: return '' return value
def _is_zip_file(path): """Returns whether to treat the given file as a zip file.""" return path[-4:] in ('.zip')
def de_median_redshift(wavelength, median_z): """De-redshifts the same way as above Parameters: wavelength (array): wavelength values to convert median_z (int): redshift to change the wavelength by Returns: wavelength_red (array): redshifted wavelength """ wavelength_red = wavelength...
def mean(my_list): """ This function calculates the mean of a list Parameters ---------- my_list: list The list of numbers that we want to average Returns ------- mean_list : float The mean of the list Examples ------- >>> mean ([1,2,3,4,5]) 3.0 "...
def safe_string(msg): """ Make the string safe, by trying to convert each character in turn to string, replacing bad ones with ? """ def map_char(c): try: return str(c) except: return "?" return "".join(map_char(c) for c in msg)
def coullet(XYZ, t, a=0.8, b=-1.1, c=-0.45, d=-1): """ The Coullet Attractor. x0 = (0.1,0,0) """ x, y, z = XYZ x_dt = y y_dt = z z_dt = a * x + b * y + c * z + d * x**3 return x_dt, y_dt, z_dt
def lines_to_chars(text1, text2): """Split two texts into a list of strings. Reduce the texts to a string of dicts where each Unicode character represents one line. Args: text1: First string. text2: Second string. Returns: Three element tuple, containing the encoded text1, the...
def _to_absolute(detection, box): """Convert detection relative to box to absolute coordinates.""" x0, y0, x1, y1, p = detection bx0, by0, *_ = box return x0 + bx0, y0 + by0, x1 + bx0, y1 + by0, p
def update_entries(entries, new_entry): """Adds the new_entry to the entries. 1. If new_entry URL is already in there, do not add to the list. 2. It sorts the list according to the created date. """ if not any(d['created'] == new_entry['created'] for d in entries): entries.append(new_entry)...
def _alpn_list_to_str(alpn_list): """ Transform ['h2', 'http/1.1'] -> "h2;http/1.1" None is returned if list is None or empty """ if alpn_list: assert not isinstance(alpn_list, str) return ';'.join(alpn_list) return None
def search_tweets(api, keyword, date_start, lang): """Creates a query and searches for Tweets""" query = '%s %s' % (keyword, date_start) print('') print('Query created: %s' % query) print('Searching tweets...') searched_tweets = [] max_tweets = 20000 last_id = -1 while len(searche...
def _instance_callable(obj): """Given an object, return True if the object is callable. For classes, return True if instances would be callable.""" if not isinstance(obj, type): # already an instance return getattr(obj, '__call__', None) is not None # *could* be broken by a class overri...
def hamming(s1, s2): """Count the number of differing bits between two strings""" total = 0 for c1, c2 in zip(s1, s2): total += sum(((ord(c1)^ord(c2)) >> i) & 1 for i in range(8)) return total
def split_seconds_human_readable(seconds): """ splits the seconds argument into hour, minute, seconds, and fractional_seconds components. Does no formatting itself, but used by format_seconds_human_readable(...) for formatting seconds as a human-redable HH::MM:SS.FRACTIONAL time. """ if isinstance(...
def testif(b, testname, msgOK="", msgFailed=""): """Function used for testing. :param b: boolean, normaly a tested conditionL true if passed, false otherwise :param testname: the test name :param msgOK: string to be printed if param b==True ( test condition true ) :param msgFailed: string to be prin...
def get_current_line(target, mini): """ # xxx\n...min....\nxxx """ start = target.rfind("\n", 0, mini) +1 if start < 0: start = 0 end = target.find("\n", mini) if end < 0: end = len(target) return (start, end)
def build_response(session_attributes, speechlet_response): """ Build the full response JSON from the speechlet response """ return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response }
def to_int_keys_best(l): """ l: iterable of keys returns: a list with integer keys """ seen = set() ls = [] for e in l: if not e in seen: ls.append(e) seen.add(e) ls.sort() index = {v: i for i, v in enumerate(ls)} return [index[v] for v in l]
def height(node): """ compute the height of a binary tree """ if not node: return 0 else: # Compute the height of each subtree left_height = height(node.left) right_height = height(node.right) # Use the larger one if left_height > right_height: ...
def num_spectral_coeffs_up_to_order(b): """ The SO(3) spectrum consists of matrices of size (2l+1, 2l+1) for l=0, ..., b - 1. This function computes the number of elements in a spectrum up to (but excluding) b - 1. The number of elements up to and including order L is N_L = sum_{l=0}^L (2l+1)^2...
def eff_nocc(nelec, nspin, ispin): """ Find the number of effective electrons to indicate the Fermi level example: spin = 1 2 nelec 13(odd) 6.5 (up = 7, down = 6) 12(even) 6 (up = 6, down = 6) """ if nspin == 1: return...
def cardinalityGate(argumentValues,l,h): """ Method that evaluates the CARDINALITY gate @ In, argumentValues, list, list of values @ In, l, float, min number of allowed events @ In, h, float, max number of allowed events @ Out, outcome, float, calculated outcome of the gate """ nOcc = argument...
def create_dictionary(string, value): """ Creating dictionary based on string and value order args: string: string with comma seperated no spaces value: list of value to be assigned return: dictionary with {string-keys: value} example: create_di...
def char_waveform(length): """ Helper function for creating a char waveform PV. Args: length: The length of the array. Return: The dictionary to add to the PVDB. """ return {'type': 'char', 'count': length, 'value': [0]}
def max_depth(d): """Return maximum depth of given dict.""" return (0 if not isinstance(d, dict) or len(d) == 0 else 1 + max(max_depth(v) for v in d.values()))
def is_int(s: str) -> bool: """ A method to determine if the string is indeed an integer. Returns True if it is an integer, False otherwise """ try: return float(str(s)).is_integer() except: return False
def trim(text, max_length): """Trims text to be at most `max_length`, without splitting apart words.""" if len(text) <= max_length: return text text = text[:max_length + 1] # Trim until the last two characters are the boundary between an # alphanumeric character, and a non-alphanumeric cha...
def is_fill_request_el(obj): """Object contains executable methods 'fill' and 'request'.""" return hasattr(obj, 'fill') and hasattr(obj, 'request') \ and callable(obj.fill) and callable(obj.request)
def _should_update_date(verified_mode): """ Returns whether or not the verified mode should be updated. """ return not(verified_mode is None or verified_mode.expiration_datetime_is_explicit)
def is_list(obj): """Helper method to see if the object is a Python list. >>> is_list([4]) True """ return type(obj) is list
def getcolor(string, code): """Return a given string in color depending on the code provided. :param string: String to color. :param code: Corresponding ANSI escape code. :return: The colored string. """ return f"\u001b[0;3{code};40m{string}\u001b[0;0m"
def match(cmd, s): """ Check if cmd has the required parts of s and any of the optional part. """ parts = s.split('-') start = parts[0] if len(parts) > 1: end = parts[1] else: end = "" return cmd.startswith(start) and (start+end).startswith(cmd)
def _textDD(t): """t is a tuple (d, f)""" if 0 <= t[0] <= 360: dd = t[0] if 0.0 <= t[1] < 0.5: dd = 0.0 return '%02d0' % int((dd+5)/10.0) else: return ''
def filter_dict(d, keys): """Returns a dictionary which contains only the keys in the list `keys`.""" return {k: v for k, v in d.items() if k in keys}
def is_sequence(arg): """Return if an object is iterable (you can loop over it) and not a string.""" return (not hasattr(arg, "strip") and hasattr(arg, "__iter__"))
def domain_to_filename(domain): """All '/' are turned into '-', no trailing. schema's are gone, only the raw domain + ".txt" remains """ filename = domain.replace('/', '-') if filename[-1] == '-': filename = filename[:-1] filename += ".txt" return filename
def f2str(number, decimals, lt=None, gt=None): """ Formats a number to be displayed Parameters ---------- number : float number to be formatted decimals : float decimal points to be displayed lt : float or None gt : float or None Returns ------- f : str ...
def count_pages(s): """Attempt to compute the number of pages of an article.""" try: parts = s.split("-") return int(parts[1]) - int(parts[0]) except (AttributeError, IndexError, ValueError): return None
def reconstruct_path(came_from, current_node): """ came_from : dictionary of nodes and nodes before them in the shortest found path current_node : the last node of the path """ if current_node in came_from: p = reconstruct_path(came_from,came_from[current_node]) return p + [current_n...
def jaccard(x, y) -> float: """ Compute jaccard similarity (intersection over union). Args: x: Array-like object y: Array-like object Returns: Intersection Over Union score """ s1 = set(x) s2 = set(y) if len(s1) == 0 and len(s2) == 0: return 0 return...
def _get_hashable(v): """if a list - would cast to tuple""" if isinstance(v, list): return tuple(v) else: return v
def multiply(x, y): """Multiply x and y in GF(2^8).""" res = 0 for _ in range(8): if y & 0x1: res ^= x y = y >> 1 x = x << 1 if x & 0x100: x ^= 0x11B return res
def _flat(obj): """ :param obj: :return: Return a list """ if hasattr(obj, "js_dependencies"): return list(obj.js_dependencies) if isinstance(obj, (list, tuple, set)): return obj return (obj,)