content
stringlengths
42
6.51k
def format(pat, x): """ format(pat, x) pat.format(x) """ return pat.format(x)
def Imprimir_Mensaje_2(msj): """ Imprime un mensaje :param msj: (str) Variable con el mensaje. :returns msjcomple: (str) Variable con el mensaje completo """ print('El mensaje es:',msj) msjcomple = 'El mensaje es: ' + msj return msjcomple
def days_in_month_360(month=0, year=0): """Days of the month (360 days calendar). Parameters ---------- month : int, optional (dummy value). year : int, optional (dummy value). Returns ------- out : list of int days of the month. Notes ----- Appropr...
def translateTaps(lowerTaps, pos): """Method to translate tap integer in range [0, lowerTaps + raiseTaps] to range [-lower_taps, raise_taps] """ # Hmmm... is it this simple? posOut = pos - lowerTaps return posOut
def get_nested_dict_entry_from_namespace_path(d, namespace_path): """Obtain the entry from a nested dictionary that corresponds to the path given in namespace format. A namespace path specifies the keys of the nested dictionary as a dot-separated string (e.g., "key1.key2.key3"). :param d: The nested dicti...
def filter_list(l): """return a new list with the strings filtered out""" return [i for i in l if not isinstance(i, str)]
def R_total(deltaT_sub, Q_drop): """ total thermal resistance of a single drop Parameters ---------- deltaT_sub: float temperature difference to the cooled wall in K Q_drop: float rate of heat flow through drop in W Returns ---------- ...
def _combine_texts_to_str(text_corpus, ignore_words=None): """ Combines texts into one string. Parameters ---------- text_corpus : str or list The texts to be combined. ignore_words : str or list Strings that should be removed from the text body. Returns ...
def structparse_ip_header_embedded_protocol(bytes_string: bytes): """Takes a given bytes string of a packet and returns information found in the IP header about the embedded protocol at the next level of encapsulation. Examples: >>> from scapy.all import *\n >>> icmp_pcap = rdpcap('icmp.pcap')\...
def hexify(ustr): """Use URL encoding to return an ASCII string corresponding to the given UTF8 string >>> hexify("http://example/a b") b'http://example/a%20b' """ # s1=ustr.encode('utf-8') s = "" for ch in ustr: # .encode('utf-8'): if ord(ch) > 126 or ord(ch) < 33: ...
def zenodo_fetch_resource_helper(zenodo_project, resource_id, is_record=False, is_file=False): """ Takes a Zenodo deposition/record and builds a Zenodo PresQT resource. Parameters ---------- zenodo_project : dict The requested Zenodo project. auth_parameter : dict The user's Zen...
def _should_reverse_image(format): """ Reverses the array format for JPG images Args: format: The format of the image input Returns: bool: True if the image should be reversed. False otherwise """ should_reverse = ["JPG"] if format in should_reverse: return True ...
def dice_coefficient(sequence_a, sequence_b): """(str, str) => float Return the dice cofficient of two sequences. """ a = sequence_a b = sequence_b if not len(a) or not len(b): return 0.0 # quick case for true duplicates if a == b: return 1.0 # if a != b, and a or b a...
def rotate_right(v, n): """ bit-wise Rotate right n times """ mask = (2 ** n) - 1 mask_bits = v & mask return (v >> n) | (mask_bits << (32 - n))
def make_queue_name(mt_namespace, handler_name): """ Method for declare new queue name in channel. Depends on queue "type", is it receive event or command. :param mt_namespace: string with Mass Transit namespace :param handler_name: string with queue time. MUST be 'command' or 'event' :return: ...
def process_molecules_for_final_mdl(molecules): """ grab molecule defintions from mdlr for final mdl. """ molecule_str = "" for idx, molecule in enumerate(molecules): diffusion_list = molecule[1]['diffusionFunction'] molecule_name = molecule[0][0] component_str = "" component...
def _human_size(nbytes): """Return a human-readable size.""" i = 0 suffixes = ["B", "KB", "MB", "GB", "TB"] while nbytes >= 1000 and i < len(suffixes) - 1: nbytes /= 1000.0 i += 1 f = ("%.2f" % nbytes).rstrip("0").rstrip(".") return "%s%s" % (f, suffixes[i])
def coerce_int(obj): """Return string converted to integer. .. Usage:: >>> coerce_int(49) 49 >>> coerce_int('49') 49 >>> coerce_int(43.22) 43 """ try: return int(obj) if obj else obj except ValueError: return 0
def build_shell_arguments(shell_args, apps_and_args=None): """Build the list of arguments for the shell. |shell_args| are the base arguments, |apps_and_args| is a dictionary that associates each application to its specific arguments|. Each app included will be run by the shell. """ result = shell_args[:] if...
def map_compat_network_region(network_region: str) -> str: """ Map network regions from old to new Note that network regions aren't really geos and there are networks within geos like DKIS (NT) and NWIS (WA) that need to retain their network_region """ if not network_region ...
def trim(value): """ Strips the whitespaces of the given value :param value: :return: """ return value.strip()
def remove_duplicates(any_list): """Remove duplicates without changing order of items Args: any_list (list): List of items Returns: list: List without duplicates """ final_list = list() for item in any_list: if item not in final_list: final_list.append(item...
def fib(n): """Recursive function to return the nth Fibonacci number """ if n <= 1: return n else: return(fib(n-1) + fib(n-2))
def second_half(string: str) -> str: """Return second half of a string.""" if len(string) % 2 != 0: raise ValueError(f"Ivalid string'{string}' with length {len(string)}") else: return string[int(len(string) / 2):]
def corner_points(m, cell_num, x, y): """ :param m: :param cell_num: :param x: :param y: :return: """ # Your code here sq_size = m / cell_num top_left = (x, y) top_right = (x + sq_size, y) bottom_left = (x, y + sq_size) bottom_right = (x + sq_size, y ...
def arduino_map(x, in_min, in_max, out_min, out_max): """ copy the function map from Arduino """ return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
def hex_to_bin(hex_number): """converts a hexadecimal number to binary""" return bin(int(hex_number, 16))[2:]
def __must_be_skipped(type_id): """Assesses whether a typeID must be skipped.""" return type_id.startswith("<dbo:Wikidata:")
def trailer(draw): """ trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME """ #'(' [testlist] ')' | '[' subscript ']' | '.' NAME return ''
def stringToInt(text): """ returns an integer if the string can be converted, otherwise returns the string @param text: the string to try to convert to an integer """ if text.isdigit(): return int(text) else: return text
def add_feed(msg, change, addition): """Adds an element to a given RethinkDB feed. Returns the msg and feed.""" if not change['old_val']: msg[addition] = change['new_val'][addition] elif change['new_val'][addition] != change['old_val'][addition]: msg[addition] = change['new_val'][addition] ...
def _is_vendor_extension(key): """Return 'True' if a given key is a vendor extension.""" return key.startswith("x-")
def is_dunder(attr_name: str) -> bool: """ Retuns whether the given attr is a magic/dunder method. :param attr_name: """ return attr_name.startswith("__") and attr_name.endswith("__")
def read_python_source(filename): """Read the Python source text from `filename`. Returns bytes. """ with open(filename, "rb") as fin: source = fin.read() return source.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
def _process_field(item, field_mapping): """ Process the mapping rules for a given field. :param item: The item from the Overpass response. :param field_mapping: The field mapping to apply (not pre-processed). :return: The new value of the field. """ # Handle the special address filter ...
def string_list(argument): """ Converts a space- or comma-separated list of values into a python list of strings. (Directive option conversion function) Based in positive_int_list of docutils.parsers.rst.directives """ if ',' in argument: entries = argument.split(',') else: ...
def merge_sort(elements): """ Use the simple merge sort algorithm to sort the :param elements. :param elements: a sequence in which the function __get_item__ and __len__ were implemented, as well as the slice and add operations. :return: the sorted elements in increasing order """ length = l...
def r_max(nxs): """ Find the maximum in a recursive structure of lists within other lists. Precondition: No lists or sublists are empty. """ largest = None first_time = True for e in nxs: if type(e) == type([]): val = r_max(e) else: val = e ...
def preprocess_codebook(codebook): """ Removes trajectories from keys and puts the trajectories into single symbol list format. Also removes skills with 0 frequency. """ trajectories = codebook.pop('trajectories') codebook_with_spaces = {} for key, value in codebook.items(): if key =...
def _fmt_and_check_cutoffs(cutoffs, vocab_size): """Parse and get the cutoffs used in adaptive embedding + adaptive softmax Parameters ---------- cutoffs The cutoffs of the vocab_size Size of the vocabulary Returns ------- cutoffs The parsed cutoffs, will be [0,...
def is_valid_value_for_issns(issns_dict): """ Expected issns_dict is a dict keys: 'epub' and/or 'ppub' values: issn (1234-5678) """ try: if len(issns_dict) == 0 or not set(issns_dict.keys()).issubset({'epub', 'ppub'}): raise ValueError( f"Expected dict which k...
def separate_content_and_variables(text, boundary='{# /variables #}'): """Separate variables and content from a Markdown file""" # Find boundary pos = text.find(boundary) # Text contains variables if pos > 0: return(text[:pos].strip(), text[(pos + len(boundary)):].strip()) # Text does...
def _parse_output_string(string_value: str) -> str: """ Parses and cleans string output of the multimeter. Removes the surrounding whitespace, newline characters and quotes from the parsed data. Some results are converted for readablitity (e.g. mov changes to moving). Args: string_value...
def flatten(data, parent_key="", separator=".", **kwargs): """ Reference Name ``flatten`` Turn a nested structure (combination of lists/dictionaries) into a flattened dictionary. This function is useful to explore deeply nested structures such as XML output obtained from devices over NETCONF. ...
def valid(number): """ Returns true if the number string is luhn valid, and false otherwise. The number string passed to the function must contain only numeric characters otherwise behavior is undefined. """ checksum = 0 number_len = len(number) offset = ord('0') i = number_len - ...
def pop_key(keys, pop_dict): """[Pop key and return value if one is in argument. otherwise just pop off dictionary] """ if isinstance(keys, list): for key in keys: pop_key(key, pop_dict) elif keys in pop_dict: return pop_dict.pop(keys) return None
def filter_id(mention: str): """ Filters mention to get ID "<@!6969>" to "6969" Note that this function can error with ValueError on the int call, so the caller of this function must take care of this """ for char in ("<", ">", "@", "&", "#", "!", " "): mention = mention.replace(char, ""...
def find_cycles(perm): """ Finds the cycle(s) required to get the permutation. For example, the permutation [3,1,2] is obtained by permuting [1,2,3] with the cycle [1,2,3] read as "1 goes to 2, 2 goes to 3, 3 goes to 1". Sometimes cycles are products of more than one subcycle, e.g. (12)(34)(5678) ...
def get_studies_with_attribute(attribute_name, attribute_dict): """Get identifiers of studies whose metadata contains the given attribute_name. Parameters ---------- attribute_name : str The name of an attribute to check against attribute_dict in order to identify studies containing thi...
def str2bool(v): """Convert a string to a boolean. Arguments: v {str} -- string to convert Returns: {bool} -- True if string is a string representation of True """ return str(v).lower() in ("yes", "true", "t", "1")
def attrname(obj, lower_name): """Look up a real attribute name based on a lower case (normalized) name.""" for name in dir(obj): if name.lower() == lower_name: return name return lower_name
def get_pkg_vendor_name(pkg): """ Method to extract vendor and name information from package. If vendor information is not available package url is used to extract the package registry provider such as pypi, maven """ vendor = pkg.get("vendor") if not vendor: purl = pkg.get("purl") ...
def draft_window_position(m) -> str: """One of the named positions you can move the window to""" return "".join(m)
def unique_char(string): """.""" individuals = set() string = ''.join(string.lower().split(' ')) for char in string: if char in individuals: return False individuals.add(char) return True
def set_difficulty(difficulty): """Set the difficulty level""" if difficulty == "easy": return 10 elif difficulty == "hard": return 5
def flatten_list(input_list): """Flatten multi-layer list ot one-layer.""" flattened_result = list() for ipt in input_list: if isinstance(ipt, (tuple, list)): flattened_result.extend(flatten_list(ipt)) else: flattened_result.append(ipt) return flattened_result
def path_to_file(path): """ Path to file /impl/src/main/java/com/mogujie/service/mgs/digitalcert/utils/CertUtil.java .../CertUtil.java :param path: :return: """ paths = path.split('/') paths = list(filter(None, paths)) length = len(paths) return '.../{0}'.format(paths[length ...
def add_zero_frame(matrix): """adds frame of zeros around matrix""" n = len(matrix) m = len(matrix[0]) res = [[0 for j in range(m+2)] for i in range(n+2)] for i in range(n+1): for j in range(m+1): if not(i == 0 or j == 0 or i == n+1 or j == m+1): res[i][...
def updated_full_record(full_record): """Update fields (done after record create) for Dublin Core serializer.""" full_record["access"]["status"] = "embargoed" return full_record
def merge(pinyin_d_list): """ :rtype: dict """ final_d = {} for overwrite_d in pinyin_d_list: final_d.update(overwrite_d) return final_d
def get_or_else(data, key, default_value = None): """ Tries to get a value from data with key. Returns default_value in case of key not found. """ if not data: return default_value try: return data[key] except: return default_value
def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: int ) -> float: """ Formula for amortization amount per month: A = p * r * (1 + r)^n / ((1 + r)^n - 1) where p is the principal, r is the rate of interest per month and n is the number of payments >>>...
def format_time(total_minutes: int) -> str: """Format time.""" end_hours, end_minutes = divmod(total_minutes, 60) end_hours = end_hours % 24 return f"T{end_hours:02g}:{end_minutes:02g}Z"
def message_warning(msg, *a, **kwargs): """Ignore everything except the message.""" return str(msg) + '\n'
def database_label(database): """Return normalized database label for consistency in file names. """ if database: return database else: return 'database_na'
def _diff(*a): """Returns difference between list t1, and list tn. """ return set.difference(*tuple(map(lambda x : set(x), a)))
def checksum(data): """ Compute a checksum for DATA. """ # Remove this later after development assert isinstance(data, bytearray), "data must be a bytearray" chk = data[0] for i in range(1, len(data)): chk ^= data[i] return chk
def get_ingredients(raw_text): """toma un texto y saca una lista de items y sus cantidades""" ingredients = [] for l in raw_text.split('\n'): if len(l) > 1: ingredients.append(l.split(' ')) return ingredients
def sane_parser_name(name) -> bool: """ Checks whether given name is an acceptable parser name. Parser names must not be preceded or succeeded by a double underscore '__'! """ return name and name[:2] != '__' and name[-2:] != '__'
def dictify(obj): """ Convert any object to a dictionary. If the given object is already an instance of a dict, it is directly returned. If not, then all the public attributes of the object are returned as a dict. """ if isinstance(obj, dict): return obj else: return { ...
def get_unique_survey_and_business_ids(enrolment_data): """Takes a list of enrolment data and returns 2 unique sets of business_id and party_id's :param enrolment_data: A list of enrolments :return: A pair of sets with deduplicated survey_id's and business_id's """ surveys_ids = set() business...
def format_interval(t): """ Formats a number of seconds as a clock time, [H:]MM:SS Parameters ---------- t : int Number of seconds. Returns ------- out : str [H:]MM:SS """ mins, s = divmod(int(t), 60) h, m = divmod(mins, 60) if h: return '{0:d}:{...
def join_with_function(func, values1, values2): """Join values using func function.""" return [ func(value1, value2) for value1, value2 in zip(values1, values2) ]
def _decode_json_int(o): """_decode_json_int Loads integers in a json as int. Pass in as parameter `object_hook` for `json.load`. """ if isinstance(o, str): try: return int(o) except ValueError: return o elif isinstance(o, dict): return {_decode_js...
def quersumme(integer): """bildet die Quersumme einer Zahl""" string = str(integer) summe = 0 for ziffer in string: summe = summe + int(ziffer) return summe
def load_env(context): """Get the current environment for the running Lambda function. Parses the invoked_function_arn from the given context object to get the name of the currently running alias (either production or staging) and the name of the function. Example: arn:aws:lambda:aws-regio...
def point_in_rectangle(point, rect_min, rect_max) -> bool: """ Check if a point is inside a rectangle :param point: a point (x, y) :param rect_min: x_min, y_min :param rect_max: x_max, y_max """ return rect_min[0] <= point[0] <= rect_max[0] and rect_min[1] <= point[1] <= rect_max[1]
def fib(n): """Fib without recursion.""" a, b = 0, 1 for i in range(1, n + 1): a, b = b, a + b return b
def LSC(X, Y): """Return table such that L[j][k] is length of LCS for X[0:j] and Y[0:k].""" n, m = len(X), len(Y) # introduce convenient notations L = [[0] * (m+1) for k in range(n+1)] # (n+1) x (m+1) table for j in range(n): for k in range(m): if X[j] == Y[k]: ...
def check_sender_agency(msg): """ deprecated. originally designed to help lookup the agency by the sender. this is problematic because occasionally a contact sends on behalf of multiple agencies. keeping this code for reference but it's not advisable to implement, i.e. could result in false matc...
def get_allowed_categories(version): """ Modelnet40 categories 0 - airplane 1 - bathtub 2 - bed 3 - bench 4 - bookshelf 5 - bottle 6 - bowl 7 - car 8 - chair 9 - cone 10 - cup 11 - curtain 12 - desk 13 - door 14 - dresser 1...
def option_to_text(option): """Converts, for example, 'no_override' to 'no override'.""" return option.replace('_', ' ')
def _decodebytestring(a): """ Convert to string if input is a bytestring. Parameters ---------- a : byte or str string or bytestring Returns ------- str string version of input """ if isinstance(a, bytes): return a.decode() else: return a
def fileobj_closed(f): """ Returns True if the given file-like object is closed or if f is a string (and assumed to be a pathname). Returns False for all other types of objects, under the assumption that they are file-like objects with no sense of a 'closed' state. """ if isinstance(f, str...
def extract_usernames(events): """Extracts the username from a list of password change events.""" output = [] for event in events: separate = event.decode().split(",") output.append(separate[1]) return output
def normalize_ctu_name(name): """Ensure name is in the normal CTU form.""" return name.title().replace('Ctu', 'CTU').replace('Iot', 'IoT')
def extract_object_from_included(object_type, object_id, included): """ Helper function that retrieves a specific object. @:param type String that represents the object class. @:param id String that represents the id of the object. @:param List of objects. @:return object in JSON or None """ ...
def flatten(tree): """Flattens a tree to a list. Example: ["one", ["two", ["three", ["four"]]]] becomes: ["one", "two", "three", "four"] """ i = 0 while i < len(tree): while isinstance(tree[i], (list, tuple)): if not tree[i]: tree.pop(i) if...
def _gr_xmin_ ( graph ) : """Get x-min for the graph >>> xmin = graph.xmin() """ # _size = len ( graph ) if 0 == _size : return 0 # x_ , y_ = graph.get_point ( 0 ) # return x_
def compare_slots(slots, quizproperty): """ compare slots to find if users answer matches """ proplower = quizproperty.lower() for key, val in slots.items(): if val.get('value'): lval = val['value'].lower() if lval == proplower: return True return False
def file_from_list_of_images(file_list, current_file, request): """ return filename from file_list depends of request request: position on the list """ if file_list: if request == "first": file = file_list[0] elif request == "previous": if current_file in file...
def points2d_at_height(pts, height): """Returns a list of 2D point tuples as 3D tuples at height""" if isinstance(pts, tuple): if len(pts) == 2: return [(*pts, height)] return [(pts[0], pts[1], height)] pts3d = [] for pt in pts: if len(pt) == 3: pts3d.appe...
def get_model_name(obj): """ returns the model name of an object """ return type(obj).__name__
def _tuplify(an_iterable): """Given an iterable (list, tuple, numpy array, pygamma.DoubleVector, etc.), returns a native Python type (tuple or list) containing the same values. The iterable is converted to a tuple if it isn't already a tuple or list. If it is a tuple or list, it's returned unchang...
def show_bad(spot, guess): """ Shows a bad door, given the prize spot & guess """ if spot==1: return 2 if guess==3 else 3 if spot==2: return 1 if guess==3 else 3 if spot==3: return 1 if guess==2 else 2
def get_rel_pos(abs_pos, ex_num, rel_starts): """Convert absolute position to relativ.""" if len(rel_starts) == 1: return abs_pos ex_num_0 = int(ex_num) - 1 rel_pos_uncorr = abs_pos - rel_starts[ex_num_0] rel_pos = rel_pos_uncorr if rel_pos_uncorr >= 0 else 0 return rel_pos
def c_string_to_str(array) -> str: """ Cast C-string byte array to ``str``. """ return bytes(array).partition(b'\0')[0].decode('utf-8')
def resume(server_id, **kwargs): """Resume server after suspend.""" url = '/servers/{server_id}/action'.format(server_id=server_id) req = {"resume": None} return url, {"json": req}
def get_tag_value(x, key): """Get a value from tag""" if x is None: return '' result = [y['Value'] for y in x if y['Key'] == key] if result: return result[0] return ''
def hinderedRotor2D(scandir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry='none'): """Read a two dimensional hindered rotor directive, and return the attributes in a list""" return [scandir, pivots1, top1, symmetry1, pivots2, top2, symmetry2, symmetry]