content
stringlengths
42
6.51k
def user_auth_check(login_session): """ checks whether a user is logged in or not. :param login_session: :return: """ user = {} try: user['email'] = login_session['user_email'] user['id'] = login_session['user_id'] except KeyError: user = False return user
def to_precision(x,p): """ returns a string representation of x formatted with a precision of p Based on the webkit javascript implementation taken from here: https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp """ import math x = float(x) if x ...
def splitAndTrim(s, separator=",", maxsplit=-1, removeEmptyEntries=True): """Splits a string into a list, each value having been stripped of leading and trailing whitespace.""" if s == None: return None values = [] if not s: return values for x in s.split(separator, maxsplit): y = x.strip() if y or y ==...
def reg_indicator(letter): """Return a regional indicator charater from corresponing capital letter. """ return 0x1F1E6 + ord(letter) - ord('A')
def calc_posterior(likelihood, prior, norm_list): """ Calculate the posterior probability given likelihood, prior, and normalization Positional Arguments: likelihood -- float, between 0 and 1 prior -- float, between 0 and 1 norm_list -- list of tuples, each tuple has two v...
def pretty_duration(seconds): """Return a human-readable string for the specified duration""" if seconds < 2: return '%d second' % seconds elif seconds < 120: return '%d seconds' % seconds elif seconds < 7200: return '%d minutes' % (seconds // 60) elif seconds < 48 * 360...
def bisect_right(a, x, key=None, lo=0, hi=None, rv=False): # pylint: disable=too-many-arguments """ binary search :param a: a list :param x: target value :param key: sort_attr :param lo: start_index :param hi: end_index :param rv: reverse :return: index of insert """ key = k...
def _sargs(row,x,y): """ return x, y, if row == True else y,x""" if row: return (x,y) else: return (y,x)
def check_type_and_values_of_alt_name_dict(alt_name_dict, alt_id_col, df): """ Ensures that `alt_name_dict` is a dictionary and that its keys are in the alternative id column of `df`. Raises helpful errors if either condition is not met. Parameters ---------- alt_name_dict : dict. A...
def FREQ_COUNT(src_column): """ Builtin frequency counts for groupby. Returns a dictionary where the key is the `src_column` and the value is the number of times each value occurs. >>> sf.groupby("user", ... {'rating_distinct':tc.aggregate.FREQ_COUNT('rating')}) """ return ("__builtin__freq_count_...
def soft_get(node, attr): """ If node has soft_get callable member, returns node.soft_get(attr), else return <SUB-ELEMENT> """ return node.soft_get(attr) if hasattr(node, 'soft_get') and callable(node.soft_get) else '<SUB-ELEMENT>'
def to_lowercase(words): """ Convert all characters to lowercase from list of tokenized words. Args: words (list): List of tokenized words. Returns: list: Tokenized words. """ new_words = [] for word in words: new_word = word.lower() new_words.append(new_wor...
def magnitude(x): """ Return the magnitude of ``x`` .. note:: If ``x`` is not an uncertain number type, returns :func:`abs(x)<abs>`. """ try: return x._magnitude() except AttributeError: return abs(x)
def _break_ip_address(cidr_ip_address): """ Function divides the input parameter into IP address and network mask. :param cidr_ip_address: IP address in format of IP/prefix_size :return: IP, prefix_size """ if "/" in cidr_ip_address: ip_address, prefix_size = cidr_ip_address.split("/") ...
def first_index_in_set(seq, items): """Returns index of first occurrence of any of items in seq, or None.""" for i, s in enumerate(seq): if s in items: return i
def sky_brightness(Dh, m, I_0): """ :param Dh: the horizontal diffuse irradiance :param m: the relative optical airmass :param I_0: the extraterrestrial irradiance :return: the sky's brightness noted as Delta """ return Dh * m / I_0
def get_approval_status(config, ref_doctype): """check the approval status for consumption""" for entry in config: if entry.get('ref_doctype') == ref_doctype: return entry.get('status') return 'Pending'
def format_fulltext_duration(seconds): """Format a duration as ``h hours, m minutes``. Parameters ---------- seconds : int Duration in seconds. Returns ------- str """ minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) if hours > 2: ...
def isIPAddress(s): """Return True if the string looks like an IP address: n.n.n.n where n is between 0 and 255 """ if not s: return False # see if there is a port specifier if s.find(':') > 0: return True if s == 'localhost': return True # special case for loopback...
def format_multiline_lines(lines): """Same as format_multline, but taking input pre-split into lines.""" out_lines = [] for i, line in enumerate(lines): if i != 0: if not line.strip(): line = '.' line = ' ' + line out_lines.append(line) return '\n'...
def _table_row(line): """ Return all elements of a data line. Return all elements of a data line. Simply splits it. Parameters ---------- line: string A stats line. Returns ------- list of strings A list of strings, containing the data on the line, split at white s...
def streamPrint(token: str = '', saveToken: str = '', printToken: bool = True): """ Helper function to take a token candidate, save destination, and print if requested. Args: token: New string to append. saveToken: Save token string stream. printToken: Returns: appended string w...
def weakchecksum(data): """ Generates a weak checksum from an iterable set of bytes. """ a = b = 0 l = len(data) for i in range(l): a += data[i] b += (l - i)*data[i] return (b << 16) | a, a, b
def _convert(expected_type, value): """ Check value is of or can be converted to expected type. """ if not isinstance(value, expected_type): try: value = expected_type(value) except: raise TypeError('expected ' + str(expected_type)) return value
def data_complete(star): """Checks if the star has the required data""" try: float(star[8]) except ValueError: return False return True
def get_attrs_key(data, key): """Lookup an attrs key in pyroute2 data.""" for attr_key, attr_value in data["attrs"]: if attr_key == key: return attr_value
def backtolang(exp): """ Takes a expression list and converts it back into a stupidlang expression. Parameters ---------- exp : list A list representing a parsed stupidlang expression Returns ------- str A string with the corrsponding stupidlang code Examples ...
def find_position(tile_type, level, tile_size): """Finds the first occurence of the given tile type found in the level, and returns the x,y coordinates of its centre as a 2-tuple. If not found, returns 0,0""" # iterate through all the level tiles for j, row in enumerate(level): for i, tile ...
def format_mongo_query(key, op, value): """ Format a mongo-style JSON query parameter. Parameters ---------- key: str Key to compare against within each item in the resource, e.g. ``formula``, ``band_gap`` or ``color``. op: str MongoDB operation, e.g. ``'$gt'``. value: Any ...
def _get_output_filename(dataset_dir, split_name, dataset): """Creates the output filename. Args: dataset_dir: The dataset directory where the dataset is stored. split_name: The name of the train/test split. Returns: An absolute file path. """ return '%s/%s_%s.tfrecord' % (dataset_dir, dataset, ...
def find_lcs(s1, s2): """find longest common string""" m = [[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)] mmax = 0 p = 0 len_s1 = len(s1) len_s2 = len(s2) for i in range(len_s1): for j in range(len_s2): if s1[i] == s2[j]: m[i + 1][j + 1] = m...
def proficiencyBonus(level, expertise=False): """ Return proficiency bonus for a given level to apply to a skill. """ return (((level - 1) / 4) + 2) * (1, 2)[expertise]
def already_on_command_line(existing_args_list, potential_command_line_args): """Utility method for checking if any of the potential_command_line_args is already present in existing_args. """ return any(potential_arg in existing_args_list for potential_arg in potential_command_line_args)
def to_roman(value: int, make_upper: bool = True) -> str: """ The presence of 500 (D) and 50 (L), coupled with the special handling of 400, 900, 40, 90, 4 and 9, make table lookup seem like the best approach. """ if value == 0: return 'Zero' if value > 3999: return f'{value:,}' thousands, value ...
def search_workspace(results, params, meta): """ Return result data from es_client.query and convert into a format conforming to the schema found in rpc-methods.yaml/definitions/methods/search_workspace/result """ return { "search_time": results["search_time"], "count": results["...
def ownRound(number): """ This method is resposable to round the number If the number is bigger than its converted integer number it will round for the next decimal number """ if int(number) != number: return (int(number)+1) else: return number
def _slugify(value: str) -> str: """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ # import unicodedata # value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') # value = re.sub('[^\w\s-]', '', value).strip().lower...
def recall_neg_conf(conf): """compute recall of the positive class""" TN, FP, FN, TP = conf if (TN + FP) == 0: return float('nan') return TN/float(TN+FP)
def prune_sorter_key(scene): """ Used by prune_scenerios to extract key for sorting. The key is the saved random value multiplied by the probability of choosing. """ p = 1.0 if 'P' in scene[1]: p = scene[1]['P'] return p * scene[1]['_rand']
def prettyprint_bool(b): """Convert a bool to text 'on' or 'off'.""" return "on" if b else "off"
def calculate_group_percent(group1, group2): """calculates one group's percentage of a two-group total""" if group1 + group2 == 0: return 0 else: return round(group1 * 100.0 / (group1 + group2), 2)
def tracked_result_dict(enum): """Converts the enumerator code for EtrackingResult to string, see openVR.h for documentation""" return { 1: 'TrackingResult_Uninitialized', 100: 'TrackingResult_Calibrating_InProgress', 101: 'TrackingResult_Calibrating_OutOfRange', 200: 'Tracking...
def create_schedule_file(csv_file_path: str, idf_output_file: str, obj_name: str, col_num: int, rows_skip: int, min_per_item: int): """Create Schedule:File object IDF file given inputs.""" sched_file_obj = ['Schedule:File,', f'\t{obj_name},', ...
def recursive_example(input): """ Simple Recursive Function """ if input <= 0: return input else: output = recursive_example(input - 1) return output
def parse_model_http(model_metadata, model_config): """ Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client) """ if len(model_metadata['inputs']) != 1: raise Exception("expecting 1 input, got {}".format...
def dict_value_div(dict, n): """Divide all the values in the dictionary by a number.""" result = {key: value / n for key, value in dict.items()} return result
def resolve_references(schema, context=None): """Resolve References within a JSON schema""" if context is None: context = schema if '$ref' in schema: address = schema['$ref'].split('/') assert address[0] == '#' schema = context for key in address[1:]: sche...
def next_term(n): """Generates next term in Collatz sequence after n.""" if n%2: return 3*n + 1 return n // 2
def remove_from_string(string, letters): """Given an original string and a string of letters, returns a new string which is the same as the old one except all occurrences of those letters have been removed from it.""" new_string = '' for char in string: if char not in letters: ne...
def calc_coord(X, Y, dX, dY, xm_mesa, ym_mesa, xm_pad, ym_pad) -> list: """ Calculate various coordinates for a device. >>> calc_coord(1, 1, 1000, 1000, 0, 0, 0, 0) [1.0, 1.0, 1.0, 1.0] >>> calc_coord(0, 3, 1000, 1000, 500, 700, 500, 500) [0.5, 3.5, 0.5, 3.7] :return: [X_pad, Y_pad, X_mes...
def _make_parameter_declarations(function, kind, types, sig, offset=0): """Generates variable declarations assigning elements of the ufunc buffer array to numbered local i/o pointers and values. """ parameter_declarations = "" for i in range(len(types)): if sig[i] in "vVpPfF": # vector ...
def largest_factor(n): """Return the largest factor of n that is smaller than n. >>> largest_factor(15) # factors are 1, 3, 5 5 >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40 40 >>> largest_factor(13) # factor is 1 since 13 is prime 1 """ "*** YOUR CODE HERE ***"...
def adjust_lenght(string, max_length): """Adjust the length of string.""" while len(string) > max_length: string = string[:-1] return string
def latitude_bounds(lat: float, lon: float, max_distance: float): """ Calculate the latitude bounds a point can have in order to be at a certain distance to a reference point. """ assert max_distance >= 0 return lat - max_distance * 1.02, lat + max_distance * 1.02
def par_auteur(name): """ Add 'par' to the author names """ author_phrase = '' if name: author_phrase = " par {},".format(name) return author_phrase
def search_function(magazine_list, user_input): """ This function takes in the list of magazines and the user search criteria and returns a sorted list :param magazine_list: list :param user_input: string :return: list """ filtered_list = [] magazines = sorted(magazine_list) ...
def mvalue_to_slots(nvalue, mvalue): """ convert center n an m into start and stop n """ startn = nvalue - mvalue stopn = nvalue + mvalue -1 return startn, stopn
def util_set2bitmap(bm): """ Enable bits specified in a bm set and return a bitmap bytearray """ s = bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") # Disable secondary bitmap if no 65-128 fields are present if bm.isdisjoint(range(65, 129)): bm.discard(1) ...
def intersects(box_a, box_b, grace, dynamic_grace): """ Checks whether two rectangles intersect or inside in other. Args: box_a <tuple> : First rectangle (x, y, w, h) box_b <tuple> : Second rectangle (x, y, w, h) grace <list> : Relaxation for intersecti...
def find_matching_episode(sdex, fpinfo): """ Find matching episode (season and episode number) from submitted entries """ episode_id = int(fpinfo.get('episode', 0)) season_id = int(fpinfo.get('season', 0)) for epdata in sdex.get('episodes', []): if int(epdata['season']) == season_id: ...
def flatten_partial_references(image_specs): """Resolve all partial references in each image spec to a concrete list. Turns this: example-image: partials: - foo another-example: partials: - bar - image: example-image - bat Into this: example-image: ...
def convert_sv_char(c): """ logic for shifting senate vote characters to real ASCII """ # capital letters shift 64 if 65 <= ord(c) - 64 <= 90: return chr(ord(c) - 64) # punctuation shift 128 else: try: return chr(ord(c) - 128) except ValueError: return...
def parse_token_clause(token_clause): """Parse the clause that could be either 'with', 'using', or 'without'.""" use_token = {"with": True, "using": True, "without": False}.get(token_clause) if use_token is None: raise Exception("Wrong clause specified: {t}".format(...
def calculateShift(points): """ calculate an average shift dG_clc - dG_exp """ number_of_points = len(points) sum_diff = 0.00 for pH, experiment, calculation in points: sum_diff += experiment - calculation return sum_diff/number_of_points
def relativespecpath(specfilename): """ relative spec path :param specfilename: :return: """ return 'specs/' + specfilename + '.csv'
def _flatten_list_of_lists(_2d_list): """Input a list of lists and output one single list""" flat_list = [] # Iterate through the outer list for element in _2d_list: if type(element) is list: # If the element is of type list, iterate through the sublist for item in ele...
def _get_xml_declaration(version='1.0', encoding='UTF-8'): """Gets XML declaration (for the specified version and encoding). :param version: XML version :param encoding: encoding :return: XML declaration :rtype: str """ return '<?xml version="' + version + '" encoding="' + encoding + '"?>'
def coefficient_of_performance(delta_T, source='air'): """ COP is function of temp difference source to sink. The quadratic regression is based on Staffell et al. (2012) https://doi.org/10.1039/C2EE22653G. """ if source == 'air': return 6.81 - 0.121 * delta_T + 0.000630 * delta_T**2 ...
def shunt(infix): """ Create a postfix regular expression from it's infix." Parameters: arg1 (String): Infix regular expression. Returns: String: The postfix equivalent. """ # Convert input to a stack like list infix = list(infix)[::-1] # Operator stack opers = [] ...
def map_uni_to_alphanum(uni): """Maps [0-9 A-Z a-z] to numbers 0-62.""" if 48 <= uni <= 57: return uni - 48 elif 65 <= uni <= 90: return uni - 65 + 10 return uni - 97 + 36
def wrap2(angle, wrap = 180.0): """ 2 sided wrap of angle to [-wrap, +wrap] angle and wrap may be positive or negative If wrap == 0 just returns angle ie don't wrap Wrap2 = (2 sided one positive one negative) wrap of angle to signed interval [-wrap, + wrap] wrap is half circle if wrap = 0 t...
def _justify_pair(pair, width=80, padding_with='.'): """align first element along the left margin, second along the right, padding spaces""" n = width - len(pair[0]) return '{key}{value:{c}>{n}}'.format(key=pair[0], value=pair[1], c=padding_with, n=n)
def parse_game_score(game_score): """Parse a list of scores from a game into sets. We have two cases: - A team scores at least one point. Then we can simply look for when the next score is lower than the previous score. - A team scores no points. Then we have to look for a string of...
def get_rrmgr_cmd(src, dst, compression=None, tcp_buf_size=None, connections=None): """Returns rrmgr command for source and destination.""" cmd = ['rrmgr', '-s', 'zfs'] if compression: cmd.extend(['-c', '%s' % str(compression)]) cmd.append('-q') cmd.append('-e') if tcp_...
def _breakdown_dict(dic: dict): """ Breaks down our whole bmw-json schema into a single dictionary. :param dic: a dictionary in our bmw-json schema. :return: a single dictionary containing every module and its "domain", "contextGroup" and "abstractionLayer" without any deeper lists or dictionaries. ...
def player_value_to_string(text): """ Parses the player's value from a string. Args: text: The standard string of a player's value from Transfermarkt. Returns: A float representing the player's value. If the value cannot be parsed, returns None. """ # Free transfer ...
def cumulative_distribution(distribution): """Return normalized cumulative distribution from discrete distribution.""" cdf=[] cdf.append(0.0) psum=float(sum(distribution)) for i in range(0,len(distribution)): cdf.append(cdf[i]+distribution[i]/psum) return cdf
def _nice_case(line): """Make A Lowercase String With Capitals (PRIVATE).""" line_lower = line.lower() s = "" i = 0 nextCap = 1 while i < len(line_lower): c = line_lower[i] if c >= "a" and c <= "z" and nextCap: c = c.upper() nextCap = 0 elif c in "...
def get_fish_xn_yn(source_x, source_y, radius, distortion): """ Get normalized x, y pixel coordinates from the original image and return normalized x, y pixel coordinates in the destination fished image. :param distortion: Amount in which to move pixels from/to center. As distortion grows, pixels w...
def line_item_type(d, i, r): """Get line item type from item. Using usage for now. Amazon billing offers usage|tax :param d: Report definition :type d: Dict :param i: Item definition :type i: Dict :param r: Meter reading :type r: usage.reading.Reading :return: payer_account_id ...
def width(region): """ Get the width of a region. :param region: a tuple representing the region with chromosome, start, end as the first 3 columns :return: an int """ return region[2] - region[1]
def d_theta_parabolic(C, k, clk): """ A downwards concave parabola of form: f(x) = -c(x)(x - a) Here: C -> x k -> c clk -> a """ return -1 * k * C * (C - clk)
def to_digits(number): """ Calculating the digits of the number """ digits = [] while number > 0: digits.append(number % 10) number = number // 10 digits.reverse() return digits
def get_sign_bit(num: int) -> int: """Returns the sign bit of a number (MSB of an unsigned int) Args: num: >>> get_sign_bit(128) 0 >>> get_sign_bit(-128) 1 """ return -(num >> num.bit_length())
def and_(a, b): """ Combines two :any:`Filters<Filter>` with an "and" operation, matching any results that match both of the given filters. :param a: The first filter to consider. :type a: Filter :param b: The second filter to consider. :type b: Filter :returns: A filter that matches b...
def append_to_list(lst, preffix): """ @param lst: @param preffix: @return: """ return [preffix + str(item) for item in lst]
def exclude_bracket(enabled, filter_type, language_list, language): """Exclude or include brackets based on filter lists.""" exclude = True if enabled: # Black list languages if filter_type == 'blacklist': exclude = False if language is not None: for ...
def int_to_dd(t): """ Takes an iterable of integers and returns a dot-decimal string. """ return '.'.join((str(x) for x in t))
def getEditIdCmd(column0): """return awk command to edit ids in GTF file""" return ('awk', '-v', 'FS=\\t', '-v', 'OFS=\\t', '-v', 'column={}'.format(column0 + 1), '{sub("^ENSTR", "ENST0", $column); sub("^ENSGR", "ENSG0", $column); sub("_PAR_Y", "", $column); print $0}')
def factorypath_entry_xml(kind, entry_id): """Generates an eclipse xml factorypath entry. Args: kind: Kind of factorypath entry. Example values are 'PLUGIN', 'WKSPJAR' entry_id: Unique identifier for the factorypath entry Returns: xml factorypath entry element with the ...
def prob1(l): """Accept a list 'l' of numbers as input and return a list with the minimum, maximum, and average of the original list. """ ans = [] ans.append(min(l)) ans.append(max(l)) ans.append(float(sum(l))/len(l)) return ans
def get_reference_to_embedded_list(event): # -*- coding: utf-8 -*- """This method takes a dict of the format shown below, and returns a reference to the "items" list found inside it. If the incoming 'event' parameter doesn't have the expected format, an empty list is returned. Here is an example in...
def process_dictionary (dictionary): """ `process_dictionary()` sorts the dictionary and removes duplicated words. * **dictionary** (*list*) : the input dictionary (while processing) * **return** (*list*) : the sorted dictionary without duplicated words """ return sorted(set(dictionary))
def ucwords(value: str): """Uppercase first letter of each word but leaves rest of the word alone (keeps existing case)""" words = [] for word in value.split(' '): if word: words.append(word[0].upper() + word[1:]) return ' '.join(words)
def verbose_name(obj): """Return the object's verbose name.""" try: return obj._meta.verbose_name except Exception: return ''
def pretty_bool(value): """Check value for possible `True` value. Using this function we can manage different type of Boolean value in xml files. """ bool_dict = [True, "True", "true", "T", "t", "1"] return value in bool_dict
def getByName(list, name): """ Return element by a given name. """ if list is None or name is None: return None for element in list: if element.get('name') is None: continue if element['name'] == name: return element return None
def apply_format(var, format_str): """Format all non-iterables inside of the iterable var using the format_str Example: >>> print apply_format([2, [1, 4], 4, 1], '{:.1f}') will return ['2.0', ['1.0', '4.0'], '4.0', '1.0'] """ if isinstance(var, (list, tuple)): new_var = map(lambda x: a...
def speed_convert(size): """ Hi human, you can't read bytes? """ power = 2**10 zero = 0 units = {0: '', 1: 'Kb/s', 2: 'Mb/s', 3: 'Gb/s', 4: 'Tb/s'} while size > power: size /= power zero += 1 return f"{round(size, 2)} {units[zero]}"
def pos_to_border_format(text): """Returns valid Bootstrap classes to label a ballot position border.""" return { 'Yes': 'border-yes', 'No Objection': 'border-noobj', 'Abstain': 'border-abstain', 'Discuss': 'border-discuss', 'Block': 'border-disc...