content
stringlengths
42
6.51k
def is_prime(n): """Returns True if n is prime and False otherwise""" if n == 1: return False # check for all numbers up to sqrt(n) whether they divide n for divider in range(2, int(n ** 0.5) + 1): if n % divider == 0: # if a divider is found, immediately return False return False # we only get here if no divider has been found --> n is prime return True
def merge_dicts(*dict_args): """ Efficiently merges arbitrary number of dicts, giving precedence to latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def get_legacy_qos_policy(extra_specs): """Return legacy qos policy information if present in extra specs.""" external_policy_name = extra_specs.get('netapp:qos_policy_group') if external_policy_name is None: return None return dict(policy_name=external_policy_name)
def params_to_string(params_num) -> str: """ :param params_num: :type params_num: :return: :rtype:""" if params_num // 10 ** 6 > 0: return str(round(params_num / 10 ** 6, 2)) + " M" elif params_num // 10 ** 3: return str(round(params_num / 10 ** 3, 2)) + " k" else: return str(params_num)
def get_prefix(filename): """ Get the name of the file without the extension """ return filename.split(".")[0]
def FindMatch(data, name): """Tries to find an item in a dictionary matching a name. Callers have to ensure the data names aren't contradictory (e.g. a regexp that matches a string). If the name isn't a direct key, all regular expression objects in the dictionary are matched against it. @type data: dict @param data: Dictionary containing data @type name: string @param name: Name to look for @rtype: tuple; (value in dictionary, matched groups as list) """ if name in data: return (data[name], []) for key, value in data.items(): # Regex objects if hasattr(key, "match"): m = key.match(name) if m: return (value, list(m.groups())) return None
def task_key(task): """Return a sort key for a given task.""" function, args = task return function.__name__, args
def comp(z1, z2, tol): """Return a bool indicating whether the error between z1 and z2 is <= tol. If z2 is non-zero and ``|z1| > 1`` the error is normalized by ``|z1|``, so if you want the absolute error, call this as ``comp(z1 - z2, 0, tol)``. """ if not z1: z1, z2 = z2, z1 if not z1: return True diff = abs(z1 - z2) az1 = abs(z1) if z2 and az1 > 1: return diff/az1 <= tol else: return diff <= tol
def find_missing(ar_prog): """Finds missing item in the arithmetic progression.""" # The sum of terms of arithmetic progression is: # S = n*(a1 + an)/2 # where in our case since 1 item is missing n = len(ar_prog) +1 sum_complete = (len(ar_prog) + 1)*(ar_prog[0] + ar_prog[-1])/2 sum_current = sum(ar_prog) return sum_complete - sum_current
def sensitivity_formula(counts): """Return sensitivity counts: dict of counts, containing at least TP and FN """ tp = counts['TP'] fn = counts['FN'] if not tp and not fn: return 0.0 sensitivity = tp/(tp + fn) return sensitivity
def re_sub_escape(pattern): """ Escape the replacement pattern for a re.sub function """ return pattern.replace(u"\\", u"\\\\").replace(u"\n", u"\\n").replace( u"\r", u"\\r").replace(u"\t", u"\\t").replace(u"\f", u"\\f")
def clean_text_up(text: str) -> str: """ Remove duplicate spaces from str and strip it. """ return ' '.join(text.split()).strip()
def from_html(html_color): """ Converts an HTML color string like FF7F00 or #c0ffee to RGB. """ num = int(html_color.lstrip('#'), 16) return [num // 65536, (num // 256) % 256, num % 256]
def find_fcb_offset(content): """ Find Flash Control Block offset @return int offset >=0 on success, -1 if an error occured. """ try: index = content.index(b'FCB ') if (index > 4): return (index-4) return -1 except ValueError as exc: return -1
def isQualifiedActor(stringList): """ Determine if cast member is relevant to our search Example stringList: (nconst, primaryName, birthYear, deathYear, primaryProfession, knownForTitles) ["nm0000004", "John Belushi", "1949", "1982", "actor,soundtrack,writer", "tt0078723,tt0072562,tt0077975,tt0080455"] """ notKnownForAnything = stringList[-1] == '\\N' notAnActor = 'actor' not in stringList[-2] isDead = stringList[-3].isdigit() hasNoBirthYear = stringList[-4] == '\\N' firstOrLastNameIsANumber = stringList[1].isdigit() or stringList[-5].isdigit() if notKnownForAnything or notAnActor or isDead or hasNoBirthYear or firstOrLastNameIsANumber: return False else: return True
def compsort(q): """sorting function, by just comparing elements to elements, requires implementation of __gt__. Probably not the fastest version (n**2)""" ret=[] for j,qq in enumerate(q): for i,k in enumerate(ret): if k>qq: ret.insert(i,qq) break if len(ret)<=j:ret.append(qq) return ret
def replace_all(text, subst): """ Perform the substitutions given by the dictionary ``subst`` on ``text``. """ for old in subst.keys(): text = old.sub(subst[old], text) return text
def normalise(word): """Normalises words to lowercase and stems and lemmatizes it.""" word = word.lower() #word = stemmer.stem(word) #word = lemmatizer.lemmatize(word) return word
def check_valid_timestamp( timestamp=None): """Function check_valid_timestamp Check for the correct format of string timestamp with format <date>_<time> :param timestamp: A string timestamp (any format) :return bool: True if pattern follows <date>_<time>, otherwise False """ #Check a valid timestamp scheme input # <date (YYMMDD)>_<time (hh:mm)> ts_valid = False if timestamp != None: ts = timestamp.split("_") if len(ts) == 2 and len(ts[0]) == 6 and len(ts[1]) == 4: ts_valid = True return ts_valid
def swap_diff(start, goal, limit): """A diff function for autocorrect that determines how many letters in START need to be substituted to create GOAL, then adds the difference in their lengths. """ def helper_function(tally, i): if limit < tally: #stop when reach the limit! return tally elif len(goal) == i or len(start) == i: #stop when reach the length return tally + abs(len(start) - len(goal)) elif goal[i] == start[i]: #check every character return helper_function(tally,i+1) #next char else: return helper_function(tally+1,i+1) #count diff and next char return helper_function(0,0)
def to_minutes(chrono): """convert seconds to minute display""" return f"{int(float(chrono)/60)}:{round(float(chrono) - (float(chrono) // 60) * 60, 2)}"
def binary_superposition_mop_r_3(ar_1, ar_2: tuple, mop): """substitution for unary multioperations. :param ar_1: multioperation which. :param tuple ar_2: multioperation which. :param tuple mop: multioperation for :rtype: tuple """ dic_mop = { 1: (0,), 2: (1,), 3: (0, 1), 4: (2,), 5: (0, 2), 6: (1, 2), 7: (0, 1, 2) } a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9 = 0, 0, 0, 0, 0, 0, 0, 0, 0 if ar_1[0] != 0 and ar_2[0] != 0: for x in dic_mop[ar_1[0]]: for y in dic_mop[ar_2[0]]: a_1 = a_1 | mop[x * 3 + y] if ar_1[1] != 0 and ar_2[1] != 0: for x in dic_mop[ar_1[1]]: for y in dic_mop[ar_2[1]]: a_2 = a_2 | mop[x * 3 + y] if ar_1[2] != 0 and ar_2[2] != 0: for x in dic_mop[ar_1[2]]: for y in dic_mop[ar_2[2]]: a_3 = a_3 | mop[x * 3 + y] if ar_1[3] != 0 and ar_2[3] != 0: for x in dic_mop[ar_1[3]]: for y in dic_mop[ar_2[3]]: a_4 = a_4 | mop[x * 3 + y] if ar_1[4] != 0 and ar_2[4] != 0: for x in dic_mop[ar_1[4]]: for y in dic_mop[ar_2[4]]: a_5 = a_5 | mop[x * 3 + y] if ar_1[5] != 0 and ar_2[5] != 0: for x in dic_mop[ar_1[5]]: for y in dic_mop[ar_2[5]]: a_6 = a_6 | mop[x * 3 + y] if ar_1[6] != 0 and ar_2[6] != 0: for x in dic_mop[ar_1[6]]: for y in dic_mop[ar_2[6]]: a_7 = a_7 | mop[x * 3 + y] if ar_1[7] != 0 and ar_2[7] != 0: for x in dic_mop[ar_1[7]]: for y in dic_mop[ar_2[7]]: a_8 = a_8 | mop[x * 3 + y] if ar_1[8] != 0 and ar_2[8] != 0: for x in dic_mop[ar_1[8]]: for y in dic_mop[ar_2[8]]: a_9 = a_9 | mop[x * 3 + y] return a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9
def trim_hash(commit): """Trim a commit hash to 8 characters.""" return commit[:8]
def flatten_dict(input_, prefix=None, join_with=".", filter_none=True): """ Flatten a dictionary """ if prefix is None: prefix = [] if isinstance(input_, list): result = {} for v in input_: result.update(flatten_dict(v, prefix, join_with, filter_none)) return result if isinstance(input_, dict): result = {} for k, v in input_.items(): prefix.append(k) result.update(flatten_dict(v, prefix, join_with, filter_none)) prefix.pop() return result if filter_none is True and input_ is None: return {} return {join_with.join(prefix): input_}
def recursive_len(item): """Calculate the number of elements in nested list Args: item (list): list of lists (i.e. nested list) Returns: Total number of elements in nested list """ if type(item) == list: return sum(recursive_len(subitem) for subitem in item) else: return 1
def chunked(data, chunksize): """ Returns a list of chunks containing at most ``chunksize`` elements of data. """ if chunksize < 1: raise ValueError("Chunksize must be at least 1!") if int(chunksize) != chunksize: raise ValueError("Chunksize needs to be an integer") res = [] cur = [] for e in data: cur.append(e) if len(cur) >= chunksize: res.append(cur) cur = [] if cur: res.append(cur) return res
def IsNumber(s): """ Return True if 's' can be converted in a float """ try: v = float(s) return True except ValueError: return False
def calculate_number_of_conditions(conditions_length, max_conditions): """ Every condition can hold up to max_conditions, which (as of writing this) is 10. Every time a condition is created, (max_conditions) are used and 1 new one is added to the conditions list. This means that there is a net decrease of up to (max_conditions-1) with each iteration. This formula calculates the number of conditions needed. x items in groups of y, where every group adds another number to x Math: either math.ceil((x-1)/(y-1)) or math.floor((x+(y-1)-2)/(y-1)) == 1 + (x-2)//(y-1) :param int conditions_length: total # of conditions to handle :param int max_conditions: maximum number of conditions that can be put in an Fn::Or statement :return: the number (int) of necessary additional conditions. """ num_conditions = 1 + (conditions_length - 2) // (max_conditions - 1) return num_conditions
def unpack_plot_settings(panel_dict, entry): """ :param panel_dict: :param entry: :return: """ return [panel_dict[key][entry] for key in ['panel_' + str(i + 1) for i in range(len(panel_dict))]]
def gen_edges(col_num, row_num): """Generate the names of the outer edges in the traffic light grid network. Parameters ---------- col_num : int number of columns in the traffic light grid row_num : int number of rows in the traffic light grid Returns ------- list of str names of all the outer edges """ edges = [] x_max = col_num + 1 y_max = row_num + 1 def new_edge(from_node, to_node): return str(from_node) + "--" + str(to_node) # Build the horizontal edges for y in range(1, y_max): for x in [0, x_max - 1]: left_node = "({}.{})".format(x, y) right_node = "({}.{})".format(x + 1, y) edges += new_edge(left_node, right_node) edges += new_edge(right_node, left_node) # Build the vertical edges for x in range(1, x_max): for y in [0, y_max - 1]: bottom_node = "({}.{})".format(x, y) top_node = "({}.{})".format(x, y + 1) edges += new_edge(bottom_node, top_node) edges += new_edge(top_node, bottom_node) return edges
def space_list(line: str) -> list: """"Given a string, return a list of index positions where a blank space occurs. >>> space_list(" abc ") [0, 1, 2, 3, 7] """ spaces = [] for idx, car in enumerate(list(line)): if car == " ": spaces.append(idx) return spaces
def _get_downcast_proxy(class_reference, property): """Get downcast proxy for property in class_reference, None if not set.""" if not hasattr(class_reference, "__deserialize_downcast_proxy_map__"): return None return class_reference.__deserialize_downcast_proxy_map__.get(property, None)
def column_names_prepare(raw_names) -> tuple: """ Returns the tuple of column names, where: * character '_' is replaced with a space ' '; * the first letter in a word is capitalized. """ return tuple([name.replace('_', ' ').capitalize() for name in raw_names])
def filter_claim_fn(example, _): """Filter out claims/evidence that have zero length.""" if 'claim_text_word_ids' in example: claim_length = len(example['claim_text_word_ids']) else: claim_length = len(example['claim_text']) # Explicit length check required. # Implicit length check causes TensorFlow to fail during tracing. if claim_length != 0: return True else: return False
def linear_map(val, lo, hi): """Linear mapping.""" return val * (hi - lo) + lo
def is_a_palindrome(string: str) -> bool: """Return True if string is a palindrome, False otherwise. A palindrome is a string who can be read the same both ways. """ return string == ''.join(reversed(string))
def encode_quotes(string): """ Return a string with single and double quotes escaped, keyvalues style """ return string.replace('"', '\\"').replace("'", "\\'")
def get_first_line(comment): """Gets the first line of a comment. Convenience function. Parameters ---------- comment : str A complete comment. Returns ------- comment : str The first line of the comment. """ return comment.split("\n")[0]
def create_url(user_id): """concat user_id to create url.""" url = "https://api.twitter.com/2/users/{}/liked_tweets".format(user_id) return url
def has_activity(destination, activity_name): """Test if a given activity is available at the passed destination""" return destination.has_activity(activity_name) if destination else False
def maxSize(split, maxed): """ Called by combinedCheck to ensure that a given cleavage or peptide is smaller than a given maxSize. :param split: the cleavage or peptide that is to have its size checked against max size. :param maxed: the max size that the cleavage or peptide is allowed to be. :return bool: False if the split is longer than maxed, True if it is shorter. """ if len(split) > maxed: return False return True
def set_hashes(task, i): """ For some reason Prodigy was assigning the same hashes to every example in the data, which meant that when it looked at the saved annotations in the dataset to figure out which to exclude, it excluded all of them. Setting the _input_hash to the index of the candidate connection also makes lookup easier when we filter the candidates according to their annotation. """ task["_input_hash"] = i task["_task_hash"] = -(i+1) return task
def legend(*, shadow=False, frameon=True, fancybox=False): """Adjust the legend-style.""" return { "legend.shadow": shadow, "legend.frameon": frameon, "legend.fancybox": fancybox, }
def checkout(cash: float, list: dict) -> float: """ build a function that sums up the value of the grocery list and subtracts that from the cash passed into the function. return the "change" from the cash minus the total groceries value. """ total=float() for key,value in list.items(): total = total + value return (cash-total)
def get_first_years_performance(school): """ Returns performance indicator for this school, as well as an indicator (1-5; 3 is average, 1 is worse, 5 is better) that compares the school to the national average. """ performance = {} ratio = school['renondb'].strip() # bolletje compared_performance = school['renonbol'].strip() if ratio: ratio = float(ratio.replace(',', '.')) performance['ratio'] = ratio if compared_performance: performance['compared_performance'] = int(compared_performance) performance['compared_performance_category'] = school['renoncat'].strip() return performance
def entropy(target_col): """ This function takes target_col, which is the data column containing the class labels, and returns H(Y). """ ###################### # Filling in this part# ###################### return entropy
def _format_version(name): """Formats the string name to be used in a --version flag.""" return name.replace("-", "_")
def pltostr(path): """ convert Pathlib object to absolute path as string Args: path (Path object): Pathobject to convert """ if isinstance(path, str): return path return str(path.absolute())
def dist2weights_linear(dist, max_r, max_w=1, min_w=0): """Linear distance weighting. Parameters ---------- dist: float or np.ndarray the distances to be transformed into weights. max_r: float maximum radius of the neighbourhood considered. max_w: int (default=1) maximum weight to be considered. min_w: float (default=0) minimum weight to be considered. Returns ------- weights: np.ndarray, array_like, shape (num. of retrievable candidates) values of the weight of the neighs inferred from the distances. """ weights = (max_w - dist)*((max_w-min_w)/float(max_r))+min_w return weights
def cohensutherland(left, top, right, bottom, x1, y1, x2, y2): """Clips a line to a rectangular area. This implements the Cohen-Sutherland line clipping algorithm. left, top, right and bottom denote the clipping area, into which the line defined by x1, y1 (start point) and x2, y2 (end point) will be clipped. If the line does not intersect with the rectangular clipping area, four None values will be returned as tuple. Otherwise a tuple of the clipped line points will be returned in the form (cx1, cy1, cx2, cy2). """ LEFT, RIGHT, LOWER, UPPER = 1, 2, 4, 8 def _getclip(xa, ya): p = 0 if xa < left: p = LEFT elif xa > right: p = RIGHT if ya < top: p |= LOWER elif ya > bottom: p |= UPPER return p k1 = _getclip(x1, y1) k2 = _getclip(x2, y2) while (k1 | k2) != 0: if (k1 & k2) != 0: return None, None, None, None opt = k1 or k2 if opt & UPPER: x = x1 + (x2 - x1) * (1.0 * (bottom - y1)) / (y2 - y1) y = bottom elif opt & LOWER: x = x1 + (x2 - x1) * (1.0 * (top - y1)) / (y2 - y1) y = top elif opt & RIGHT: y = y1 + (y2 - y1) * (1.0 * (right - x1)) / (x2 - x1) x = right elif opt & LEFT: y = y1 + (y2 - y1) * (1.0 * (left - x1)) / (x2 - x1) x = left else: # this should not happen raise RuntimeError("invalid clipping state") if opt == k1: # x1, y1 = int(x), int(y) x1, y1 = x, y k1 = _getclip(x1, y1) else: # x2, y2 = int(x), int(y) x2, y2 = x, y k2 = _getclip(x2, y2) return x1, y1, x2, y2
def dataline(line): """ Tries to split data from line in file, if it splits up then it has pKa data if it doesn't then it's not a data line This is very specific to the log files as created by this Epik run, not at all a general use option. """ try: data = line.split(' ') pKa = float(data[2]) return True, data[1].strip(), pKa except: return False, None, None
def uv76_to_xy(u76, v76): # CIE1976 to CIE1931 """ convert CIE1976 u'v' to CIE1931 xy coordinates :param u76: u' value (CIE1976) :param v76: v' value (CIE1976) :return: CIE1931 x, y """ denominator = (((9 * u76) / 2) - (12 * v76) + 9) if denominator == 0.0: x, y = 0.0, 0.0 else: x = ((27 * u76) / 4) / denominator y = (3 * v76) / denominator return x, y # CIE1931 x, y
def match_task(question: str, keywords: list): """Match question words with the keywords. Return True and the matched word if at least one word is matched. """ for word in question.split(" "): for kw in keywords: if word == kw: return word return ""
def get_userdetail_fields(fields): """ Returns the fields for `UserDetailSerializer`. """ fields = list(fields) fields.remove('is_superuser') fields.remove('user_permissions') fields = tuple(fields) return fields
def second_char(word): """ Return the second char @param word: given word @type word: unicode @return: the first char @rtype: unicode char """ return word[1:2]
def speak(text): """ speak :param text: :return: """ def whisper(t): return t.lower() + '...' return whisper(text)
def mongodb_int_filter(base_field, base_field_type): """Prepare filters (kwargs{}) for django queryset where fields contain digits are checked like = | > | >= | < | <= >>> mongodb_int_filter(10, '1') 10.0 >>> mongodb_int_filter(10, '2') {'$gt': 10.0} >>> mongodb_int_filter(10, '3') {'$gte': 10.0} >>> mongodb_int_filter(10, '4') {'$lt': 10.0} """ q = '' if base_field != '': if base_field_type == '1': # = q = float(base_field) if base_field_type == '2': # > q = {'$gt': float(base_field)} if base_field_type == '3': # >= q = {'$gte': float(base_field)} if base_field_type == '4': # < q = {'$lt': float(base_field)} if base_field_type == '5': # <= q = {'$lte': float(base_field)} return q
def _get_fetch_names(fetches): """Get a flattened list of the names in run() call fetches. Args: fetches: Fetches of the `Session.run()` call. It maybe a Tensor, an Operation or a Variable. It may also be nested lists, tuples or dicts. See doc of `Session.run()` for more details. Returns: (list of str) A flattened list of fetch names from `fetches`. """ lines = [] if isinstance(fetches, (list, tuple)): for fetch in fetches: lines.extend(_get_fetch_names(fetch)) elif isinstance(fetches, dict): for key in fetches: lines.extend(_get_fetch_names(fetches[key])) else: # This ought to be a Tensor, an Operation or a Variable, for which the name # attribute should be available. (Bottom-out condition of the recursion.) lines.append(fetches.name) return lines
def load_tests(loader, standard_tests, pattern): """Prevents test discovery in the mixin modules. Mixin test cases can't be run directly. They have to be used in conjunction with a test class which performs the setup required by the mixin test cases. This does not prevent mixin test case discovery in test classes that inherit from mixins. Args: loader: A unit test loader instance. Unused. standard_tests: Already loaded test cases. pattern: Test method name pattern. Unused. Returns: Already loaded standard_tests. """ del loader, pattern # Unused. return standard_tests
def sizeof_fmt(num, suffix='B'): """ Provides human-readable string for an integer size in Byles https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['','K','M','G','T','P','E','Z']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def use_simple_logging(kwargs): """Checks if simple logging is requested""" return any([x in kwargs for x in ('log_folder', 'logger_names', 'log_levels', 'log_multiproc', 'log_level')])
def none_to_null(value): """ Returns None if the specified value is null, else returns the value """ return "null" if value == None else value
def human_size(num, suffix='B'): """ Convert bytes length to a human-readable version """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "{0:3.1f}{1!s}{2!s}".format(num, unit, suffix) num /= 1024.0 return "{0:.1f}{1!s}{2!s}".format(num, 'Yi', suffix)
def __get_float(section, name): """Get the forecasted float from xml section.""" try: return float(section[name]) except (ValueError, TypeError, KeyError): return float(0)
def isextension(name): """Return True if name is an API extension name (ends with an upper-case author ID). This assumes that author IDs are at least two characters.""" return name[-2:].isalpha() and name[-2:].isupper()
def chomp(s: str) -> str: """Remove a LF, CR, or CR LF line ending from a string""" if s.endswith("\n"): s = s[:-1] if s.endswith("\r"): s = s[:-1] return s
def get_start_name(name, prefix_name=""): """ gets the start name. :return: <str> start name. """ return '{prefix}{name}'.format(prefix=prefix_name, name=name)
def Area(pl, ps): """ calculate area of points given in ps by name """ n = len(ps) are = 0 for i in range(n): j = (i + 1) % n if ps[i] in pl and ps[j] in pl: are += (pl[ps[i]][0] + pl[ps[j]][0]) * (pl[ps[i]][1] - pl[ps[j]][1]) return are / 2
def get_sh_type(sh_type): """Get the section header type.""" if sh_type == 0: return 'SHT_NULL' elif sh_type == 1: return 'SHT_PROGBITS' elif sh_type == 2: return 'SHT_SYMTAB' elif sh_type == 3: return 'SHT_STRTAB' elif sh_type == 4: return 'SHT_RELA' elif sh_type == 5: return 'SHT_HASH' elif sh_type == 6: return 'SHT_DYNAMIC' elif sh_type == 7: return 'SHT_NOTE' elif sh_type == 8: return 'SHT_NOBITS' elif sh_type == 9: return 'SHT_REL' elif sh_type == 10: return 'SHT_SHLIB' elif sh_type == 11: return 'SHT_DYNSYM' elif sh_type == 14: return 'SHT_INIT_ARRAY' elif sh_type == 15: return 'SHT_FINI_ARRAY' elif sh_type == 16: return 'SHT_PREINIT_ARRAY' elif sh_type == 17: return 'SHT_GROUP' elif sh_type == 18: return 'SHT_SYMTAB_SHNDX' elif sh_type == 19: return 'SHT_NUM' elif sh_type == 1610612736: return 'SHT_LOOS' else: print('Unable to match {} to a sh_type.'.format(sh_type)) raise ValueError
def dRELU(x): """if x <= 0: return 0 else: return 1""" #return x * (1 - x) return 1
def tex_coord(x, y, n=8): """ Return the bounding vertices of the texture square. """ m = 1.0 / n dx = x * m dy = y * m return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
def getname(f): """Get the name of an object. For use in case of callables that are not functions, and thus may not have __name__ defined. Order: f.__name__ > f.name > str(f) """ try: return f.__name__ except: pass try: return f.name except: pass return str(f)
def validipaddr(address): """ Returns True if `address` is a valid IPv4 address. >>> validipaddr('192.168.1.1') True >>> validipaddr('192.168. 1.1') False >>> validipaddr('192.168.1.800') False >>> validipaddr('192.168.1') False """ try: octets = address.split(".") if len(octets) != 4: return False for x in octets: if " " in x: return False if not (0 <= int(x) <= 255): return False except ValueError: return False return True
def is_form_post(environ): """Determine whether the request is a POSTed html form""" content_type = environ.get('CONTENT_TYPE', '').lower() if ';' in content_type: content_type = content_type.split(';', 1)[0] return content_type in ('application/x-www-form-urlencoded', 'multipart/form-data')
def get_nested_field(value, field): """ Get nested field from list of objects or single instance :param value: Single instance or list to look up field :param field: Field to lookup :return: List or single instance of looked up field """ if field == '__self__': return value fields = field.split('__') for fld in fields: if isinstance(value, list): value = [getattr(v, fld) for v in value] else: value = getattr(value, fld) return value
def flatten_dialogue(dialogue): """ Flatten a dialogue into a single string Dialogue are list of turns (list of lists) """ flattened = [] for turn in dialogue: # filter first element of turn if it is none if turn[0] != "none": flattened.append(" ".join(turn)) else: flattened.append(turn[1]) return " ".join(flattened)
def num_eights(x): """Returns the number of times 8 appears as a digit of x. >>> num_eights(3) 0 >>> num_eights(8) 1 >>> num_eights(88888888) 8 >>> num_eights(2638) 1 >>> num_eights(86380) 2 >>> num_eights(12345) 0 >>> from construct_check import check >>> # ban all assignment statements >>> check(HW_SOURCE_FILE, 'num_eights', ... ['Assign', 'AugAssign']) True """ "*** YOUR CODE HERE ***" def is_eight(x): if x == 8: return 1 else: return 0 if x < 10: return is_eight(x) else: return num_eights(x // 10) + is_eight(x % 10)
def check_validity_specie_tag_in_reaction_dict(k): """Validate key in database reaction entry""" return not ( k == "type" or k == "id_db" or k == "log_K25" or k == "log_K_coefs" or k == "deltah" or k == "phase_name" )
def frontend_ip_configuration_id(subscription_id, resource_group_name, appgateway_name, name): """Generate the id for a frontend ip configuration""" return '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/applicationGateways/{2}/frontendIPConfigurations/{3}'.format( subscription_id, resource_group_name, appgateway_name, name )
def _contains_date(format): """ Check if a format (string) contains a date. (It currently check if the string contains tokens from the simpledateformat https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html that represent, years, months, days). :param format: A string format representing a simple date format. :type format: str :return: True if values part of a date are contained in the format string. :rtype: bool """ part_of_date_tokens = "GyYMwWdDFEu" for token in part_of_date_tokens: if token in format: return True return False
def cut_article(article: str) -> str: """ Takes an article and returns the first 25 words. If the article is less than 25 words it returns the full original article. Keyword arguments: article (string) : The article to take in Returns: new_art (string) : The first 25 words of the article or article : Unmodified article """ words = article.split(' ') if len(words) > 25: cut_art = words[0:25] new_art = " ".join(cut_art) return new_art else: return article
def process_events (events, fn): """ (list, fn) -> list Takes a list of events as well as a function that is called on each event. A list is returned, which is composed of the return values from the function. """ aggregator = [] for event in events: aggregator.append(fn(event)) return aggregator
def aper_corr_galex(mag, band, aperture=3): """ Aperture correction for GALEX magnitudes from Morrissey et al. (2007)""" if band=="nuv": if aperture==1: m = mag - 2.09 return m elif aperture==2: m = mag - 1.33 return m elif aperture==3: m = mag - 0.59 return m elif aperture==4: m = mag - 0.23 return m elif aperture==5: m = mag - 0.13 return m elif aperture==6: m = mag - 0.09 return m elif aperture==7: m = mag - 0.07 return m elif band=="fuv": if aperture==1: m = mag - 1.65 return m elif aperture==2: m = mag - 0.96 return m elif aperture==3: m = mag - 0.36 return m elif aperture==4: m = mag - 0.15 return m elif aperture==5: m = mag - 0.10 return m elif aperture==6: m = mag - 0.09 return m elif aperture==7: m = mag - 0.07 return m
def pretty_dict_repr(d): """Represent a dictionary with human-friendly text. Assuming d is of type dict, the output should be syntactically equivalent to repr(d), but with each key-value pair on its own, indented line. """ lines = [' {0!r}: {1!r},'.format(k, v) for (k, v) in sorted(d.items())] return '\n'.join(['{'] + lines + ['}'])
def str2bool(string): """ Only true if string is one of "yes", "true", "t", "1". Returns false otherwise. """ return string.lower() in ("yes", "true", "t", "1")
def endpoints(edge): """ Return a pair with the edge's **endpoints** (the nodes it connects). """ if len(edge) == 2: return tuple(edge) else: return tuple(edge) + tuple(edge)
def fix_pooltype(pooltype): """ :type: str :param pooltype: Pool type to fix :rtype: str :return: Fixed pool type """ if pooltype == 'Transactional': pooltype = 'Transactional Workloads' else: pooltype = '{0} Storage'.format(pooltype) return pooltype
def stop_word_removal(text_all, cached_stop_words): """ Returns text with removed stop words Keyword arguments: text_all -- list of all texts (list of str) cached_stop_words -- list of all stopwords (list of str) """ new_text_all = [] for text in text_all: text1 = ' '.join([word for word in text.split() if word not in cached_stop_words]) new_text_all.append(text1) return new_text_all
def make_erc_681_url( to_address, payment_amount, chain_id=1, is_token=False, token_address=None ): """Make ERC681 URL based on if transferring ETH or a token like DAI and the chain id""" base_url = "ethereum:" chain_id_formatted_for_url = "" if chain_id == 1 else f"@{chain_id}" if is_token: if token_address is None: raise ValueError( "if is_token is true, then you must pass contract address of the token." ) return ( base_url + token_address + chain_id_formatted_for_url + f"/transfer?address={to_address}&uint256={payment_amount}" ) # if ETH (not token) return ( base_url + to_address + chain_id_formatted_for_url + f"?value={payment_amount}" )
def get_details_format(s: str, lang: str = 'zh-cn'): """ Get API Request Parameters ---------- s: Company Name lang: Lang Returns ------- URL """ return "http://www.solvusoft.com/%s/file-extensions/software/%s/" % (lang, s)
def reverse(x): """ :type x: int :rtype: int """ sum1 = 0 if x > 0: n = len(str(x)) for i in range(n): rem = x % 10 x = x // 10 sum1 = (sum1 * 10) + rem return sum1 elif x < 0: x = x * -1 n = len(str(x)) for i in range(0, n): rem = x % 10 x = x // 10 sum1 = (sum1 * 10) + rem return sum1 * -1 else: return x
def get_exponential_decay_gamma(scheduling_factor, max_epochs): """Return the exponential learning rate factor gamma. Parameters ---------- scheduling_factor : By how much to reduce learning rate during training. max_epochs : int Maximum number of epochs. """ return (1 / scheduling_factor) ** (1 / max_epochs)
def findDictInDictList(dictList, value): """findDictInDictList. Args: dictList: value: """ # This is extremely inefficient code... We need to get the info pertaining to a specific filename dictVal = {} for row in dictList: if row['fileID'] == value: dictVal = row return dictVal
def _applescriptify(text): """Replace double quotes in text.""" return text.replace('"', '" + quote + "')
def format_date_filter(date, time=False): """Returns a formatted date string out of a `datetime` object. Args: time (bool): Add to date the time too if this is True. """ if not date: # NOTE(cmiN): Prefer to return empty string for missing dates (instead of N/A). return "" template = "%d-%b-%y" if time: template += " %H:%M" return date.strftime(template)
def _union(queries): """ Create a union of multiple query expressions. """ return "(" + " union ".join(queries) + ")"
def get_aws_region(service_arn): """ returns AWS Region from a service arn :param service_arn: ARN of a service :type service_arn: string :returns: AWS Account Region :rtype: string """ aws_region = service_arn.split(':')[3] return aws_region
def _indent(content, indent): """ :param content: :param indent: :return: """ if indent == 0: return content else: indent = " " * indent if isinstance(content, list): return ["".join([indent, line]) for line in content] else: return "".join([indent, content])
def calendar_module(raw_str: str) -> str: """ >>> calendar_module('08 05 2015') 'WEDNESDAY' """ import calendar month, day, year = map(int, raw_str.split()) num_day = calendar.weekday(year, month, day) name_day = calendar.day_name[num_day].upper() return name_day
def resolve_key(obj, key): """Resolve key given an object and key.""" if callable(key): return key(obj) elif hasattr(obj, 'metadata'): return obj.metadata[key] raise TypeError("Could not resolve key %r. Key must be callable or %s must" " have `metadata` attribute." % (key, obj.__class__.__name__))