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 othe...
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: m...
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...
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...
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 para...
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"...
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. ...
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 =...
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) Exam...
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 """ ...
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 pa...
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.p...
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 ...
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...
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 m...
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 ------- uniqu...
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(...
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 ) ...
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. ===============================================================...
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 isinstan...
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 ...
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...
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 = resou...
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 sett...
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...
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: ...
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 ...
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 ...
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",...
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 an...
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> p...
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, ob...
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("...
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 ...
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']['Ro...
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 descri...
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...
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...
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 s...
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 int...
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, val...
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...
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 numb...
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 = { " ": "_", "!": "_", "#": "_",...
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 ...
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()) ...
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) ...
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 = { ...
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 isins...
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 te...
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 ...
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 t...
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("'{...
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, bu...
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: Dir...
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: ...
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) f...
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: ...
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...