content
stringlengths
42
6.51k
def rush(value=False, realtime=False): """ """ # dummy method. return False
def _get_phaseorder_frompar(nseg, npe, etl, kzero): """Return phase reordering indices in a slice""" phase_order = [] oneshot = [i*nseg for i in range(npe)] for i in range(nseg): phase_order += [j+i for j in oneshot ] return phase_order
def get_num_features(fp_size, kernel_size, padding, stride): """Computes the number of features created by a 2d convolution. See: http://cs231n.github.io/convolutional-networks/ """ return (fp_size - kernel_size + 2 * padding) / stride + 1
def extract_bits(bit, bit_dict): """Extract bits which is turend on (1). Args: bit (int): Bit to check. bit_dict (dict): Correspondance dict of bit and status. Return: valid_bit (:obj:`list` of :obj:`str`): List of bit which is turned on (1). Example: >>> s...
def deunicode(s): """Returns a UTF-8 compatible string, ignoring any characters that will not convert.""" if not s: return s return str(s.decode('utf-8', 'ignore').encode('utf-8'))
def get_provenance_record(caption, statistics, plot_type, ancestor_files): """Create a provenance record describing the diagnostic data and plot.""" record = { 'ancestors': ancestor_files, 'authors': ['schlund_manuel'], 'caption': caption, 'domains': ['global'], 'plot_typ...
def convert_error_code(error_code): """Convert error code from the format returned by pywin32 to the format that Microsoft documents everything in.""" return error_code % 2 ** 32
def dichotomy(list, value): """ list: array of integers in ascending order value: value to return its position in list return: False in value not in list, else the position of value in the list """ list_beginning = 0 list_end = len(list) list_middle = ((list_beginning+list_end)//2) if value not in lis...
def get_jaccard_similarity(s, t): """Computes the Jaccard Similarity of two sets""" return len(s.intersection(t)) / len(s.union(t))
def is_valid_credit_card(card_num): """ Checks if valid credit card by: 1. Multiply every other digit by 2, starting with second-to-last digit, then add products digits together. 2. For the ones not multiplied, add to other digits 3. If total % 10 is 0, number is valid """ first_total...
def title(txt): """ Provide nice title for parameterized testing.""" return str(txt).split('.')[-1].replace("'", '').replace('>', '')
def statsAndTransAreComplete(thisDir): """ Is the cycle done with both Stats and Transalign? """ import os import sys import xml.etree.ElementTree as ET import xml.parsers.expat as expat if not os.path.exists(thisDir): return False return (os.path.exists(os.path.join(thisDir, 'x...
def byte_to_gigabyte(byte): """ Convert byte value to gigabyte """ return byte / (1024.0 ** 3)
def get_mu(x, knots, mu=None): """ Find the knot interval index (mu) for a given value x This is a prerequisite for alg 2.20 and 2.21. Optional to supply a suggestion to try first. Throws on error. """ if mu != None: if x >= knots[mu] and x < knots[mu+1]: return mu fo...
def smart_split(line): """ split string like: "C C 0.0033 0.0016 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'" in the list like: ['C', 'C', '0.0033', '0.0016', 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'] """ flag_in = False l_val, val = [], [] for hh in line.s...
def clean_image_url(image_url): """Clean the image url to retrieve""" if image_url.startswith("//"): image_url = 'http:' + image_url return image_url
def compare_descr_lists (list1, list2): """ Compare two descriptor lists Parameters ---------- list1 : list list2 : list Returns ------- bool True if the list have exactly the same values in the same order. """ if len(list1) != len(list2): return False...
def _hc2rgb1(h, c): """ Takes the hue and chroma and returns the helper rgb1. Parameters ---------- h float The hue in degrees c float The chroma in [0, 1] """ try: h = float(h) c = float(c) except ValueError: raise ValueError("h (%s) and c (%s) must be (convertible to) floats" % (str(h), str(c)...
def nudge_min_max(k, x_min, x_max): """ This function applies a small shift on data range to make sure 0 is quantized to exact 0. k is int type, x_min and x_max are float type. 0 is important since there are lots of 0 in data, and it doesn't require operations. """ assert x_min <= x_max, "got x_mi...
def delete_nearby_point(interp_lane): """Avoid too close of two lines. :param interp_lane: the raw line :type interp_lane:list :return: the processed line :rtype:list """ x_pt_list = [] y_pt_list = [] cnt = 0 pre_x = cur_x = 0 pre_y = cur_y = 0 for pt in interp_lane: ...
def get_activity_charts_data(activity_actions, sync_user): """Get data for Translation activity and Review activity charts.""" human_translations = set() machinery_translations = set() new_suggestions = set() peer_approved = set() self_approved = set() rejected = set() for action in act...
def rm_sub_allele(allele: str) -> str: """ Remove suballele from a called named allele. (star)2.001 -> (star)2 (star)2.001_x2 -> (star)2x2 Args: allele (str): [description] Returns: str: [description] """ sv = allele.split("_")[-1] if "_" in allele else None main_al...
def _diff_bearings(bearings, bearing_thresh=40): """ Identify kinked nodes (nodes that change direction of an edge) by diffing Args: bearings (list(tuple)): containing (start_node, end_node, bearing) bearing_thresh (int): threshold for identifying kinked nodes (range 0, 360) Return...
def get_name_from_equivalent_ids(equivalent_ids, input_label=None): """Find name from equivalent id dict. :param: equivalent_ids: a dictionary containing all equivalent ids of a bio-entity. :param: input_label: desginated input_label """ if input_label: return input_label if not equival...
def fix_list(num_list): """ Hack to ensure my rounding didn't put values outside of 0-255 :param num_list: List of numbers. :return: The same number list. """ for index in range(len(num_list)): if num_list[index] > 255: num_list[index] = 255 elif num_list[index] < 0: ...
def extractParams(input): """ :Description: Takes the '-p' input and splits it into individual parameter :param input: POST Parameter :type input: String :return: Dictionary with the parameter as elements :note: This function is required to prepare the parameter for...
def get_part (partDict, node): """ get the subgraph name that node is partitioned into """ for part, nodelist in partDict.items(): if node in nodelist: return part
def cs_gp(Z=1, **kwargs): """Cross section for A(g,p)X averaged over E[.3, .8] GeV Returns cross section of photoproduction of a proton averaged over the energy range [.3, .8] GeV, in milibarn units. Arguments: Z {int} -- Number of protons of the target nucleus A {int} -- (optional) """ if 'A' in kwargs:...
def verify_boot_code(boot_code): """ Verifies the input boot code, computing the accumulator value and checking if the program runs infinitely. If an infinite loop is detected, the execution is halted. The function returns a tuple where the first element is the value of the accumulator when the program ...
def get_ref(subject, name): """Return a named reference to the given state.""" if hasattr(subject, "__ref__"): return subject.__ref__(name) else: return subject
def is_valid_c_name(name): """Checks if a name is a valid name for a C variable or function. Args: name (str): name to check Returns: valid (bool): 'True' if the name is valid, 'False' otherwise """ allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890' ...
def cleanup(val): """ Round up little number to 0 :param val: learned policy :return: """ if abs(val) < 1e-3: return 0 else: return val
def _dBInverse(dBSignal,dbScale=20.0): """ inverse calculation of dB to standard gain ratio """ return 10.0**(dBSignal/dbScale)
def create_lm_sequence(dp_json): """ Input: a JSON loaded from one of the `lean_step` JSONlines-formatted datasets Output: A string for language modelling. """ (prompt_keyword, prompt_text), (completion_keyword, completion_text) = list(dp_json.items()) prompt = prompt_keyword.upper() + " " + str(promp...
def row_col_indices(sc_point_gids, row_length): """ Convert supply curve point gids to row and col indices given row length Parameters ---------- sc_point_gids : int | list | ndarray Supply curve point gid or list/array of gids row_length : int row length (shape[1]) Returns...
def per_shortest(total, x, y): """Divides total by min(len(x), len(y)). Useful for normalizing per-item results from sequences that are zipped together. Always returns 0 if one of the sequences is empty (to avoid divide by zero error). """ shortest = min(len(x), len(y)) if not shortest...
def transform_into_dict(items, id_key='id', remove_id=True): """Transforms list into dictionary based on 'id' field. Args: remove_id (bool): removes id from dict. """ items_dict = {item[id_key]: item for item in items} if remove_id: for item in items: del item[id_key] ...
def _isnumeric(var) : """ Test if var is numeric, only integers are allowed """ return type(var) is int
def resolv_dict(dic, key): """This function used to get the value from gui json, replacement of eval :param dic: Dictionary to resolve :type dic: Dictionary(dict) :param key: Search Key for value needs to be found :type key: String or a tree :return: Value of the key :rtype: String """ ...
def replace_chars(a, chars): """ function that replaces the occurrences of chars in the string :param a: input string :param chars: chars to be replaced with "" (nothing) :return: """ string = a for char in chars: copy_string = string.replace(char, '') string = ...
def unpack_singleton(x): """Gets the first element if the iterable has only one value. Otherwise return the iterable. # Argument: x: A list or tuple. # Returns: The same iterable or the first element. """ if len(x) == 1: return x[0] return x
def multisplit(s, sep): """ Split a string based on a list of descriptors. Returns the split string as well as the characters found in the split (ie % & ...) """ splitchar = [] stack = [s] for char in sep: pieces = [] for substr in stack: pieces.extend(substr.split(...
def update_rgba_opacity(rgba, new_opacity=0.5): """Example usage: Input: 'rgba(44, 160, 44, 1)' Output: 'rgba(44, 160, 44, 0.5)' """ rgba_list = rgba[4:].strip('()').split(', ') rgba_list[-1] = str(new_opacity) return 'rgba('+', '.join(rgba_list)+')'
def list_intersection(list_1, list_2): """intersection of lists equivalent to set.intersection """ return [i for i in list_1 if i in list_2]
def bootset_bss_match(bootset, manifest, params): """ Validate that the bos session template bootset matches the specified kernel parameters and manifest """ try: bootset_type = bootset["type"] except KeyError: return False if bootset_type != "s3": return False tr...
def good_view(variable_name: str) -> str: """ Function for make pretty names of environmental variables. :param variable_name: str name of env variable. :return: str pretty view. """ return variable_name.lower().replace('_', ' ')
def compress_user(path, tilde_expand, tilde_val): """Does the opposite of expand_user, with its outputs. """ if tilde_expand: return path.replace(tilde_val, '~') else: return path
def prettyDict(d: dict) -> str: """Takes a dictionary and lays it out in "Key: Value" format, seperated by tabs.""" return "".join("{}: {}\t".format(i, d[i]) for i in d)
def get_uid_and_initial(key, value): """ Covert content returned from fom values get query to uid and initial values to populate a fom object Used by bulk load of values for a single object or bulk load of many objects, for example find all references of an article in one HTTP get, and build them without doing ad...
def comment(strng,indent=''): """return an input string, commented out""" template = indent + '# %s' lines = [template % s for s in strng.splitlines(True)] return ''.join(lines)
def get_gauss_smooth_sd_old(var): """ Sample from distributions :param var: either a dict describing a distribution, or a scalar value :return: mean value """ if type(var) == dict: if var['type'] == 'uniform': try: rv = var['smooth_sd'] except: ...
def int_if_digit(s: str): """Iterpret as integer if `s` represents a digit string.""" try: if s.isdigit(): return int(s) except AttributeError: pass return s
def range_check(low, high, expand=False, asint=False): """\ :py:func:`range_check` will verify that that given range has a *low* lower than the *high*. If both numbers are integers, it will return a list of the expanded range unless *expand* is :py:const:`False`, in which it will just return the hi...
def check_sub_format(long_string): """ Checks for sub formats instead of SRT formats""" if long_string[0] == '{': return False if long_string[0] == '1' or long_string[0] == '0': return True print("Not sure, first line is ", long_string.splitlines()[0]) return False
def get_file_type(file_name): """ Determine file type by extracting suffix of file_name """ if file_name is None: return None file_type = file_name.split(".")[-1].strip() if file_type == "nc": file_type = "netcdf" if file_type == "prmtop": file_type = "parm7" if ...
def find_bgn_fin_pairs(locts): """Find pairs of [bgn, fin] from loctation array """ if len(locts)==0: return [] else: bgns = [locts[0]] fins = [] for i1 in range(1, len(locts) - 1): # range from locts[1] to locts[-2] if locts[i1] - locts[i1 - 1] > 1: ...
def pil_crop_rect(rect_tup): """ x, y, w, h -> x, y, x+w, x+h """ x, y, w, h = [int(x) for x in rect_tup] return (x, y, x + w, y + h)
def degrees_to_handbrake_rotation(degrees): """Return value HandBrake uses for rotation""" if degrees == 90: return 4 elif degrees == 180: return 3 elif degrees == 270: return 7 else: return None
def img_resolution(width, height): """ Returns the image's resolution in megapixels. """ res = (width * height) / (1000000) return round(res, 2)
def _convert2dict(file_content_lines): """ Convert the corosync configuration file to a dictionary """ corodict = {} index = 0 for i, line in enumerate(file_content_lines): stripped_line = line.strip() if not stripped_line or stripped_line[0] == '#': continue ...
def _downsample(n_samples_in, n_samples_out): """Compute downsample rate""" downsample = int(n_samples_in // n_samples_out) if downsample < 1: raise ValueError("Number of samples should always decrease") if n_samples_in % n_samples_out != 0: raise ValueError("Number of samples for two co...
def convert_to_dict(columns, results): """ This method converts the resultset from postgres to dictionary interates the data and maps the columns to the values in result set and converts to dictionary :param columns: List - column names return when query is executed :param results: List / Tupple - r...
def twos_comp_forward(val, bits): #takes pythons version of signed numbers and converts to twos comp """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val ...
def clean_path(path): """Ensure a path is formatted correctly for url_for.""" if path is None: return '' if path == '/': return path return path.strip('/')
def MESeries(v): """ MExxxx series selector :param v: :type v: dict :return: :rtype: bool """ return v["platform"].startswith("ME")
def _test_active(options): """ Test the activate options. This has 3 possible values. """ if options['active']: activate = True elif options['inactive']: activate = False else: activate = None return activate
def brane_standardize(some_string): """ Parameters ---------- some_string : str Column of Strings to be standardized Returns ------- word : str Standardized String """ word = some_string.strip() word = word.replace(" ", "_") word = word.lower().capitalize() ...
def full_status(status): """Human readable status label.""" if status == 'p': return 'Passed' elif status == 'f': return 'Failed' elif status == 'i': return 'Ignored' return ''
def fix(l): """ Parameters ---------- l : object Returns ------- l : object If `l` is anything but a string, the return is the same as the input, but it may have been modified in place. If `l` is a string, the return value is `l` converted to a float. If `l` ...
def bbox_center_to_lowerleft(bbox): """convert a bbox of form [cx, cy, w, h] to [minx, miny, w, h]. Works for numpy array. """ cx, cy, w, h = bbox out_box = [[]]*4 out_box[0] = cx - 0.5*w out_box[1] = cy - 0.5*h out_box[2] = w out_box[3] = h return out_box
def convertToInt32(_bytes: list) -> list: """ Convert a list of Uint8 to Int32 Ported from javascript :param _bytes: a bytearray """ result = [] i = 0 while i < len(_bytes): result.append(_bytes[i] << 24 | _bytes[i + 1] << 16 | _bytes[i + 2] << 8 | _bytes[i + 3]) i += 4 ...
def error(message, code=400): """Generate an error message. """ return {"error": message}, code
def _reverse_bytes(mac): """ Helper method to reverse bytes order. mac -- bytes to reverse """ ba = bytearray(mac) ba.reverse() return bytes(ba)
def request_add_host(request, address): """ If the request has no headers field, or request['headers'] does not have a Host field, then add address to Host. :param request: a dict(request key, request name) of http request :param address: a string represents a domain name :return: request after add...
def eucl_dist_output_shape(shapes): """ Get the shape of the Euclidean distance output. Parameters ---------- shapes Input shapes to the Euclidean distance calculation. Returns ------- The shape of the Euclidean distance output. """ shape1, shape2 = shapes return sh...
def bytes_to_gb(n_bytes): """ Convert storage allowance bytes to a readable gb value """ if n_bytes < 1073741824: return '{:.2f}'.format(n_bytes / 1073741824) else: return '{:d}'.format(int(n_bytes / 1073741824))
def tflip(tup): """ Flips tuple elements. This is useful for list to screen coordinates translation. In list of lists: x = rows = vertical whereas on screen: x = horizontal """ return (tup[1], tup[0])
def fibo(n): """Fibo value with recursive algorithm""" if n <= 1: return n else: return fibo(n-1) + fibo(n-2)
def _node_tuple(d, keys): """Return `tuple` of `d` values ordered by `keys`. @type d: `dict` @type keys: `tuple` """ return tuple(d[k] for k in keys)
def latex(s): """ Transforma la cadena s en una cadena latex """ try: r = { 'th0': r'\theta_0', 'th1c': r'\theta_{1c}', 'th1s': r'\theta_{1s}', 'th0T': r'\theta_{0_T}' }[s] except KeyError: r = s return...
def fmttimelong(n): """ fmttimelong """ if n == 0: return 'complete!' try: n = int(n) assert n >= 0 and n < 5184000 # 60 days except: return '<unknown>' m, s = divmod(n, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) y, d = divmod(d, 365) dec, y = divm...
def get_ips(leases): """ get list of ips in leases leases is a dict from parse_dhcpd_config return ips as list for each host in leases dict """ return [leases[host]['ip'] for host in leases]
def factorial(n): """Calcula el factorial de n n int > 0 returns n! """ print(n) if n == 1: return 1 return n * factorial(n - 1)
def combination(n, r): """ :param n: the count of different items :param r: the number of select :return: combination n! / (r! * (n - r)!) """ r = min(n - r, r) result = 1 for i in range(n, n - r, -1): result *= i for i in range(1, r + 1): result //= i return ...
def create_function_def(return_type: str, function_name: str, func_params: list) -> str: """ Create a function definition/header Parameters: return_type (str): type of function's return value function_name (str): name of the function func_params (list): storing argument type...
def nvert(graph): """Gets the number of vertices, |V|, in the graph.""" return 1 + max((max(edge) for edge in graph))
def do_prepend(a, b): """ Adds the specified string to the beginning of another string. https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/test/integration/standard_filter_test.rb#L502 """ return '{}{}'.format(b, a)
def remove_nexus_metadata(d: dict): """ Returns a copy of the provided dictionary without nexus metadata (i.e. root keys starting with '_'). """ x = dict() for k in d.keys(): if not k.startswith('_'): x[k] = d[k] return x
def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f): """Returns the minor loss coefficient for a square reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. re: Reynold's number. f: Darcy friction factor. """...
def liangbarsky(left, top, right, bottom, x1, y1, x2, y2): """Clips a line to a rectangular area. This implements the Liang-Barsky line clipping algorithm. left, top, right and bottom denote the clipping area, into which the line defined by x1, y1 (start point) and x2, y2 (end point) will be clipp...
def get_ordered_indices(N, k): """Return a list of tuples of indices i,j,k, and l, such that 2*N > i > j > k > l. """ idx_list = [] # 2N because this sums over possible majoranas # num_fermions = N, num_majoranas = 2*N if k == 4: for i in range(2 * N): for j in range(i+1,...
def merge_mappings(areas_mapping, tlds_mapping): """ add tld to each area """ merged_mapping = areas_mapping.copy() for hostname, area in merged_mapping.items(): country = area['country'] area['tld'] = tlds_mapping[country] return merged_mapping
def unique(items): """ Python's equivalent of MATLAB's unique (legacy) :type items: list :param items: List to operate on :return: list """ found = set([]) keep = [] for item in items: if item not in found: found.add(item) keep.append(item) retur...
def get_file_name(file_path: str) -> str: """ Returns the name of a file from a file path. :param file_path: file path :return: name of file """ from pathlib import Path p = Path(file_path) return str(p.name)
def adjacent(g,node, n): """ find all adjacent nodes of input node in g g: 2D array of numbers, the adjacency matrix node: int, the node whose neighber you wanna find return: a list of ints """ result = [] for i in range(n): if g[node][i] != 0: result.append(i) ...
def ok(x): """ checks whether an intersection occured """ return (0<=x<=1)
def seq_match(seq0, seq1): """True if seq0 is a subset of seq1 and their elements are in same order. >>> seq_match([], []) True >>> seq_match([1], [1]) True >>> seq_match([1, 1], [1]) False >>> seq_match([1], [1, 2]) True >>> seq_match([1, 1], [1, 1]) True >>> seq_match(...
def getaxeslist(pidevice, axes): """Return list of 'axes'. @type pidevice : pipython.gcscommands.GCSCommands @param axes : Axis as string or list of them or None for all axes. @return : List of axes from 'axes' or all axes or empty list. """ axes = pidevice.axes if axes is None else axes if ...
def __decode_marking(m_t): """ Decode a marking using a dictionary Parameters --------------- m_t Marking as tuple Returns --------------- m_d Marking as dictionary """ m_d = {} for el in m_t: if el not in m_d: m_d[el] = 1 else: ...
def from_decimal(dec_data: str, delimiter: str = " ") -> bytes: """Converts decimal string into bytes object""" if delimiter == "": data = [dec_data[i:i+3] for i in range(0, len(dec_data), 3)] else: data = dec_data.split(delimiter) return bytes(map(int, data))