content
stringlengths
42
6.51k
def isInt(input): """ This function check input is a integer value. :param input: unknown type object """ return isinstance(input, int)
def call_function(func, *args): """ helper for calling function, usually lambda functions """ return func(*args)
def from_question_name(name: str) -> str: """ Generates GIFT text for a question name. Parameters ---------- name : str Name of a question. Returns ------- out: str GIFT-ready question name. """ return f'::{name}::'
def isNormal( word, unique ): """ Determine if a word is "normal", that is it has 5-8 letters of the alphabet, or it includes q/x/z @param word The English word to calculate the difficulty of @param unique The number of unique letters in that word @returns true if t matches our definition of "normal", false otherwise """ if 'z' in word or 'x' in word or 'q' in word: return unique >= 5 return unique <= 8 and unique >=5
def toggle(byte: int, index: int) -> int: """Toggle bit at index.""" assert 0 <= byte <= 255 assert 0 <= index <= 7 return byte ^ (1 << index)
def find_exact_match(needle, sorted_haystack, lo=0, hi=None): """Returns haystack index of matching entry, or index before hole. """ haystack = sorted_haystack if hi is None: hi = len(haystack) assert len(haystack) > 0 if hi - lo == 1: return lo while hi - lo >= 2: mid = int((lo + hi) / 2) if haystack[mid] == needle: return mid if haystack[mid] < needle: lo = mid else: hi = mid assert hi - lo == 1, (hi, lo, needle) return lo
def get_leveshtein(s1, s2): """Returns levenshtein's length, i.e. the number of characters to modify to get a pattern string""" if s1 is None or s2 is None: return -1 if len(s1) < len(s2): return get_leveshtein(s2, s1) # len(s1) >= len(s2) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
def region_builder(data): """ Takes an instance of a ping result and builds a dictionary ready to display. The ping result returns the raw results. This function returns a dictionary with all the sections formatted. :param data: dic Result of ping call. :return dic Result of the ping ready to display. """ if len(data) == 1: return {'index': -1, 'region': data[0].ljust(4), 'average': '', 'maximum': '', 'color': '| color=#444'} index = float(data[1]) region_initials = '{region}:'.format(region=data[0].ljust(4)) average = '{average} {unit}'.format(average=data[1], unit=data[3]) maximum = '(max {maximum} {unit})'.format(maximum=data[2], unit=data[3]) if index < 100: color = '|color=#0A640C' # Green elif index < 150: color = '|color=#FEC041' # Yellow else: color = '|color=#FC645F' # Red return {'index': index, 'region': region_initials, 'average': average, 'maximum': maximum, 'color': color}
def init_parameters(parameter): """Auxiliary function to set the parameter dictionary Parameters ---------- parameter: dict See the above function NMFconv for further information Returns ------- parameter: dict """ parameter = dict() if not parameter else parameter parameter['numIter'] = 30 if 'numIter' not in parameter else parameter['numIter'] parameter['numComp'] = 3 if 'numComp' not in parameter else parameter['numComp'] parameter['numTemplateFrames'] = 8 if 'numIter' not in parameter else parameter['numTemplateFrames'] parameter['beta'] = 0 if 'beta' not in parameter else parameter['beta'] parameter['sparsityWeight'] = 0 if 'sparsityWeight' not in parameter else parameter['sparsityWeight'] parameter['uncorrWeight'] = 0 if 'uncorrWeight' not in parameter else parameter['uncorrWeight'] return parameter
def _get_scan_summary_totals(summary_totals: dict, title: str, warnings: list) -> str: """get text summary of summary dict""" totals_txt = f"{title}: {summary_totals['total']} " if summary_totals["total"] > 0: totals_txt += "(" breakdowns = [] for key in ["critical", "high", "medium", "low", "none", "na"]: if summary_totals[key] > 0: breakdowns.append(f"{key}:{summary_totals[key]}") if len(warnings) > 0: breakdowns.append("warnings:true") totals_txt += ", ".join(breakdowns) totals_txt += ")" return totals_txt
def disassemble(s): """ :param s: string :return: list of string """ str_lst = [] for chr in s: str_lst.append(chr) return str_lst
def temperature_ratio_across_normal_shock( mach_upstream, gamma=1.4 ): """ Computes the ratio of fluid temperature across a normal shock. Specifically, returns: T_after_shock / T_before_shock Args: mach_upstream: The mach number immediately before the normal shock wave. gamma: The ratio of specific heats of the fluid. 1.4 for air. Returns: T_after_shock / T_before_shock """ gm1 = gamma - 1 m2 = mach_upstream ** 2 return ( (2 * gamma * m2 - gm1) * (gm1 * m2 + 2) ) / ( (gamma + 1) ** 2 * m2 )
def boolean_to_xml(obj: bool) -> str: """ serialize a boolean to XML :param obj: boolean :return: string in the XML accepted form """ if obj: return "true" else: return "false"
def dict_diff(first, second): """ Return a dict of keys that differ with another config object. If a value is not found in one fo the configs, it will be represented by KEYNOTFOUND. @param first: Fist dictionary to diff. @param second: Second dicationary to diff. @return diff: Dict of Key => (first.val, second.val) """ diff = {} # Check all keys in first dict for key in first: if key not in second: diff[key] = (first[key], None) elif (first[key] != second[key]): diff[key] = (first[key], second[key]) # Check all keys in second dict to find missing for key in second: if key not in first: diff[key] = (None, second[key]) return diff
def a_from_pf(p): """Fractional amplitude of modulation from pulsed fraction If the pulsed profile is defined as p = mean * (1 + a * sin(phase)), we define "pulsed fraction" as 2a/b, where b = mean + a is the maximum and a is the amplitude of the modulation. Hence, a = pf / (2 - pf) Examples -------- >>> a_from_pf(1) 1.0 >>> a_from_pf(0) 0.0 """ return p / (2 - p)
def NFW_model(r3d_kpc, norm, rs): """ Compute a NFW model Parameters ---------- - r3d_kpc (kpc): array of radius - norm : the normalization - rs (kpc): characteristic radius parameter Outputs -------- - NFW model profile as a function of the input radius vector """ return norm / (r3d_kpc / rs) / (1 + (r3d_kpc / rs))**2
def cutR_seq(seq, cutR, max_palindrome): """Cut genomic sequence from the right. Parameters ---------- seq : str Nucleotide sequence to be cut from the right cutR : int cutR - max_palindrome = how many nucleotides to cut from the right. Negative cutR implies complementary palindromic insertions. max_palindrome : int Length of the maximum palindromic insertion. Returns ------- seq : str Nucleotide sequence after being cut from the right Examples -------- >>> cutR_seq('TGCGCCAGCAGTGAGTC', 0, 4) 'TGCGCCAGCAGTGAGTCGACT' >>> cutR_seq('TGCGCCAGCAGTGAGTC', 8, 4) 'TGCGCCAGCAGTG' """ complement_dict = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} #can include lower case if wanted if cutR < max_palindrome: seq = seq + ''.join([complement_dict[nt] for nt in seq[cutR - max_palindrome:]][::-1]) #reverse complement palindrome insertions else: seq = seq[:len(seq) - cutR + max_palindrome] #deletions return seq
def zeropad_1501(name): """ Arxiv IDs after yymm=1501 are padded to 5 zeros """ if not '/' in name: # new ID yymm, num = name.split('.') if int(yymm) > 1500 and len(num) < 5: return yymm + ".0" + num return name
def update(data): """Update the data in place to remove deprecated properties. Args: data (dict): dictionary to be updated Returns: True if data was changed, False otherwise """ changed = False for cfg_object in data.values(): externals = [] paths = cfg_object.pop('paths', {}) for spec, prefix in paths.items(): externals.append({ 'spec': str(spec), 'prefix': str(prefix) }) modules = cfg_object.pop('modules', {}) for spec, module in modules.items(): externals.append({ 'spec': str(spec), 'modules': [str(module)] }) if externals: changed = True cfg_object['externals'] = externals return changed
def decimal2dm(decimal_degrees): """ Converts a floating point number of degrees to the equivalent number of degrees and minutes, which are returned as a 2-element list. If 'decimal_degrees' is negative, only degrees (1st element of returned list) will be negative, minutes (2nd element) will always be positive. Example: >>> decimal2dm(121.135) [121, 8.100000000000307] >>> decimal2dm(-121.135) [-121, 8.100000000000307] """ degrees = int(decimal_degrees) minutes = abs(decimal_degrees - degrees) * 60 return [degrees, minutes]
def smallest_missing(arr: list) -> int: """ A modified version of binary search can be applied. If the number mid index == value, then the missing value is on the right, else on the left side. Time Complexity: O(log(n)) """ beg, end = 0, len(arr) - 1 while beg <= end: if arr[beg] != beg: return beg m = (beg + end) >> 1 if arr[m] == m: beg = m + 1 else: end = m - 1 return end + 1
def commands(message: dict) -> list: """ Extract commands from message """ def get_command(entity, text): offset = entity["offset"] length = entity["length"] return text[offset:offset + length] if not "entities" in message: return [] entities = [x for x in message["entities"] if x["type"] == "bot_command"] return [get_command(entity, message["text"]) for entity in entities]
def unique_dict_in_list(array): """Returns the unique dictionaries in the input list, preserving the original order. Replaces ``unique_elements_in_list`` because `dict` is not hashable. Parameters ---------- array: `List` [`dict`] List of dictionaries. Returns ------- unique_array : `List` [`dict`] Unique dictionaries in `array`, preserving the order of first appearance. """ if not array: return array result = [] # Brute force. # Avoids comparing json dumped ordered dictionary. # The reason is that when dictionary contains list/dict unhashable items, set does not work. for item in array: if not any([item == element for element in result]): result.append(item) return result
def validate_name(name): """ Function to validate input names""" if name.isalpha(): temp = name else: print("Invalid entry for name.\nName cannot contain special characters or numbers") temp = '$' return temp
def _sort_conf(key): """Use with sorted: return an integer value for each section in config.""" sections = {'queue': 1, 'jobs': 2, 'jobqueue': 3} return sections[key]
def BitValue(value, bitno): """ Returns the specific bit of a words value """ mask = 1 << bitno if (value & mask): return True else: return False
def make_distinct(label_lst): """ Make the label_lst distinct """ tag2cnt, new_tag_lst = {}, [] if len(label_lst) > 0: for tag_item in label_lst: _ = tag2cnt.setdefault(tag_item, 0) tag2cnt[tag_item] += 1 tag, wrd = tag_item new_tag_lst.append((tag, wrd, tag2cnt[tag_item])) assert len(new_tag_lst) == len(set(new_tag_lst)) return new_tag_lst
def generate_incbin_asm(start_address, end_address): """ Return baserom incbin text for an address range. Format: 'INCBIN "baserom.gbc", {start}, {end} - {start}' """ incbin = ( start_address, '\nINCBIN "baserom.gbc", $%x, $%x - $%x\n\n' % ( start_address, end_address, start_address ), end_address ) return incbin
def decompose_exec_yielddata(yield_data): """ Decompose ``Executor``s yield data, return a pair which contains remote host and its return context represent as ``(host, context)``. """ return yield_data.popitem()
def func(x): """ function to integrate: a 9th degree polynomial""" fx = x**9 + x**8 + x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x + 1 return fx
def varint_to_blob_length(l): """ Blob field lengths are doubled and 12 is added so that they are even and at least 12 """ if l == 0: return 0 else: return (l - 12) / 2
def convert_flags_to_boolean_dict(flags): """Return a dict with a key set to `True` per element in the flags list.""" return {f: True for f in flags}
def join(words, sep="", template="{word}"): """ Join an iterable of strings, with optional template string defining how each word is to be templated before joining. """ return sep.join(template.format(word=word) for word in words)
def get_key_by_value(dct, val): """ Gets key by value from input dictionary :param dct: input dictionary :type dct: dict :param val: value in input dictionary (MUST BE) :return: suitable key """ for item in dct.items(): if item[1] == val: return item[0]
def count(a_list): """ ================================================================================================= count(a_list) This function takes a list as input and counts the occurrences of each element of the list. ================================================================================================= Arguments: a_list -> A list with any type of items in it. The items in the dictionary will become the keys of the count dictionary. ================================================================================================= Returns: A dictionary where the keys are the elements of a_list and the values are the number of occurrences of that element in the list. ================================================================================================= """ # Initialize the counts dictionary counts = {} # and loop over the elements of a_lsit for item in a_list: # if the string of the item is not already a key in the list if str(item) not in list(counts.keys()): # then initialize a key in the counts dictionary with value 1 counts[str(item)] = 1 # Otherwise, the string of the item is already a key else: # so increase the count by one counts[str(item)] += 1 # and return the coutns dictionary after counting is complete. return counts
def entity_attributes_to_int(attributes: dict): """Convert entity attribute floats to int.""" for attr_name, attr_data in attributes.items(): if attr_name == "xy_color": continue if isinstance(attr_data, float): attributes[attr_name] = int(attr_data) elif isinstance(attr_data, list): for i, value in enumerate(attr_data): if isinstance(value, float): attr_data[i] = int(value) return attributes
def Binary_Search(Arr, find): """ type Arr: list[int] type find: int """ left = 0 right = len(Arr)-1 while(left <= right): mid = (left + right)//2 if( Arr[mid] == find): return mid elif(Arr[mid] < find): left = mid + 1 else: right = mid - 1 return -1
def label_2_float(x, bits): """Convert integer numbers to float values Note: dtype conversion is not handled Args: ----- x: data to be converted Tensor.long or int, any shape. bits: number of bits, int Return: ------- tensor.float """ return 2 * x / (2 ** bits - 1.) - 1.
def get_unique_groups(input_list): """Function to get a unique list of groups.""" out_list = [] for item in input_list: if item not in out_list: out_list.append(item) return out_list
def get_scan_resource_label(system_type: str) -> str: """ Given a system type, returns the label to use in scan output """ resource_label_map = { "redshift_cluster": "Redshift Cluster", "rds_instance": "RDS Instance", "rds_cluster": "RDS Cluster", } resource_label = resource_label_map.get(system_type, "Unknown") return resource_label
def filter_null(settings, null='__null__'): """Replace null values with None in provided settings dict. When storing values in the peer relation, it might be necessary at some future point to flush these values. We therefore need to use a real (non-None or empty string) value to represent an unset settings. This value then needs to be converted to None when applying to a non-cluster relation so that the value is actually unset. """ filtered = {} for k, v in settings.items(): if v == null: filtered[k] = None else: filtered[k] = v return filtered
def _is_pixel(item): """ Returns True if item is a pixel, False otherwise. A pixel is a tuple of 3 ints in the range 0..255 Parameter item: The item to check Precondition: NONE (item can be anything)( """ if type(item) != tuple or len(item) != 3: return False for ii in range(3): if type(item[ii]) != int or item[ii] < 0 or item[ii] > 255: return False return True
def compareTime(time_A, time_B): """ input: string, string output: boolean description: compare time, time_A >= time_B is True """ if time_A >= time_B: return True else: return False
def adjust_r2(r2, n, k): """ https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2 :param r2: R2 score (unadjusted yet) :param n: Number of samples :param k: Number of features :return: Adjusted R2 score """ nom = (1-r2) * (n-1) denom = n-k-1 if denom <= 0: raise ValueError('At least ' + str(k+2) + ' samples needed to calculate adjusted R2 score') return 1 - (nom/denom)
def _strip_comment(string, comment_characters=('!', ), quote_characters=('"', "'")): """ Return the string only until the first comment (if any), but makes sure to ignore comments if inside a string Note: it expects to get a SINGLE line, without newline characters Note: it does not cope with escaping of quotes :param string: the string to check :param comment_characters: a list or tuple of accepted comment characters :param quote_characters: a list or tuple of accepted valid string characters """ new_string = [] # Will contain individual charachters of the new string in_string = False string_quote = None # Will contain the specific character used to enter # this string: this avoids that 'aaa" is considered as # the string containing the three characters aaa for char in string: if char == '\n': raise ValueError( "I still cannot cope with newlines in the string...") # Check if we are entering/existing a string if in_string and char == string_quote: #print("EXIT") in_string = False string_quote = None elif not in_string and char in quote_characters: #print("ENTER") in_string = True string_quote = char #print(char, in_string, string_quote) # We found a comment, return until here (without the comment) if not in_string and char in comment_characters: return "".join(new_string) new_string.append(char) # If we are here, no comments where found if in_string: raise ValueError( "String >>{}<< is not closed, it was open with the {} char".format( string, string_quote)) # I just return the same string, even if this would be equivalent to "".join(new_string) return string
def str_join(sep, ls): """Return a joined string of all the members of the list converted in strings""" return sep.join(str(l) for l in ls)
def coord(x, y, unit=1): """ Converts pdf spacing co-ordinates to metric. """ x, y = x * unit, y * unit return x, y
def GetPipelineResultsPathInGCS(artifacts_path): """Gets a full Cloud Storage path to a pipeline results YAML file. Args: artifacts_path: string, the full Cloud Storage path to the folder containing pipeline artifacts, e.g. 'gs://my-bucket/artifacts'. Returns: A string representing the full Cloud Storage path to the pipeline results YAML file. """ return '{0}/results/results.yaml'.format(artifacts_path)
def to_applescript(pyList): """Delimit a list into a string value for AppleScript parsing.""" final_ls = [] for ls_item in pyList: if isinstance(ls_item, list): ls_item = to_applescript(ls_item) final_ls.append(ls_item) pyStr = "|".join(str(item) for item in final_ls) return "{" + pyStr + "}"
def _get_subjects_and_metrics_by_tag(data_model, reports, tag: str): """Return all subjects and metrics that have the tag.""" subjects = {} for report in reports: for subject_uuid, subject in list(report.get("subjects", {}).items()): for metric_uuid, metric in list(subject.get("metrics", {}).items()): if tag not in metric.get("tags", []): del subject["metrics"][metric_uuid] if subject.get("metrics", {}): subject_name = subject.get("name") or data_model["subjects"][subject["type"]]["name"] subject["name"] = report["title"] + " / " + subject_name subjects[subject_uuid] = subject return subjects
def format_comment_title(product): """Produce a Markdown-formatted string based on a given "product"--a string containing a browser identifier optionally followed by a colon and a release channel. (For example: "firefox" or "chrome:dev".) The generated title string is used both to create new comments and to locate (and subsequently update) previously-submitted comments.""" parts = product.split(":") title = parts[0].title() if len(parts) > 1: title += " (%s channel)" % parts[1] return "# %s #" % title
def getPrevRecord(records, index): """ Attempts to get the chronologically previous record :param records: <list[recorder.Record|(str)]> list of records (type doesn't matter) :param index: <int> index value of starting record (index - 1 should be the previous record) :return: <recorder.Record|(str) or None> previous record from list (returns whatever the list element type is) """ try: # if the previous index is a valid index if index - 1 >= 0: # return the previous record return records[index - 1] except IndexError: pass # if returning the prev record was unsuccessful, return None return None
def my_map(function, arg_list): """ this is map(int,input()) wala function takes function as 1st argument and iterate all element of list through that function""" result=[function(i) for i in arg_list] return result
def import_dotted_name(name): """Get an object by its "dotted name", a string representing its import location. The last dot can also be a colon instead. .. versionadded:: 0.6 """ name = str(name) if ':' in name: module, obj = name.split(':', 1) elif '.' in name: module, obj = name.rsplit('.', 1) else: return __import__(name, level=0) mod = __import__(module, fromlist=[obj], level=0) return getattr(mod, obj)
def parse_hosts(conf): """ From a parsed hosts file, loop through all the nodes and get the actual hosts from each line """ parsed_hosts = {} if not conf: return parsed_hosts for section in conf.sections: parsed_hosts[section] = []
def breakfast(ham: str, eggs: str = 'eggs') -> str: """Breakfast creator. This function has a positional argument, a keyword argument, and the return value annotated. """ return ham + ' and ' + eggs
def integer(input): """Convert the given input to an integer value. :param input: the value to convert to an integer :type input: any :returns: converted integer value :rtype: int """ try: return int(input) except (TypeError, ValueError): raise ValueError("Unable to convert {0!r} to an integer value.".format(input))
def f1_scores(detected, ground_truth): """ Calculates the f1-scores for the given sets - 'detected' is a set containing the timestamps for all detected anomalies - 'ground_truth' is a set containing the timestamps for all known anomalies """ # Calculate the true positives, false positives and false negatives # For more information, see: https://en.wikipedia.org/wiki/Precision_and_recall TP = (detected & ground_truth) FP = float(len(detected - TP)) FN = float(len(ground_truth - TP)) TP = float(len(TP)) try: precision = TP / (TP + FP) except ZeroDivisionError: precision = float('nan') try: recall = TP / (TP + FN) except ZeroDivisionError: recall = float('nan') try: f1_score = (2*TP)/((2*TP) + FP + FN) except ZeroDivisionError: f1_score = float('nan') return precision, recall, f1_score
def results_to_list(results): """ convert api response to a list :param results:dict resultset form athena :return:list """ columns = [ col['Label'] for col in results['ResultSet']['ResultSetMetadata']['ColumnInfo']] listed_results = [] for res in results['ResultSet']['Rows'][0:]: values = [] for field in res['Data']: try: values.append(list(field.values())[0]) except Exception: values.append(list(' ')) listed_results.append(dict(list(zip(columns, values)))) return listed_results
def secondary_training_status_changed(current_job_description, prev_job_description): """Returns true if training job's secondary status message has changed. Args: current_job_description: Current job description, returned from DescribeTrainingJob call. prev_job_description: Previous job description, returned from DescribeTrainingJob call. Returns: boolean: Whether the secondary status message of a training job changed or not. """ current_secondary_status_transitions = current_job_description.get("SecondaryStatusTransitions") if ( current_secondary_status_transitions is None or len(current_secondary_status_transitions) == 0 ): return False prev_job_secondary_status_transitions = ( prev_job_description.get("SecondaryStatusTransitions") if prev_job_description is not None else None ) last_message = ( prev_job_secondary_status_transitions[-1]["StatusMessage"] if prev_job_secondary_status_transitions is not None and len(prev_job_secondary_status_transitions) > 0 else "" ) message = current_job_description["SecondaryStatusTransitions"][-1]["StatusMessage"] return message != last_message
def cents_to_dollars(cents): """ Convert cents to dollars. :param cents: Amount in cents :type cents: int :return: float """ return round(cents / 100.0, 2)
def decode_string(val: bytes) -> str: """Decodes a possibly null terminated byte sequence to a string using ASCII and strips whitespace.""" return val.partition(b'\x00')[0].decode('ascii').strip()
def link(gsheet_key): """Return GSheet URL for data from Web UI.""" return 'https://docs.google.com/spreadsheets/d/%s/edit' % gsheet_key
def AuthorToJSON(author): """ Converts an Author object into a JSON-compatible dictionary. Returns None on failure. """ if not author: return None try: json_dict = { "type":"author", "id":author.url, "host":author.host, "displayName":author.username, "url":author.url, "github":author.github } return json_dict except: return None
def factorials(number: int, iteratively=True) -> int: """ Calculates factorials iteratively as well as recursively. Default iteratively. Takes linear time. Args: - ``number`` (int): Number for which you want to get a factorial. - ``iteratively`` (bool): Set this to False you want to perform a recursion factorial calculation. By default calculates iteratively """ if iteratively: if not (isinstance(number, int) and number >= 0): # Raise non negative number error raise ValueError("'number' must be a non-negative integer.") result = 1 if number == 0: return 1 for i in range(2, number+1): result *= i return result else: # If user want's to perform a recursive factorial calculation if not (isinstance(number, int) and number >= 0): # Raise non negative number error raise ValueError("'number' must be a non-negative integer.") if number == 0: return 1 result = number * factorials(number - 1) return result
def compatibility_layer(spec): """Make specs compatible with older versions of Connexion.""" if not isinstance(spec, dict): return spec # Make all response codes be string. # Most people use integers in YAML for status codes, # we don't want to annoy them by saying "response codes must be strings" for path_name, methods_available in spec.get('paths', {}).items(): for method_name, method_def in methods_available.items(): if (method_name == 'parameters' or not isinstance( method_def, dict)): continue response_definitions = {} for response_code, response_def in method_def.get( 'responses', {}).items(): response_definitions[str(response_code)] = response_def method_def['responses'] = response_definitions return spec
def evaluate(bounds, func): """ Evaluates simpsons rules on an array of values and a function pointer. .. math:: \int_{a}^{b} = \sum_i ... Parameters ---------- bounds: array_like An array with a dimension of two that contains the starting and ending points for the integrand. func: function A function being evaluted in this integral Returns ------- integral: float The integral of function (func) between the bounds """ if len(bounds) != 2: raise ValueError("Bounds should be a length of two, found %d." % len(bounds)) a = float(bounds[0]) b = float(bounds[1]) ya = func(a) yb = func((a + b) / 2) yc = func(b) I = (b - a) * (ya + 4 * yb + yc) / 6.0 return I
def is_container(obj): """ Test if an object is a container (iterable) but not a string """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
def num_elements(num): """Return either "1 element" or "N elements" depending on the argument.""" return '1 element' if num == 1 else '%d elements' % num
def mapping_fields(mapping, parent=[]): """ reads an elasticsearh mapping dictionary and returns a list of fields cojoined with a dot notation args: obj: the dictionary to parse parent: name for a parent key. used with a recursive call """ rtn_obj = {} for key, value in mapping.items(): new_key = parent + [key] new_key = ".".join(new_key) rtn_obj.update({new_key: value.get('type')}) if value.get('properties'): rtn_obj.update(mapping_fields(value['properties'], [new_key])) elif value.get('fields'): rtn_obj.update(mapping_fields(value['fields'], [new_key])) rtn_obj[new_key] = [rtn_obj[new_key]] + \ list(value['fields'].keys()) return rtn_obj
def convert_byte32_arr_to_hex_arr(byte32_arr): """ This function takes in an array of byte32 strings and returns an array of hex strings. Parameters: byte32_arr Strings to convert from a byte32 array to a hex array """ hex_ids = [] for byte32_str in byte32_arr: hex_ids = hex_ids + [byte32_str.hex()] return hex_ids
def ten(val): """ Converts a sexigesmal number to a decimal Input Parameters ---------------- val : str, list, numpy.ndarray A sexigesimal number that is a colon-delimited string or 3-element list of numpy.npdarray Returns -------- float The decimal number Procedure --------- Based on the IDL Astronomy User's Library sixty program. Basic manipulation and formating Examples -------- > x = '-00:00:40.04424' > ten(x) -0.0111234 > x = [-0.0,0.0,40.04424] > ten(x) -0.0111234 > x = [0.0,0.0,-40.04424] > ten(x) -0.0111234 > import numpy as np > x = np.array([-0.0,0.0,40.04424]) > ten(x) -0.0111234 > import numpy as np > x = np.array([0.0,0.0,-40.04424]) > ten(x) -0.0111234 Modification History -------------------- 2022-05-24 - Written by M. Cushing, University of Toledo. """ # Figure out what the name is typ = type(val).__name__ # String input if typ == 'str': hms=(val.split(':')) decimal = abs(float(hms[0]))+float(hms[1])/60.+float(hms[2])/3600. # Grab the first element of the string to test for positivity posneg = hms[0][0] if posneg == '+': return(decimal) elif posneg == '-': return(-1*decimal) else: return(decimal) # A list of numpy array elif typ == 'list' or typ == 'ndarray': # Convert to positive (to deal with things like [-0.0,0.0.40] decimal = abs(float(val[0])+float(val[1])/60.+float(val[2])/3600.) # Check for negative prod = val[0]*val[1]*val[2] if prod == -0.0: decimal *=-1 return(decimal)
def clean_name(name: str) -> str: """Return a string with correct characters for a cell name. [a-zA-Z0-9] FIXME: only a few characters are currently replaced. This function has been updated only on case-by-case basis """ replace_map = { " ": "_", "!": "_", "#": "_", "%": "_", "(": "", ")": "", "*": "_", ",": "_", "-": "m", ".": "p", "/": "_", ":": "_", "=": "", "@": "_", "[": "", "]": "", } for k, v in list(replace_map.items()): name = name.replace(k, v) return name
def as_list(x): """A function to convert an item to a list if it is not, or pass it through otherwise Parameters ---------- x : any object anything that can be entered into a list that you want to be converted into a list Returns ------- list a list containing x """ if not isinstance(x, list): return [x] else: return x
def unique(in_list: list) -> list: """Return a list with only unique elements.""" return list(set(in_list))
def col_index(s_i: int) -> int: """col index [0, 1, ... 8] on the 9x9 board from the state index [0, 1, ... 80]""" return 3 * ((s_i // 9) % 3) + s_i % 3
def makeFileName(name): """Makes a string serve better as a file name.""" return (name .encode('ascii', 'replace') .decode('ascii') .replace('?', '_') .replace('/', '_'))
def expand_word_graph(word_graph): """Expands word graph dictionary to include all words as keys.""" expanded_word_graph = word_graph.copy() for word1 in word_graph: for word2 in list(word_graph[word1]): expanded_word_graph[word2] = (expanded_word_graph.get(word2, set()) | set([word1])) return expanded_word_graph
def get_max_firing_rate(spiketrains): """ Get maximum firing rate :param spiketrains: :return: """ if spiketrains is None or spiketrains == 0: return 0 max_val = -1000000 for spiketrain in spiketrains: if len(spiketrain) > max_val: max_val = len(spiketrain) return max_val
def parse_url(url): """ Returns username from url """ return url.split('/')[-1].split('?')[0]
def calc_delay(delay, computed_exposure, num): """Calculate the real delay time. Return a dictionary of metadata.""" real_delay = max(computed_exposure, delay) print( "INFO: requested delay = {}s -> computed delay = {}s".format( delay, real_delay ) ) delay_md = { "sp_requested_delay": delay, "sp_requested_num": num, "sp_computed_delay": real_delay, } return delay_md
def class_filter(classes, class_name): """ Filter classes by comparing two lists. :param classes: confusion matrix classes :type classes: list :param class_name: subset of classes list :type class_name: list :return: filtered classes as list """ result_classes = classes if isinstance(class_name, list): if set(class_name) <= set(classes): result_classes = class_name return result_classes
def parse_int_list(text): """Parse a string into a list of integers For example, the string "1,2,3,4" will be parsed to [1, 2, 3, 4]. Parameters ---------- text : str String to parse Returns ------- List[int] Parsed integer list """ result = [int(i) for i in text.split(',')] return result
def max_factor(x: int, y: int) -> int: """ Find the maximum `d` such that `x % d == 0` and `d <= y`. """ if x <= y: return x result = 1 for d in range(2, min(int(x**0.5), y) + 1): inv_d = x // d if inv_d * d == x: if inv_d <= y: return inv_d result = d return result
def get_query_params_str(params: dict, array_type_params: dict) -> str: """ Used for API queries that include array type parameters. Passing them in a dictionary won't work because their keys must be equal which is not possible in python dictionaries, thus we will eventually pass the parameters in the URL itself. Example: Because we can't pass {"a": "0", "a": "1"} as a dict to the params argument of the request function, we will pass the parameters as a part of the URL suffix: ?a=0&a=1. Args: params: string/integer parameters array_type_params: array type parameters Returns: (str) The query params string, which will be appended to the API request URL suffix. """ query_params_str = '&'.join([f'{k}={v}' for k, v in params.items()]) for array_type_param, values in array_type_params.items(): curr_param_str = '&'.join([f'{array_type_param}={v}' for v in values]) query_params_str += '&' + curr_param_str return query_params_str
def find_in_list_of_list(list_, item): """ Example: Arguments: list_: [[0,1],[2,3]] item: 2 Returns: (1,0) """ for sub_list in list_: if item in sub_list: return (list_.index(sub_list), sub_list.index(item)) raise ValueError("'{}' is not in list".format(item))
def _get_coords(lat, lng, factor, order="lnglat"): """Determines coordinate order.""" if order not in ("lnglat", "latlng"): raise ValueError(f"order must be either 'latlng' or 'lnglat', not {order}.") return (lat / factor, lng / factor) if order == "latlng" else (lng / factor, lat / factor)
def extract_single_worded_key(dictionary, key): """ verify that key is in dictionary and its value is a single word """ if key in dictionary: value = dictionary[key] if len(value.split()) == 1: return value raise RuntimeError('\'{}\' of injected file must be a single word, but got {}: \'{}\'' .format(key, len(value.split()), value)) raise RuntimeError('\'{}\' is not specified for injected file \'{}\' !' .format(key, dictionary))
def formatDollars(d,noneValue='',zeroValue='$0'): """Formats a number as a whole dollar value with alternatives for None and 0.""" if d is None: return noneValue elif d==0: return zeroValue return '${:.0f}'.format(d)
def vect_prod_s(_V1, _V2): """ Returns scalar product of vectors V1 and V2 """ sizeV1 = len(_V1) sizeV2 = len(_V2) sizeV = sizeV1 if(sizeV1 < sizeV2) else sizeV2 res = 0 for i in range(sizeV): res += _V1[i]*_V2[i] return res
def islist(obj): """ islist """ return isinstance(obj, list)
def safe_iterator(node, tag=None): """Return an iterator that is compatible with Python 2.6""" if node is None: return if hasattr(node, "iter"): return node.iter(tag) else: return node.getiterator(tag)
def print_pstats_list(pstats, pformat=None): """Print list of pstats dict formatted :param list pstats: pstats dicts to print :param str format: String.format style to show fields with keys: ncalls, tottime, tt_percall, cumtime, ct_percall, file, lineno, method rcalls, calls :return: Directly print of result formatted and return True""" if not pstats: return False if pformat is None: pformat = ("{method:<40s} {factor:>16s} {cumtime:>10s} " "{calls:>10s} {rcalls:>10s} {tottime:>10s} " "{tt_percall:>10s} {ct_percall:>10s} " "<{file}:{lineno}") for pstat_line in [dict(zip(pstats[0].keys(), pstats[0].keys()))] + pstats: print(pformat.format(**pstat_line)) return True
def unpack(value): """ Return a three tuple of data, code, and headers :param value: :return: """ if not isinstance(value, tuple): return value, 200, {} try: data, code, headers = value return data, code, headers except ValueError: pass try: data, code = value return data, code, {} except ValueError: pass return value, 200, {}
def complex_to_xy(complex_point): """turns complex point (x+yj) into cartesian point [x,y]""" xy_point = [complex_point.real, complex_point.imag] return xy_point
def _like_rnncell(cell): """Checks that a given object is an RNNCell by using duck typing.""" conditions = [ hasattr(cell, "output_size"), hasattr(cell, "state_size"), hasattr(cell, "zero_state"), callable(cell), ] return all(conditions)
def shifted(x): """Shift x values to the range [-0.5, 0.5)""" return -0.5 + (x + 0.5) % 1
def lexicographic_order(array): """MSD radix sort.""" def lex_r(array, k): buckets = [[] for _ in range(27)] for elem in array: if not k < len(elem): buckets[0].append(elem) else: buckets[ord(elem[k]) - ord('a') + 1].append(elem) for i in range(1, 27): if len(buckets[i]) > 1: buckets[i] = lex_r(buckets[i], k + 1) result = [] for bucket in buckets: result += bucket return result return lex_r(array, 0)
def plot_poly(ploty, poly): """ Taken from the materials and modified. Returns a set of plotx points calulated from the polynomial and input ploty data. """ fit_success = False try: plotx = poly[0]*ploty**2 + poly[1]*ploty + poly[2] fit_success = True except TypeError: # Avoids an error if poly is still none or incorrect print('The function failed to fit a line!') plotx = 1*ploty**2 + 1*ploty return plotx, fit_success
def get_permutations(sequence): """ Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations of sequence Example: >>> get_permutations('abc') ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Note: depending on your implementation, you may return the permutations in a different order than what is listed here. """ # Base case - single character is the only permutation of itself if len(sequence) == 1: return list(sequence) # Recursive case first_character = sequence[0] permutations = [] candidates = get_permutations(sequence[1:]) for candidate in candidates: for position in range(len(candidate) + 1): permutations.append( candidate[:position] + first_character + candidate[position:]) return permutations