content
stringlengths
42
6.51k
def part_encode(part): """Encode a part of a JSON pointer. >>> part_encode("foo") 'foo' >>> part_encode("~foo") '~0foo' >>> part_encode("foo~") 'foo~0' >>> part_encode("/foo") '~1foo' >>> part_encode("foo/") 'foo~1' >>> part_encode("f/o~o") 'f~1o~0o' >>> part_enc...
def _match_linear_pattern(root, pattern): """ Use Depth First Search to match the pattern :param root: operation :param pattern: List[Node] :return: Return List[operation] if pattern matches entirely else [] """ op = root if not pattern or len(op.outputs) != 1: return [] no...
def parse_string_properties(properties): """Returns a dictionary corresponding to a list of properties in the form PROPERTY=VALUE""" prop_dict = {} for p_str in properties: k,v = p_str.split('=') prop_dict[k]=v return prop_dict
def rt_label(label, it = True): """ Rich text label: Format label with italic + bold HTML tags and replace '_' by HTML subscript tags Parameters ---------- label : string Name for the label to be converted, containing '_' for subscripts Returns ------- html_label : str...
def _CanViewViewpointContent(viewpoint, follower): """Returns true if the given follower is allowed to view the viewpoint's content: 1. Follower must exist 2. Viewpoint must not be removed by the follower """ if viewpoint is None or follower is None or not follower.CanViewContent(): return False re...
def claclulate_gini_index(classification1, classification2): """ calculate gini index for the split :param classification1: total count of records in classification 1 :param classification2: total count of records in classification 2 :return: calculated gini index for the split """ i...
def replaceAll(s, subs, rep): """ Replaces all substrings in a string with another string """ count = 0 for i in s: if i == subs: count += 1 return s.replace(subs, rep, count)
def _cxx_inc_convert(path): """Convert path returned by cc -E xc++ in a complete path.""" return path.strip()
def load4(b): """ Convert 4-bit binary in integer. """ return int(b, 2)
def array_to_string(array): """ Convert an array to a string with the elements separated by spaces i.e. [a,b,c] -> a b c Parameters ---------- array : list List of values Returns ------- string : str Values concatenated into a string """ str_array = [str(a) for ...
def get_filter_arg_vnode_type(f, arg): """Convert integer to file (vnode) type string.""" arg_types = { 0x01: "REGULAR-FILE", 0x02: "DIRECTORY", 0x03: "BLOCK-DEVICE", 0x04: "CHARACTER-DEVICE", 0x05: "SYMLINK", 0x06: "SOCKET", 0x...
def ProgressingPercentage(max_iter, i: int, next_step: int, step = 10): """ Function that shows the progressing percentage of an iterative process. @param max_iter (int): Maximal number of interations @param i (int): Current iteration @param next_step (int): Next step of the percentage (set to 0 for the first ite...
def get_resources_list(object_dict, resources_list): """ Method to get the list of resources labels :param object_dict: dictionary to describe XNAT object parameters :param resources_list: list of resources requested from the user :return: None if empty, 'all' if all selected, list otherwise ""...
def get_skip_comments(events, skip_users=None): """ Determine comment ids that should be ignored, either because of deletion or because the user should be skipped. Args: events: a list of (event_type str, event_body dict, timestamp). Returns: comment_ids: a set of comment ids th...
def sec2human(seconds) -> str: """ formats a timedelta object into semi-fuzzy human readable time periods. :param seconds: seconds to format into a time period :type seconds: int or float :return: human readable string :rtype: str """ periods = [ ('year', 60 * 60 * 24 * 365), ...
def _is_ctl(c): """Returns true iff c is in CTL as specified in HTTP RFC.""" return ord(c) <= 31 or ord(c) == 127
def str_to_bool(value): """Return the boolean value of the given string, or the verbatim value if it is not a string""" true_strings = ["true", "True"] if isinstance(value, str): return value in true_strings return value
def table_get_link_order(column, order_key, order): """Get the correct order parameter value for the table heading link""" if column == order_key: # If the user is clicking on the column again, they want the # oposite order if order == "desc": return "asc" else: ...
def stretch1d(n, nmin, nmax): """n: normalized to [0..1.0]""" return nmin + n * (nmax - nmin)
def camel_to_snake(s): """ converts CamelCase string to camel_case\ taken from https://stackoverflow.com/a/44969381 :param s: some string :type s: str: :return: a camel_case string :rtype: str: """ no_camel = ''.join(['_'+c.lower() if c.isupper() else c for c in s])...
def empty_reference_resolution(root=None, leave=None, update=None, create=None): """Generates an empty reference_resolution dictionary. Generates a ``Reference Resolution`` dictionary, where there are keys like 'root', 'leave', 'update', 'create' showing: root: the versions referenced directly to the ...
def _dict_builder(string): """Return a dictionary containing the occurrence of each char.""" occurrences = dict() for char in string: occurrences[char] = occurrences.get(char, 0) + 1 return occurrences
def _call_string(call): """Converts the provided call to string.""" positional_args = call[0] keyword_args = call[1] arg_strings = [] if positional_args: arg_strings.append(', '.join([str(arg) for arg in positional_args])) if keyword_args: arg_strings.append(', '.join( [f'{k}={v}' for (k, v...
def process_plan_result(plan_name, plan_result_dict): """ :param plan_result_dict: :param plan_name: A data structure example: { 'with_tester': { '6': { 'p': {'platform_id': 6, 'status': 'p', 'exec_qty': 0}, 'f': {'platform_id': 6, 'status': 'f', 'exec_qty': 0},...
def format_instrument_name(instrument_model, instrument_id): """ :type instrument_model: str :type instrument_id: str :rtype: unicode """ instrument_name = u'%s %s' % (instrument_model, instrument_id) return instrument_name
def single_or_default(sequence, condition=None, default=None): """ Returns the single item in a sequence that satisfies specified condition or specified default value if no item found. Raises error if more items found. Args: sequence: iterable Sequence of items to go through. ...
def make_failure_dict(error_message): """ Helper method to return failed query. """ return { 'status': 'failure', 'message': error_message }
def get_assume_role_input(role_arn, duration): """Create input for assume_role.""" return { 'RoleArn': role_arn, 'RoleSessionName': 'terrasnow_enterprise', 'DurationSeconds': duration }
def mandel(x, y, max_iters, value): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ i = 0 c = complex(x,y) z = 0.0j for i in range(max_iters): z = z*z + c ...
def _resource_graph(resource_sets): """Convert an iterable of resource_sets into a graph. Each resource_set in the iterable is treated as a node, and each resource in that resource_set is used as an edge to other nodes. """ nodes = {} edges = {} for resource_set in resource_sets: # ...
def are_all_equal(iterable): """ Returns ``True`` if and only if all elements in `iterable` are equal; and ``False`` otherwise. Parameters ---------- iterable: collections.abc.Iterable The container whose elements will be checked. Returns ------- bool ``True`` iff a...
def is_number_like(obj): """Return True if obj looks like a SINGLE number.""" try: obj = obj + 1 # might still be an array! obj = float(obj) except: return False # all cool return True
def parse_int_or_string(s): """Parse an integer or return the original string if it cannot be done.""" try: return int(s) except ValueError: return s
def longest_common_prefix(items1, items2): """ Return the longest common prefix. >>> longest_common_prefix("abcde", "abcxy") 'abc' :rtype: ``type(items1)`` """ n = 0 for x1, x2 in zip(items1, items2): if x1 != x2: break n += 1 return items1[:n]
def get_workdir_data(project_doc, asset_doc, task_name, host_name): """Prepare data for workdir template filling from entered information. Args: project_doc (dict): Mongo document of project from MongoDB. asset_doc (dict): Mongo document of asset from MongoDB. task_name (str): Task name...
def gen_result(err, success=False): """ gen_result returns the result dict with given params""" return {'results': {'Success': success, 'ErrorInfo': {'Message': err,}}}
def get_influencers(user_index, adjacency_matrix): """helper function to retrieve the influencing users for a certain user by passing the latter index to the function""" influencers = set() for e, col in enumerate(adjacency_matrix[user_index]): if adjacency_matrix[user_index][e] > 0: ...
def damerau_levenshtein_distance(word_1: str, word_2: str) -> int: """Calculates the distance between two words.""" inf = len(word_1) + len(word_2) table = [ [inf for _ in range(len(word_1) + 2)] for _ in range(len(word_2) + 2) ] for i in range(1, len(word_1) + 2): table[1][i] = i -...
def getZfromFileName(fileName, suppress = False): """ Lifts a redshift from a file name. Assumes file names are formatted as "...zX.XXX..." where X.XXX is the redshift. Parameters ---------- fileName : str suppress : bool, default = False Whether or not to suppress error messag...
def flatten_hierarchical_dict(original_dict, separator='.', max_recursion_depth=None): """Flatten a dict. Inputs ------ original_dict: dict the dictionary to flatten separator: string, optional the separator item in the keys of the flattened dictionary max_recursion_depth: posit...
def next_center(center, min, max): """set center to correct new value""" true_center = ((max - min) // 2) + min if true_center != center: return true_center elif true_center == min: return max else: return min
def new_list_with_mygene_ids(reporter_query_list, mygene_dict, gene_symbol_output_file): """Check all the symbols or IDs and find entrezgene/NCBI IDs if they exist. If they do not exist, then just keep symbol. Returns list in order of input. """ print("Step 3: START") print("Step 3: make replac...
def bitwise_xor_2lists(list1, list2): """ Takes two bit patterns of equal length and performs the logical inclusive XOR operation on each pair of corresponding bits """ list_len = len(list1) return_list = [None] * list_len for i in range(list_len): return_list[i] = list1[i] ^ list2[i...
def get_amount(amount): """encode amount (float number) to the cryptonote format. Hope its correct. Based on C++ code: https://github.com/byterubpay/bitbyterub/blob/master/src/cryptonote_core/cryptonote_format_utils.cpp#L211 """ CRYPTONOTE_DISPLAY_DECIMAL_POINT = 12 str_amount = str(amount) ...
def marathon_lb_domains(domains): """ marathon-lb takes comma-separated domain names for its HAPROXY_{n}_VHOST labels. Convert our space-separated domains to that form. """ return ",".join(domains.split())
def create_intervals(interval_length: int, n_intervals: int): """ Creates the intervals for observations. :param interval_length: Length of the one interval in seconds. :param n_intervals: Number of intervals. :return: List of intervals. """ return list(range(0, (interval_length * n_interval...
def VecAdd(a, b): """Return vector a-b. Args: a: n-tuple of floats b: n-tuple of floats Returns: n-tuple of floats - pairwise addition a+b """ n = len(a) assert(n == len(b)) return tuple([a[i] + b[i] for i in range(n)])
def rgb_to_hex(r, g, b): """Converts from three rgb numbers to their hex representations. """ assert (0.0 <= r <= 1.0) and (0.0 <= g <= 1.0) and (0.0 <= b <= 1.0), f"OOB:[{r}, {g}, {b}]" return "{0:02x}{1:02x}{2:02x}".format(int(r*255),int(g*255),int(b*255))
def greetings(name): """ Says hello to someone. :param name: str, whom to say hello to :return: str, greeting """ if name == 'LeChuck': raise ValueError return 'Hello, ' + name + '!'
def check_glue_records(records): """ Checks the glue records to see if the query turned up there """ if "address" not in records or records is None: return False looking_for = records["question"]._dn for address in records["address"]: # Check if that domain name is there ...
def lookup_format(dic): """ Return a dictionary readily useable for filter kwargs. Args: dic (dict): The dictionary to be formatted. Returns: dict: The same dictionary with the keys concatenated with '__in' """ return dict((k + '__in', v) for k, v in dic.items())
def str2bool(v): """String to boolean Args: v (string): String """ if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False
def _getCommandLine(pid): """ Given a PID, use the /proc interface to get the full command line for the process. Return an empty string if the PID doesn't have an entry in /proc. """ cmd = '' try: with open('/proc/%i/cmdline' % pid, 'r') as fh: cmd = fh.read() ...
def get_markdown_row(field, link, multi_field): """Creates a markdown table for the given fields """ # Replace newlines with HTML representation as otherwise newlines don't work in Markdown description = field["description"].replace("\n", "<br/>") show_name = field["name"] ecs = True if '...
def mpls_label_group_id(sub_type, label): """ MPLS Label Group Id sub_type: - 1: L2 VPN Label - 2: L3 VPN Label - 3: Tunnel Label 1 - 4: Tunnel Label 2 - 5: Swap Label """ return 0x90000000 + ((sub_type << 24) & 0x0f000000) + (label & 0x00ffffff)
def triangular_numbers(n): """[Triangular Numbers - A000217](https://oeis.org/A000217) Arguments: n (Integer): Index of the sequence Returns: Integer: Value of this sequence at the specified index """ return n * (n + 1) / 2
def classmethod2display(class_, method_, descriptor_): """Convert two strings such as "Lcom/mwr/example/sieve/AddEntryActivity;" and "onCreate" into a beautiful :) string to display Xrefs: "Lcom/mwr/example/sieve/AddEntryActivity; -> onCreate" """ return "{} -> {} ( {} )".format(class_, method_, de...
def color_to_notation(color): """Help function for converting colors to notation used by solver.""" notation = { 'green': 'F', 'white': 'U', 'blue': 'B', 'red': 'R', 'orange': 'L', 'yellow': 'D' } return notation[color]
def c_edge(Eg): """ Compute the Compton edge energy associatedwith a given gamma energy Parameters ---------- Eg : float Energy of gamma that compton scatters Returns ------- Ec : float Energy of Compton edge Notes ----- .. math:: E_c(E_\\gamma...
def is_requirement(line): """ Return True if the requirement line is a package requirement; that is, it is not blank, a comment, or editable. """ # Remove whitespace at the start/end of the line line = line.strip() # Skip blank lines, comments, and editable installs return not ( ...
def de_standardize(x, mean_x, std_x): """Reverse the procedure of standardization. :param x: data :param mean_x: mean of data :param std_x: standard deviation of data :return: destandardized data """ x = x * std_x x = x + mean_x return x
def hexxed(val): """Provides an easy way to print hex values when you might not always have ints.""" if isinstance(val, (int, bytes)): return f'0x{val:04x}' return val
def make_job_header(line): """ data line => string, dict """ datum = {} header_data = line.split(":") header_info = ['title', 'customer', 'start', 'stop', 'key'] for index, value in enumerate(header_data): datum[header_info[index]] = header_data[index] return datum['key'], datum
def extract_module_name(model_path): """ Extract the module's name from path Args: model_path(str): the module's class path Returns: str: the modules name """ class_name = "".join(model_path.split(".")[0].title().split("_")) return class_name
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ hand_len = 0 for frequency in hand.values(): hand_len += frequency return hand_len
def mean_longitude_degrees(time): """Returns mean longitude (in degrees) at time.""" return (280.460 + 0.9856474 * time) % 360
def remove_cipher_extension(file): """ Removes the '.cipher' extension if present """ if len(file) > 7 and file[-7:] == ".cipher": return file[:-7] return file
def refine_search_usno( ra: list, dec: list, oid: list, id_out: list, source: list, angDist: list, ) -> list: """ Create a final table by merging coordinates of objects found on the bibliographical database, with those objects which were not found. Parameters ---------- ra: list of float ...
def format_ovs_extra(obj, templates): """Map OVS object properties into a string to be used for ovs_extra.""" return [t.format(name=obj.name) for t in templates or []]
def data_index(data, key): """Indexing data for key or a list of keys.""" def idx(data, i): if isinstance(i, int): return data[i] assert isinstance(data, dict) if i in data: return data[i] for k, v in data.items(): if str(k) == str(i): ...
def part1(input_data): """ >>> part1(["939","7,13,x,x,59,x,31,19"]) 295 """ timestamp = int(input_data[0]) bus_ids = input_data[1].split(',') # Ignore bus_ids with 'x' bus_ids = map(int, filter(lambda bus_id: bus_id != 'x', bus_ids)) # (id, time_to_wait) # last_busstop = timestam...
def func_with_args(a: int, b: int, c: int = 3) -> int: """ This function has some args. # Parameters a : `int` A number. b : `int` Another number. c : `int`, optional (default = `3`) Yet another number. Notes ----- These are some notes. # Returns ...
def min_cut(ev): """Returns the index where the elements of the Fiedler vector change it sign and the difference between the two elements ev -- fiedler vector """ for i in range(1,len(ev)): if ev[i-1] < 0 < ev[i]: return (i, ev[i]-ev[i-1]) return (None,0)
def FormatTimedelta(delta): """Returns a string representing the given time delta.""" if not delta: return None hours, remainder = divmod(delta.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) return '%02d:%02d:%02d' % (hours, minutes, seconds)
def _first(iterable, what, test='equality'): """return the index of the first occurance of ``what`` in ``iterable`` """ if test=='equality': for index, item in enumerate(iterable): if item == what: break else: index = None else: raise N...
def validate_filter_size_3d(filter_size, in_depth, num_filter): """Validates filter size for 3d CNN operations""" if isinstance(filter_size, int): return [filter_size, filter_size, filter_size, in_depth, num_filter] elif isinstance(filter_size, (tuple, list)): len_filter = len(filter_size) ...
def percent_to_float(s: str): """Helper method to replace string pct like "123.56%" to float 1.2356 Parameters ---------- s: string string to replace Returns ------- float """ s = str(float(s.rstrip("%"))) i = s.find(".") if i == -1: return int(s) / 100 if...
def _NoTimeout(state): """False iff the command timed out.""" rcode, out = state return rcode == 0 or not ('TimeoutError' in out or 'timed out' in out)
def _splittag(url): """splittag('/path#tag') --> '/path', 'tag'.""" path, delim, tag = url.rpartition('#') if delim: return path, tag return url, None
def filter_distance(distance): """Returns the distance given in parameter rounded one decimal place""" # 10cm accuracy is enough for distances return round(distance, 1)
def f_restore(landscape, site, current, future, restore): """ aa = itertools.product(*[[True, False]] * 4) for bb in aa: print bb """ cpt = { # landscape, site, current, future) : restore (True, True, True, True): 0.8, (True, True, True, False): 0.0, (True, True, Fa...
def _create_key(key): """Create the AES key from the login path file header.""" rkey = bytearray(16) for i in range(len(key)): rkey[i % 16] ^= key[i] return bytes(rkey)
def sample_name_to_fasta_path(sample_name, dest_dir): """ Convert sample name like '70_HOW9' to a file path to save the .fasta file in :param sample_name: a string specifying a sample name, typically like '70_HOW9' :param dest_dir: directory to save to :return: file path string """ ...
def windows_path(pathname): """Convert non-Windows pathname into Windows pathname.""" return pathname.replace('/', '\\')
def create_show_alert_payload(context: str): """Create and return "showAlert" dictionary to send to the Plugin Manager. Args: context (str): An opaque value identifying the instance's action you want to modify. Returns: dict: Dictionary with payload to show an alert in the button. """ ...
def toStr(inp): """ Return a string representation of the input, enclosed with ' characters :param inp: the input value :returns: string -- input value, enclosed by ' characters """ return "'%s'" % inp
def fatorial(n): """ Retorna o fatorial de n. """ if n == 0 or n == 1: return 1 return n * fatorial(n-1)
def filter_proto_rpc_functions_for_message(functions): """Return function metadata only for functions to include for generating proto rpc messages.""" functions_for_proto = {"public", "CustomCode"} return [ name for name, function in functions.items() if function.get("codegen_method"...
def design_node_dict_update(design_node_map): """ make one level dictionary for design map for easy processing :param design_node_map: design node map content :return: dict """ d = {} for item in design_node_map: if item["DesignNode"] == "Switch-A" and item.get('PhysicalNode'): ...
def FormatFigureHTML(title, caption, figure_html): """Converts a given gnuplot plot into an HTML-formatted string with captions underneath explaining the plot. """ if caption: l = ['<tr><td align="center">', '<p class="gnuplot_captions">%s</p>' % (caption), '</td></tr>'...
def group_by(sequence, key): """ Groups items of a sequence according to specified key selector and creates result values as (key, group) pairs. Args: sequence: iterable Sequence of items to go through. key: callable Item's key selector. Ret...
def _blockdevice_id(dataset_id): """ A blockdevice_id is the unicode representation of a Flocker dataset_id according to the storage system. """ return u"flocker-%s" % (dataset_id,)
def checksum_match(buf, checksum): """ Returns the index at which the checksum matches Or False if the checksum matches never @param buf: buffer including the checksum part """ c = 0x1234567 for i, b in enumerate(buf[4:]): c += b * (i+1) if (c == checksum): return...
def jpath(path, js, default=None): """ XPath for JSON! :param path: a list of keys to follow in the tree of dicts, written in a string, separated by forward slashes :param default: the default value to return when the key is not found >>> jpath('message/items', {'message':{'items':...
def endsWith(str, suffix): """Return true iff _str_ ends with _suffix_. >>> endsWith('clearly', 'ly') 1 """ return str[-len(suffix):] == suffix
def _step_to_value(step, num_steps, values): """Map step in performance to desired control signal value.""" num_segments = len(values) index = min(step * num_segments // num_steps, num_segments - 1) return values[index]
def in_place_merge(a, b): """ Recursively merges second dict into the first. """ if not isinstance(b, dict): return b for k, v in b.items(): if k in a and isinstance(a[k], dict): a[k] = in_place_merge(a[k], v) else: a[k] = v return a
def transpose(a): """transpose(a) Transposes a list of lists. """ return [[a[j][i] for j in range(len(a))] for i in range(len(a[0]))]
def _get_attribute_counts(sequence): """ counts each unique attribute in a sequence :param sequence: observed sequence of integers :type sequence: list of int :return: dictionary with keys as attribute counts and values as counts of these attribute_counts :rtype: dictionary (str -> int) ...
def cube(x): """Given a number x, returns its cube (x^3)""" return x * x * x