content
stringlengths
42
6.51k
def tabs_are_spaces(s: str, n=1): """Replaces tabs with n[=1 by default] spaces.""" return s.replace("\t", n * " ")
def get_n_s(num): """ Get a string for a float at .2f """ if num == None: return 'None' return "%.2f"%num
def linear_annuity_mapping_func(underlying, alpha0, alpha1): """linear_annuity_mapping_func calculate linear annuity mapping function. Annuity mapping function is model of $P(t, T) / A(t)$ so that it's value is positive. linear annuity mapping function calculates following formula: .. math:: ...
def _setdef(argdict, name, defaultvalue): """Like dict.setdefault but sets the default value also if None is present.""" if not name in argdict or argdict[name] is None: argdict[name] = defaultvalue return argdict[name]
def __float2str(value: float) -> str: """Convert a float into a human readable string representatoin.""" if value == 0.0: return "0.0" return "{0:.5f}".format(value)
def compute_heat_transfer_area(LMTD, U, Q, ft): """ Return required heat transfer area by LMTD correction factor method. Parameters ---------- LMTD : float Log mean temperature difference U : float Heat transfer coefficient Q : float Duty """ return ...
def secret_errors(vol_desc): """Sanity check a Secret volume description and return a string for the first problem found. Return None if no problem is found. """ required_fields = ['secret_name'] accepted_fields = ['secret_name', 'items', 'default_mode', 'optional'] secret = vol_desc.get('s...
def is_zip_path(img_or_path): """judge if this is a zip path""" return '.zip@' in img_or_path
def _get_concept_reltype(relationship, direction): """ Convert two-part relationship info (relationship type and direction) to more parsimonious representation. """ new_rel = None if relationship == 'PARTOF': if direction == 'child': new_rel = 'hasPart' elif direction...
def integral(shift, op, elements, accumulator): """ Inverse of derivative. Scans a list of elements using an accumulator. Returns the integral of the elements and the final state of the accumulator. ---------- shift : Shift of -1 is an exclusive scan and a shift of 1 is an inclusive scan. op : Opera...
def createKey(problemData): """ Creates the key for a given 'problemData' list of number of item types. """ key = '' for itData in problemData: key += str(itData) + ',' # Remove the last comma return key[:-1]
def concat_key_value(str_dict): """concat keys and values of dict containing strings elements into a list Parameters ---------- str_dict: dict dict to process {key1: value1, key2: value2} Returns ------- list ['key1 value1', 'key2 value2'] """ return [ke...
def _crc_update(crc, data, mask, const): """ CRC8/16 update function taken from _crc_ibutton_update() function found in "Atmel Toolchain/AVR8 GCC/Native/3.4.1061/ avr8-gnu-toolchain/avr/include/util/crc16.h" documentation. @param[in] crc current CRC value @param[in] data next byte of data @p...
def markdown_adjust(s): """Escape problematic markdown sequences.""" s = s.replace('\t', u'\\t') s = s.replace('\n', u'\\n') s = s.replace('\r', u'\\r') s = s.replace('`', u'') s = s.replace('|', u'\\|') return s
def unqualify(name: str) -> str: """Return an unqualified name given a qualified module/package `name`.""" return name.rsplit(".", maxsplit=1)[-1]
def LN(number): """ Calculates the natural logarithm ln of a number and returns the result as a double. See https://docs.mongodb.com/manual/reference/operator/aggregation/ln/ for more details :param number: The number or field of number :return: Aggregation operator """ return {'$ln': nu...
def _scipy_distribution_positional_args_from_dict(distribution, params): """Helper function that returns positional arguments for a scipy distribution using a dict of parameters. See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\ to see a...
def get_fashion_mnist_labels(labels): """Return text labels for the Fashion-MNIST dataset. Defined in :numref:`sec_utils`""" text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot'] return [text_labels[int(i)] for i in labels...
def _pad_to_seven(single_postcode): # r'(.*?(?=.{3}$))(.{3}$)' (potential regex) """Pad postcode strings If length of postcode is 6 or 5 then insert 1 or 2 spaces. 6 first as more common to speed up execution """ if single_postcode == single_postcode: # filters out NaNs length = len(singl...
def fib_memo_loop(n, memo): """Looping recursive fibonacci sequence implementation utilizing memoization. Use for large n. Args: n (Integer): Index of the fibonacci number memoization (Dictionary): Non-Null dictionary with prior memoized values Returns: Integer: Value of the f...
def columnToNumber(col): """ Interpret a column as the binary representation of a number. """ number = 0 for elem in col: number <<= 1 number += elem return number
def flatten_list(list_to_flat): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in list_to_flat], [])
def strip_filter(text): """Filter for trimming whitespace. :param text: The text to strip. :returns: The stripped text. """ return text.strip() if text else text
def is_public_method(class_to_check, name): """Determine if the specified name is a public method on a class""" if hasattr(class_to_check, name) and name[0] != "_": if callable(getattr(class_to_check, name)): return True return False
def numericrange_to_string(r): """Helper method to convert a NumericRange to a human-readable string.""" if not r: return "" lower = r.lower upper = r.upper if upper is None and lower is None: return "" if lower and upper is None: return str(lower) if upper and lower ...
def flip(author): """ Last, F -> F~Last """ lc = author.find(',') if lc < 0: print("%% BAD author malformed: %s" % author) return author tmp = author[lc+1:] if len(tmp) > 0: if tmp[0] == '~': tmp = tmp[1:] return tmp + '~' + author[:lc] else...
def _check_prefix(library_basename, filename_prefixes): """Return the prefix library_basename starts with or None if none matches """ for prefix in filename_prefixes: if library_basename.startswith(prefix): return prefix return None
def objlib_to_path(lib, object=None) -> str: """Returns the path for the given objlib in IFS >>> objlib_to_path("TONGKUN") '/QSYS.LIB/TONGKUN.LIB' >>> objlib_to_path("TONGKUN", "SAMREF.FILE") '/QSYS.LIB/TONGKUN.LIB/SAMREF.FILE' """ if not lib: raise ValueError() if object is not...
def keys_to_ints(d): """ Takes a dict and returns the same dict with all keys converted to ints """ return {int(k): v for k, v in d.items()}
def parse_time(x): """Extract hour, day, month, and year from time category.""" from datetime import datetime DD = datetime.strptime(x, "%Y-%m-%d %H:%M:%S") time = DD.hour day = DD.day month = DD.month year = DD.year return time, day, month, year
def max_contig_sum(L): """ L, a list of integers, at least one positive Returns the maximum sum of a contiguous subsequence in L """ max_ending_here = max_so_far = L[0] for i in L[1:]: max_ending_here = max(i, max_ending_here + i) max_so_far = max(max_so_far, max_ending_here) return ...
def par_impar(n): """ Par Impar Admite un numero y evalua si es par Parameters ----------- n : int Numero a evaluar Returns ------- bool Resultado de evaluar si es par el numero """ if n%2 == 0 : return Tr...
def _is_legacy_ip_per_task(app): """ Return whether the application is using IP-per-task on Marathon < 1.5. :param app: The application to check. :return: True if using IP per task, False otherwise. """ return app.get('ipAddress') is not None
def activate(value1, value2): """ Returns a color based on job status. """ return "orange active" if value1 == value2 else ''
def _trac_data_tags(instance, trac_type, state): """ Returns data types for specific type and an object. """ data_str = '' if instance: data = { 'state': state, 'type': trac_type, 'app': instance._meta.app_label, 'klass': instance.__class__.__n...
def cl(l): """Return compact list str representation.""" return str(l).replace(', ',',')
def _standardize_package_name(raw_package_name): """Helper to convert the arbitrary ways packages can be represented to a common (matchable) representation """ return raw_package_name.strip().lower().replace("-", "_")
def hour(x: str) -> str: """Function to return hour of day.""" return { "00": "12 AM - 1 AM", "01": "01 AM - 2 AM", "02": "2 AM - 3 AM", "03": "3 AM - 4 AM", "04": "4 AM - 5 AM", "05": "5 AM - 6 AM", "06": "6 AM - 7 AM", "07": "7 AM - 8 AM", ...
def get_topic(domain_class): """Returns a string describing a class. Args: domain_class: A class. Returns: A string describing the class. """ return domain_class.__module__ + '#' + getattr(domain_class, '__qualname__', domain_class.__name__)
def scalp_tune_install(): """ User settings for scalp operations """ scalp_tune = {} return scalp_tune
def format_parameter_name_to_option_name(parameter_name: str) -> str: """Convert a name in parameter format to option format. Underscores ("_") are used to connect the various parts of a parameter name, while hyphens ("-") are used to connect each part of an option name. Besides, the option name starts wit...
def _sparse_ftrs_values(ftr_name): """Returns the name of the values for sparse feature `ftr_name`""" return f"{ftr_name}_values"
def format_datetime_for_report(timestamp_with_tz): """Format the datetime into a string for reporting. Replace this function with datetime.isoformat(sep=' ', timespec='seconds') after we update python version to 3.6 """ if timestamp_with_tz is not None: return timestamp_with_tz.strftime('%Y-%m-...
def running_task_status(task_statuses): """ From a given list of statuses retrieved from mesos API it returns status of running task. """ for task_status in task_statuses: if task_status['state'] == "TASK_RUNNING": return task_status assert False, "Did not find a TASK_RUNNING status...
def generate_finding_title(title): """ Generate a consistent title for a finding in AWS Security Hub * Setup as a function for consistency """ return "Trend Micro: {}".format(title)
def _get_emotion_scores(clf, reviews): """ Gets emotion scores from user reviews :param clf: :param reviews: :return: """ review_list = reviews.split("</review>") scores = [] for review in review_list[:-1]: cleaned_text = review.replace("<review>", "").replace("[", "").replac...
def unused(permutation, nb_elements): """ List the elements of `range(nb_elements)` which are not in `permutation` Parameters ---------- permutation: iterable nb_elements: int Returns ------- unused_elements: tuple Examples -------- >>> unused((1, 4, 0), 6) (2, 3, 5) ...
def collate_acceptance_ratios(acceptance_list): """ Collate the running proportion of all runs that have been accepted from an MCMC chain. """ count, n_total, ratios = 0, 0, [] for n_accept in acceptance_list: n_total += 1 if n_accept: count += 1 ratios.append(co...
def SetColor(x): """ coloring scatter plots based on Network quality """ if x > 20: return "green" elif x > 15 and x <= 20: return "yellow" elif x >= 10 and x <= 15: return "red" elif x < 10: return "red"
def report_file_name(submission_id, warning, file_type, cross_type=None): """Format the csv file name for the requested file. @todo: unify these file names""" if cross_type: report_type_str = 'warning_' if warning else '' return "submission_{}_cross_{}{}_{}.csv".format(submission_id, report_...
def string_repr(string): """ It is nicer to see strings displayed with quotes when reporting, otherwise whitespace might not be apparent. """ return "'%s'" % string
def is_natural_language(line): """Determine if a line is likely to be actual natural language text, as opposed to, e.g., LaTeX formulas or tables. Pretty crude heuristic, but as long as it filters out most of the bad stuff it's okay, I guess.""" line = line.strip() if len(line) < 5: return ...
def merge_dictlist(dictlist): """Merge list of dicts into dict of lists, by grouping same key.""" ret = {k: [] for k in dictlist[0].keys()} for dic in dictlist: for data_key, v in dic.items(): ret[data_key].append(v) return ret
def run(*args): """Returns the last argument. Useful in config files.""" if not args: raise ValueError('Nothing to run.') return args[-1]
def Byte_Xor(ba1, ba2): """ Description: This function computes the xor between two byte arrays. Inputs: ba1, ba2 - byte arrays - are byte arrays of the same size to be xored. Outputs: xored - byte array - A byte array with the xored result. """ xored = bytes([_a...
def getCategory(mu_type): """ collapse mutation types per strand symmetry """ # if re.match("^[ACGT]*$", mu_type): if mu_type in ('AC', 'TG'): category = "T_G" elif mu_type in ('AG', 'TC'): category = "T_C" elif mu_type in ('AT', 'TA'): category = "T_A" elif mu_...
def get_callable(path): """Returns a callable from a given dotted path.""" try: module_path, callable_name = path.rsplit('.', 1) except ValueError: raise ImportError("%s doesn't look like a callable path" % path) module = __import__(module_path, fromlist=['']) try: return g...
def points_to_svgd(p, close=True): """ convert list of points (x,y) pairs into a closed SVG path list """ f = p[0] p = p[1:] svgd = 'M%.4f,%.4f' % f for x in p: svgd += 'L%.4f,%.4f' % x if close: svgd += 'z' return svgd
def getAnnedArgs(args, validAnns=set(('@I', '@i', '@N', '@J'))): """Parses an argument list which may contain annotations.""" annedArgs = [] annListCurr = [] for arg in args: if arg in validAnns: annListCurr.append(arg) else: annedArgs.append((annListCurr, arg)) ...
def longest_seq(seqs): """ Find the longest chain in the output of all_uninterrupted_seqs """ max_len = 0 max_seq = [] for seq in seqs: if len(seq) >= max_len: max_seq = seq max_len = len(max_seq) return max_seq
def RPL_TRACERECONNECT(sender, receipient, message): """ Reply Code 210 """ return "<" + sender + ">: " + message
def clean_link(link): """ Many links will direct you to a specific subheading of the page, or reference some particular component on the page. We don't want to consider these "different" URLs, so parse this out. In: string representiaton of a URL link. Out: "cleaned" version of the link...
def by_first_commit(a, b): """Order two changesets by their first commit date.""" return int(a['first_commit'] - b['first_commit'])
def ceil(number): """ Return the closest integer >= number. Inputs: ``float`` number Outputs: ``int`` """ floored = number // 1 if number == floored: return int(number) else: return int(floored + 1)
def create_name(part, layer, i): """ Helper function for generating names for layers. Args: part (str): Part/path the layer belongs to. layer (str): The function of the layer, .e.g conv3d. i (int): The layer depth of the layer. Returns: str: Concatenated layer name. ...
def keepsaccade(i, j, sim_lenx, sim_leny, sim_x, sim_y, sim_theta, sim_len, sim_dur, data ): """ Helper function for scanpath simplification. If no simp...
def typeof(value): """Returns the type of the given value. Example usage: {{ my_var|typeof }} """ return (u"%s" % type(value)).replace("<class '", "").replace("<type '", "").replace("'>", "")
def Pattern_Matching(Pattern, Seq): """ Exercice 1.3.5 Pattern Matching. Description: Find all occurrences of a pattern in a string. Input: Two strings, Pattern and Seq. Output: All starting positions where Pattern appears as a substring of Seq. Sample Input: AT...
def unquote(string: str) -> str: """ Remove simple quote or double quote around a string if any. >>> unquote('"hello"') 'hello' >>> unquote('"hello') '"hello' >>> unquote('"a"') 'a' >>> unquote('""') '' """ if ( len(string) >= 2 and (string.startswith('"')...
def fixBsz(bsz,nppi): """ Fix batchsize w.r.t. the number of PATCHES per image """ if bsz<1: bsz = 1 return int(bsz)
def sc_mulsub(aa, bb, cc): """ (cc - aa * bb) % l """ return cc - aa * bb
def batch(items, size): """Batches a list into a list of lists, with sub-lists sized by a specified batch size.""" return [items[x:x + size] for x in range(0, len(items), size)]
def IsNumber(s): """Returns True if string is a number.""" try: float(s) return True except ValueError: return False
def is_linked(turnCarrier): """ Checks whether a request is linked """ if turnCarrier == "": return False return True
def remove_file(filename, recursive=False, force=False): """Removes a file or directory.""" import os try: mode = os.stat(filename)[0] if mode & 0x4000 != 0: # directory if recursive: for file in os.listdir(filename): success = remo...
def strip_keys(this_object): """Strips whitespace and removes keys with empty values""" return {k: v.strip() for (k, v) in this_object.items() if v.strip() != ''}
def create_study_meta_file( study_identifier: str, type_of_cancer: str, name: str, description: str, groups: str, short_name: str, ) -> dict: """Create study metadata file Args: study_identifier (str): A string used to uniquely identify this cancer study ...
def has_updates(update_list): """ Returns true if there are updates available. """ if update_list is None or len(update_list) == 0: return False else: return True
def frhs(phi, tau): """ reaction ODE righthand side """ return 0.25*phi*(1.0 - phi)/tau
def chinese_literature_ent_type_process_fn(d): """Not match my need Arguments: d {[type]} -- [description] Returns: [type] -- [description] """ ent_type = d.split(' ')[1].replace('\n', '') return ent_type
def _segmentrepr(obj): """ >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], numpy.array([0.1, 2.2])]]]) '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))' """ try: it = iter(obj) except TypeError: return str(obj) else: return "(%s)" % ", ".join([_segmentrepr(x) for x in it])
def phaseNearTargetPhaseDeg(phase,phase_trgt): """ Adds or subtracts 360 to get the phase near the target phase. """ delta = 360.*int((phase_trgt - phase)/(360.)) phase += delta if(phase_trgt - phase > 180.): phase += 360. return phase if(phase_trgt - phase < -180.): phase -= 360. return phase
def Binary2Decimal(bin_num): """ Return the decimal representation of bin_num This actually uses the built-in int() function, but is wrapped in a function for consistency """ return int(bin_num, 2)
def msg(num, txt=['plus', 'minus', 'zero', 'other']): """ return message text for +1,-1, 0, other (e.g. None) """ # if num == 1: str = txt[0] elif num == -1: str = txt[1] elif num == 0: str = txt[2] else: str = txt[3] return str
def imgVRange(h, va, fontSize): """ return bottom,top offsets relative to baseline(0) """ if va == 'baseline': iyo = 0 elif va in ('text-top', 'top'): iyo = fontSize - h elif va == 'middle': iyo = fontSize - (1.2 * fontSize + h) * 0.5 elif va in ('text-bottom', 'bott...
def toNumber (str, default=None): """toNumber(str[, default]) -> integer | float | default Converts the given string to a numeric value. The string may be a hexadecimal, integer, or floating number. If string could not be converted, default (None) is returned. Examples: >>> n = toNumber("0x...
def augmentedMatrix(M, b): """Retorna la matriz aumentada""" a = M for i in range(len(M)): a[i].append(b[i]) return a
def network_from_context(context): """Get the Network from a Neutron Context. :param context: a Neutron Context; :return: the network; """ return getattr(context, '_network', None)
def choose_pivot_index_median_of_three(sequence, index_l, index_r): """ Choose the pivot using the median-of-three rule and return its index. sequence -- the sequence of items to sort index_l -- the index of the first of the items that we want to sort index_r -- the index just past the end of...
def compareTelemetryBinFiles(baseFileName, compareFileName): """ Compare the input binary files """ returnStatus = True """ if (baseFileName != compareFileName): fcCmd = format("fc /b %s %s > %s" % (baseFileName, compareFileName, baseFileName+"_err")) retValue = os.system...
def github_oauth_application_create(rec): """ author: @mimeframe description: An OAuth application was registered within Github. reference: https://developer.github.com /apps/building-integrations/setting-up-and-registering-oauth-apps/ """ return rec['action'] == 'oau...
def make_station_averages(stations, up_averages, down_averages): """create station objects containing time averages for next and previous stations""" assert type(stations) == list assert type(up_averages) == list assert type(down_averages) == list station_objects = [] for index, name in enu...
def multipart_content_type(boundary, subtype='mixed'): """Creates a MIME multipart header with the given configuration. Returns a dict containing a MIME multipart header with the given boundary. .. code-block:: python >>> multipart_content_type('8K5rNKlLQVyreRNncxOTeg') {'Content-Type...
def remove_language(code): """if the code starts with a single term on the first line, assume it's a language and remove it. We will need to test this to see if it works in practice. """ lines = code.split("\n") if len(lines) > 1: words = lines[0].split(" ") if len(words) =...
def parse_records(records): """ A helper function to parse a record returned by Springer API """ DEFAULT_TEXT = 'Not avaliable' if len(records) == 0: return [{'title': DEFAULT_TEXT, 'publicationName': DEFAULT_TEXT, 'abstract': DEFAULT_TEXT, 'doi': DEFAULT_TEXT, ...
def jacobi(x: int, n: int): """Jacobi symbol.""" if n <= 0: raise ValueError("'n' must be a positive integer.") if n % 2 == 0: raise ValueError("'n' must be odd.") x %= n r = 1 while x != 0: while x % 2 == 0: x //= 2 nm8 = n % 8 if nm8 ...
def _roll_up_small_pie_wedges(resource_data, resource_label, min_percentage): """Combine small wedges into a single category. Removes wedges with value 0. :param dict resource_data: values for each resource type. :param dict resource_label: labels for each resource type. :param float min_percentage: ro...
def pelem(elem): """ Helper to extract text from a bs4 element """ if elem is not None: return elem.text return ""
def levenshtein(source: str, target: str) -> int: """Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using th...
def extract_kwargs(args, exp_keys, exp_elems): """Return user-specified keyword args in a dictionary and a set (for True/False items).""" arg_dict = {} # For arguments that have values arg_set = set() # For arguments that are True or False (present in set if True) for key, val in args.items(): ...