content
stringlengths
42
6.51k
def _to_bytes_or_false(val): """ An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicode or py3 str: return val.decode('ascii') - O...
def ris_ignoreValue_check(fieldsTuple, itemType_value): """ params: fieldsTuple, () itemType_value, str. return: fieldValue_dict """ # ris_element = fieldsTuple[0] ignore_value_list = fieldsTuple[2] fieldValue_dict = {} # for ignore_value in ignore_value_list: if...
def initvalue(cm, vf): """cm = coefficient multiplicateur vf = valeur finale vi = valeur initiale calcule la vi""" vi = vf / cm return vi
def get_instance_ids_for_instances(instances): """" Take list of instances (as returned by create_instances), return instance ids. """ return [instance.id for instance in instances]
def encode_string(v, encoding="utf-8"): """ Returns the given value as a Python byte string (if possible). """ if isinstance(encoding, str): encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore")) if isinstance(v, str): for e in encoding: try: ret...
def Trim(text): """Strip spaces from the text""" return str(text).strip()
def rotate_90(rot): """ >>> rotate_90(((0, 0), (1, 0), (2, 0), (3, 0))) ((0, 0), (0, 1), (0, 2), (0, 3)) >>> rotate_90(((0, 0), (0, 1), (0, 2), (0, 3))) ((0, 0), (1, 0), (2, 0), (3, 0)) """ r = tuple((-y, x) for (x, y) in rot) min_x = min(x for (x, y) in r) min_y = min(y for (x, y) i...
def static_params(log_dir, seed=123456789): """ Create the parameters for a parallel run. @param log_dir: The directory to store the results in. @param seed: The seed for the random number generators. @return: The configuration parameters. """ params = { 'ninputs': 784, 'trim': 1e-4, ...
def calculate_N50(list_of_lengths): """Calculate N50 for a sequence of numbers. Args: list_of_lengths (list): List of numbers. Returns: float: N50 value. """ tmp = [] for tmp_number in set(list_of_lengths): tmp += [tmp_number] * list_of_lengths.count(tm...
def _to_mel(data): """ Convert a MockedPymelNode to a fully qualified dagpath. :param MockedPymelNode data: A PyNode-like object. :return: A fully qualified dagpath. :rtype: str """ try: return data.__melobject__() except AttributeError: return data
def get_letter_grade_definitions(letter_grade: str) -> str: """ Returns the definition of the letter grade that is passed into the function Grading Scale - 89.50 - 100 = A \n 88.50 - 89.49 = B+ \n 79.50 - 88.49 = B \n 78.50 - 79.49 = C+ \n 69.50 - 78.49 =...
def _cleaned_title(raw_heading: str) -> str: """Return cleaned title of artifact name.""" return raw_heading.replace('test_', '').replace('_', ' ').title()
def sundaram(A, B): """ Sieve of Sundaram Generates the list of primes between A and B (both inclusive) Algorithm: https://en.wikipedia.org/wiki/Sieve_of_Sundaram Time Complexity: O(B log B) Space Complexity: O(B) :return: List of prime numbers :rtype: List[int] """ # Get new limit N = int((B-2)/2) # Mar...
def _concept_to_lf(concept): """ Parse concept. Since fixed recursion we don't have to worry about precedence """ op = "" if "or" in concept: op = "or" elif "and" in concept: op = "and" if op: op_index = concept.index(op) left = concept[:op_index] ...
def _set_process_name(func, process_name): """_set_process_name If process_name is not set on configuration file, func.__name__ is used as the process_name :param func: :param process_name: """ if len(process_name) == 0: process_name = func.__name__ return process_name
def check_step(step, interval): """ Check step number against a user-specified interval. Utility is used typically for visualization. - Negative numbers mean 'never visualize'. - Zero means 'always visualize'. Useful for checking whether the current step is an output step, or anyting else...
def convert_durations(metric): """ Convert session duration metrics from seconds to milliseconds. """ if metric[0] == 'avgSessionDuration' and metric[1]: new_metric = (metric[0], metric[1] * 1000) else: new_metric = metric return new_metric
def dict_keys(d: dict) -> tuple: """Returns a `tuple` of all the keys present within the dictionary `d`. Args: d (dict): A dictionary to fetch all the keys of. """ # I decided to use tuple as its immutable. return tuple(d)
def time2int(time_str: str) -> int: """Transform '01:57:00' to (int)157""" return int(time_str[:2] + time_str[3:5])
def generate_list(*args): """ Silly function #1 """ array = [] for entry in args: array.append(entry) return array
def _env_translate_action(action): """ This should only be used for the Tiger ENV. Parameters ---------- action : int The action to be translated. Returns ------- str A representation of the action in English. """ ACTION_OPEN_LEFT = 0 ACTION_OPEN_RIGHT = 1 ...
def _get_x_offset(value, location, side, is_vertical, is_flipped_x): """Return an offset along the x axis. Parameters ---------- value : float location : {'first', 'last', 'inner', 'outer'} side : {'first', 'last'} is_vertical : bool is_flipped_x : bool Returns ------- floa...
def preprocess_config(conf): """Preprocess config""" conf_dict = {} int_params = ["data.batch_size", "data.test_way", "data.test_support", "data.test_query", "data.query", "data.support", "data.way", "data.episodes", "data.gpu", "data.cuda", "train.patience", "model.nb_l...
def get_slice_objects(dataslices, dims): """Get the full ranges for z, y, x if upper bound is undefined.""" # set default dataslices if dataslices is None: dataslices = [] for dim in dims: dataslices += [0, dim, 1] starts = dataslices[::3] stops = dataslices[1::3] s...
def difference(f1_d, f2_d, out_f1_head, out_f2_head): """ Figures out the difference between two dictionaries and reports the difference Parameters ---------- f1_d : dict Dictionary for first fasta, chromosome names as values f2_d : dict Dictionary for second fasta, chromosom...
def get_early_out(hour_out, check_out, tolerance): """menghitung berapa lama pegawai pulang lebih awal""" if hour_out > check_out: if (hour_out - check_out) < tolerance: result = ' ' else: result = hour_out - check_out else: result = ' ' return re...
def format_hpa(p): """Text representation of atmospheric pressure""" if p is None: return "Pressure" if float(p) < 1: return "{}hPa".format(str(p)) return "{}hPa".format(int(p))
def convertTags(tags_str, table): """Convert a string of tags into a string of integer trough table.""" # Split str tags_l = tags_str.split() # Loop of convertion tags_int_l = [str(table[tag]) for tag in tags_l] # Convert as a string result = " ".join(tags_int_l) return result
def css_compatible(name): """Is the name suitable for use as a CSS class name? This is rough and ready!""" for c in name: if not c.isalnum() and c != '_': return False return True
def run_algo(op_list): """Execute all operations in a given list (multiply all matrices to each other).""" ops = op_list[::-1] # reverse the list; after all, it's matrix mult. result = ops[0] for op in ops[1:]: result = result * op return result
def list_projection(values, columns): #--------------------------------------<<< """Return a comma-delimited string containing specified values from a list. values = list of values. (E.g., as returned from a csv.reader().) columns = list of indices (0-based) for the columns that are to be included ...
def get_reverse_list(ori_shape, transforms): """ get reverse list of transform. Args: ori_shape (list): Origin shape of image. transforms (list): List of transform. Returns: list: List of tuple, there are two format: ('resize', (h, w)) The image shape before resize,...
def _expand_xytan(x, y): """ Undo _redux_xytan() transform """ a = 0.027 return x*a, y*a
def det_coords(detector_id): """ In direct, 1-1 correspondence as to how the NASA NICER team defined its detector array! """ coord_dict = {'06':(0,0),'07':(0,1),'16':(0,2),'17':(0,3),'27':(0,4),'37':(0,5),'47':(0,6),'57':(0,7), '05':(1,0),'15':(1,1),'25':(1,2),'26':(1,3),'35':(1,4),'36...
def get_debug_option_value(curr_value, options, option_name): """Common handling of debug options. - If the current value is truthy, then ignore the option value All current values should default to falsy, so they will only be truthy when someone is debugging the plugin code - If the requested opti...
def matches_query_type(event_type, query_type): """Determine if event type matches query type Event type is tested if it matches query type according to the following rules: * Matching is performed on subtypes in increasing order. * Event type is a match only if all its subtypes are matche...
def conseq(cond, true, false): """ Behaves like the tenary operator. """ if cond: return true else: return false
def sign(x): """Sign function. :return -1 if x < 0, else return 1 """ if x < 0: return -1 else: return 1
def pressure_NORMALIZED(p_num, norm_ref): """ Calculation of the normalized pressure as a function of frequency. :param p_num numerical results. :param norm_ref reference pressure for the normalization. :param p_norm normalized pressure. :return The normalized pressure as ...
def is_same_path(path_a, path_b): """Compares everything except the _id field. If the same, returns True, otherwise False""" for k, v in path_a.items(): if k == 'graph': for k1, v1 in v.items(): if k1 == '_id': pass elif v1 != path_b[k].get...
def search(user_input): """Takes the user input. Renders the result of search: - found meal/product that has the most fitting name - found table of replacements for that meal (sortable) - if meal not found: prompt to add""" return f"Searches the replacement for '{user_input}'"
def quoted_string_literal(s, d): """ SOQL requires single quotes to be escaped. http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_quotedstringescapes.htm """ try: return "'%s'" % (s.replace("\\", "\\\\").replace("'", "\\'"),) except TypeError as e...
def cmake_cache_path(name, value, comment=""): """Generate a string for a cmake cache variable""" return 'set({0} "{1}" CACHE PATH "{2}")\n'.format(name, value, comment)
def solve(n, k): """Return list smalles number from given integers with k elements removed. input: integers(n), integer(k) output: list, with k integers removed, and original order retained ex: solve(123056,4) = '05' ex: solve(1284569,2) = '12456' """ n_st = list(str(n)[::]) o_st = list...
def is_leap_year(year): """Determine whether a year is a leap year""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def get_argument_name_from_comment(comment): """ Deducts argument name from a comment. Used to get maeningful argument name from declaration like: void foo(int /* interesting_argument */, float /* even_more_interesting_argument */ """ name = comment.replace("/*", "").repla...
def floyd_warshall(graph): """ Takes an adjacency matrix graph of edge distances and returns a matrix of shortest distances between all pairs of vertices. Distances of -1 indicate there is no path between a pair of vertices. See: http://www.cs.cornell.edu/~wdtseng/icpc/notes/graph_part3.pdf :r...
def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_typ...
def err(msg): """ : Add basic boilerplate around error message. """ return f"Error: {msg}. See `--help` for more information."
def pairwise(lst, last=True): """Build pair data with all list values. Args: ===== last (bool): pair between first and last """ res = [(x, y) for x, y in zip(lst, lst[1:])] if last: res = res + [ (x, y) for x, y in zip(lst[-1:], lst[:1]) ] return res
def unravel_list_for_matlab(my_list): """ Unpack a list into a Matlab compliant format to insert in .m files. Args: my_list: (list) of str Returns: (str) that join the different str of the list, with ' """ result = "','".join(my_list) result = "'" + result + "'" retu...
def ldapQueryStringFromQueryStrings(operand, queryStrings): """ Combines LDAP query strings into a single query string. @param operand: An LDAP operand (C{u"&"} or C{u"|"}). @type operand: L{unicode} @param queryStrings: LDAP query strings. @type queryStrings: sequence of L{unicode} """ ...
def priority_to_severity(priority): """ coverts NetWitness priority to Demisto severity grade input: - 'Low' - 'Medium' - 'High' - 'Critical' output: - 0 Unknown - 1 Low - 2 Medium - 3 High - 4 Critical """ priority_grade_...
def get_shared_prefix(word1: str, word2: str) -> str: """ Get the substring in the beginning of word1 and word2 which both share. Parameters ---------- word1 : str word2 : str Returns ------- shared_prefix : str Examples -------- >>> get_shared_prefix("foo", "bar") ...
def basename(p): """Returns the final component of a pathname""" i = p.rfind('/') + 1 assert i >= 0 return p[i:]
def count_outliers(outlier_tuple): """Counts the number of tests that identified a datapoint as an outlier """ outlier_count = 0 for item in outlier_tuple: if item == -1: outlier_count += 1 return outlier_count
def calculate_monthly_debt_ratio(monthly_debt_payment, monthly_income): """ Calculates the monthly debt ratio. Converts the monthly debt payment and monthly income parameters to int values and divides the monthly debt payment by the monthly income to produce the monthly debt ratio. Paramet...
def hour2deg(valin): """ Converts hours or HMS input to decimal degrees. Parameters ---------- valin: float Input value in HMS. Can be either: \n - a string delimeted by : or spaces \n - a list of [H,M,S] numbers (floats or ints) Returns ------- valout ...
def saludar(nombre): """Funcion que recibe un nombre y regresa su saludo""" return 'Hola {}, buenos dias.'.format(nombre)
def get_changed_files(path="."): """ Retrieves the list of changed files. """ # not implemented return []
def lerp(v1: float, v2: float, u: float) -> float: """linearly interpolate between two values""" return v1 + ((v2 - v1) * u)
def any_dict_matches(dict_of_dicts, query_dict) -> bool: """ :param dict_of_dicts: :param query_dict: :return: """ return any( query_dict == sd for sd in dict_of_dicts.values() )
def get_f1_score(precision, recall): """ Calculate and return F1 score :param precision: precision score :param recall: recall score :return: F1 score """ return (2 * (precision * recall)) / (precision + recall)
def _dict_to_conf(dictionary): """Helper to format a dictionary into a layout.conf file.""" output = [] for key in sorted(dictionary.keys()): output.append('%s = %s' % (key, dictionary[key])) output.append('\n') return '\n'.join(output)
def _create_issue_title(err: Exception, command: str) -> str: """Generate a Github issue title based on given exception and command.""" return '{}:{} during "{}"'.format(type(err).__name__, str(err), command)
def mbuild(width, height): """Build a NxN matrix filled with 0.""" result = list() for i in range(height): result.append(list()) for j in range(width): result[i].append(0.0) return result
def convert_listvalue_to_ordinal(listdata): """ Convert list elements to ordinal values [5, 3, 3, 5, 6] --> [2, 1, 1, 2, 3] Parameters: ----------- listdata: list data Return: ------- ordinals: list with oridinal values Example: -------- >>> ordinals = convert_lis...
def _get_lr_epoch_fields(lr_change_epochs): """note that the change points exclude the head and tail of the epochs. """ lr_change_epochs = [int(l) for l in lr_change_epochs.split(",")] from_s = lr_change_epochs[:-1] to_s = lr_change_epochs[1:] return list(zip(from_s, to_s))
def interleaved_sum(n, odd_term, even_term): """Compute the sum odd_term(1) + even_term(2) + odd_term(3) + ..., up to n. >>> # 1 + 2^2 + 3 + 4^2 + 5 ... interleaved_sum(5, lambda x: x, lambda x: x*x) 29 """ def helper(f, g, k): if k == n: return f(k) # Swap even ...
def shorten(s, length): """ Shorten `s` to `length` by appending it with "...". If `s` is small, return the same string >>> shorten("very long string", 9) "very l..." >>> shorten("small", 10) "small" """ if len(s) > length: return s[:length - 3] + '...' else: re...
def check_line_intersection(line1, line2): """Given two line segments (each defined by two (x,y) pairs), return true if the two segments intersect and false if they do not.""" x1, y1 = line1[0] x2, y2 = line1[1] x3, y3 = line2[0] x4, y4 = line2[1] denom = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4) if...
def sources_list(sources, params): """ Adds defined list of sources to params Parameters ---------- sources : list Payment sources params : dict Default params Returns ------- dict params with sources """ if isinstance(sources, list): for sou...
def long_to_bytes(n): """ Convert a ``long int`` to ``bytes`` :param n: Long Integer :type n: int :return: ``long int`` in ``bytes`` format. :rtype: bytes """ byteList = list() x = 0 off = 0 while x != n: b = (n >> off) & 0xFF byteList.append(b) x = ...
def fix_uso_db_space(fqcn): """ NOTE, THIS IS A TEMP FIX. TO REPAIR WRONG IMPORTS FROM THE PAST """ if fqcn[0:3] == 'db.': return 'uso.' + fqcn else: return fqcn
def fix(x): """ Replaces spaces with tabs, removes spurious newlines, and lstrip()s each line. Makes it really easy to create BED files on the fly for testing and checking. """ s = "" for i in x.splitlines(): i = i.strip() if len(i) == 0: continue i = i.s...
def sql_dynamic_row_count_mysql(schemas: list) -> str: """Generates ans SQL statement that counts the number of rows in every table in a specific schema(s) in a mysql database""" sql_schemas = ', '.join(f"'{schema}'" for schema in schemas) return f""" WITH table_list AS ( SELECT table_name ...
def baseline_deletion_payload(baseline_list): """ Returns payload to delete baseline """ return { "BaselineIds": baseline_list }
def first_role_id_in_roles(roles): """ Return the first role ID found in list of roles.""" for role in roles: if not isinstance(role, dict): continue role_id = role.get('role') if not role_id: continue return str(role_id).strip()
def makeOfficialGlyphOrder(font, glyphOrder=None): """Make the final glyph order for 'font'. If glyphOrder is None, try getting the font.glyphOrder list. If not explicit glyphOrder is defined, sort glyphs alphabetically. If ".notdef" glyph is present in the font, force this to always be the first ...
def extract_cond_units(string): """ Takes a string and returns a list of floats representing the string given. Temporary capacity unit model. Usage:: test_string = 'mAh/g' end_value = extract_value(test_string) print(end_value) # "Gram^(-1.0) Hour^(1.0) MilliAmpere^(1.0)" :para...
def _merge_dictionaries(dict1, dict2): """ Recursive merge dictionaries. :param dict1: Base dictionary to merge. :param dict2: Dictionary to merge on top of base dictionary. :return: Merged dictionary """ for key, val in dict1.items(): if isinstance(val, dict): dict2_nod...
def mod_sum(integer): """ Takes a range and returns the sum of multiples of 3 or 5 below the range. """ return sum(x for x in range(integer) if x % 3 == 0 or x % 5 == 0)
def weight(a): """returns the weight of a vector. i.e. the No of nonzero entries""" return sum(map(bool,a))
def _indent(level): """Returns leading whitespace corresponding to the given indentation `level`. """ indent_per_level = 4 return ' ' * (indent_per_level * level)
def get_sha(repo, short=None): """Returns the commit id for the currently checked out version on the given repository object. If short is given, it is interpreted as the number of characters from the SHA that get returned. E.g. short=7 returns the first 7 characters, otherwise it returns the entire SHA1...
def _pad(block, n=8): """Pads the block to a multiple of n Accepts an arbitrary sized block and pads it to be a multiple of n. Padding is done using the PKCS5 method, i.e., the block is padded with the same byte as the number of bytes to add. Args: block (bytes): The block to pad, may be a...
def _hashify(d): """Hashify a dictionary to a list of tuples.""" result = [] for key, value in d.items(): if type(value) is dict: result.append((key, _hashify(value))) else: result.append((key, value)) return tuple(result)
def A004767(n: int) -> int: """Integers of a(n) = 4*n + 3.""" return 4 * n + 3
def wrap_quote(str): """Format quote.""" return f"> {str}\n"
def fast_exp_mod(b, e, m): """ e = e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n) b^e = b^(e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n)) = b^(e0*(2^0)) * b^(e1*(2^1)) * b^(e2*(2^2)) * ... * b^(en*(2^n)) b^e mod m = ((b^(e0*(2^0)) mod m) * (b^(e1*(2^1)) mod m) * (b^(e2*(2^2)) mod...
def _hjoin_multiline(join_char, strings): """Horizontal join of multiline strings """ cstrings = [string.split("\n") for string in strings] max_num_lines = max(len(item) for item in cstrings) pp = [] for k in range(max_num_lines): p = [cstring[k] for cstring in cstrings] pp.appen...
def aliased(cls): """Class decorator used in combination with @alias method decorator.""" orig_methods = cls.__dict__.copy() seen_aliases = set() for name, method in orig_methods.items(): if hasattr(method, '_aliases'): collisions = method._aliases.intersection(orig_methods.keys() | ...
def surrogate_escape_string(input_string, source_character_set): """ Escapes a given input string using the provided source character set, using the `surrogateescape` codec error handler. """ return input_string.encode(source_character_set, "surrogateescape").decode("utf-8", "surrogateescape")
def show_bits(text, max_lines=20, tail_lines_needed=4, max_chars=100, tail_chars_needed=30): """"Extract 600 characters from a line good for displaying""" lines = text.split('\n') if len(lines) > max_lines: lines = lines[:max_lines - tail_lines...
def color_plane(color, n=8): """ :param int color: Integer value denoting the colour of a player (1 for white, 0 for black). :param int n: Chess game dimension (usually 8). :return: An n x n list containing the same value for each entry, specified by the color. :rtype: list[list[int]] ...
def validate_list_of_strings(data: list) -> bool: """ Validate that input is a list of strings. Args: data (list): The data to be validated. Returns: bool: Validation passed. Raises: ValueError: Validation failed. """ if not isinstance(data, list): raise Va...
def partTimeStamp(timeStamp): """ Part the TimeStamp into date and time for writing in Measurementparameterlist :param timeStamp: :return: date, time """ date = timeStamp.split('_')[0] time = timeStamp.split('_')[1] return date, time
def euclidean(N: int, a: int) -> int: """ Uses the Euclidean Algorithm to calculate the GCD of `N` and `a`. """ remainder = N % a if remainder == 0: return a return euclidean(a, remainder)
def solve_iter(n, memo): """ Dynamic programming in a down-top way. The function can be enhanced by only store three elements, which can save sapce usage. """ if n == 1 or n == 2 or n == 3: return memo[n] else: for i in range(4, n+1): memo[i] = memo[i-1] + memo[i-2] +...
def fileExt(filename): """Returns file extension of inputed filename. One paramater is required: filename""" import os return os.path.splitext(filename)[1]