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 ...
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: ...
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 @...
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: ...
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 = s...
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"] ...
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) retu...
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 ...
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! retur...
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,...
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 resu...
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: retu...
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 = [] ...
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 ...
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 st...
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 ...
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. :re...
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...
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(): ...
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 compare...
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...
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 ...
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...
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 ...
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') {'$g...
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: (l...
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 clas...
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, suff...
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}".forma...
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' ...
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: ...
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: ...
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', ...
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 field...
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)) ...
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 >>> # ...
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, ...
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 ...
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 ...
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)) ...
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 -...
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()...
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 ...
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: ...
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)) fo...
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 / sc...
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 re...
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 "" t...
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 ""....
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." % ...