content
stringlengths
42
6.51k
def read_targets(tarfile): """ Return a tuple of targets Arguments: - `tarfile`: A tab-del file with EcoCyc names of sRNA and target """ if not tarfile: return None tars = [] try: for line in open(tarfile): tars.append(tuple(line.strip().split()[:2])) exce...
def difreq(seq): """ Does di-nucleotide shuffling of sequences, preserving the frequences. Code found here: https://www.biostars.org/p/66004/ """ from collections import defaultdict counts = defaultdict(lambda: defaultdict(int)) for a, b in zip(seq, seq[1:]): counts[a][b] += 1 ...
def get_values_of_key(key, list_dict): """lists values of different dict with same key Args: key (string): key of dictionary list_dict (list): list of dictionaries with equal keys but different values Returns: [list]: list of values from that key """ key_values = [] for ...
def get_filesize(filename): """Returns the size of a file, in bytes.""" import os try: # Since this function runs remotely, it can't depend on other functions, # so we can't call stat_mode. return os.stat(filename)[6] except OSError: return -1
def hslToRgb(h, s, l): """ convert from HSL (hue-saturation-luminosity) to RGB format h, s, l are all in the range [0,1] r, g, b will be in the range [0,255] see https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion """ r, g, b = 0, 0, 0 if s == 0: ...
def remove_items(headers, condition): """ Removes items from a dict whose keys satisfy the given condition. :param headers: a dict of headers :param condition: a function that will be passed the header key as a single argument and should return True if the header is to be removed. :returns:...
def get_step_index(curr_iter, decay_iters): """Get step when the learning rate is decayed. """ for idx, decay_iter in enumerate(decay_iters): if curr_iter < decay_iter: return idx return len(decay_iters)
def bprop_scalar_log(x, out, dout): """Backpropagator for primitive `scalar_log`.""" return (dout / x,)
def make_list(arg, obj_class): """ Convert an object of predefined class to a list of objects of that class or ensure a list is a list of objects of that class :param list[obj] | obj arg: string or a list of strings to listify :param str obj_class: name of the class of intrest :return list: lis...
def acceptance_probability(previousConfigCost, newConfigurationCost, NumberOfSteps): """ e = previous config e' = new config T = NumberOfSteps * Implementation of P(e, e', T). * The probability of making a transition from the current state s * to a candidate state ...
def msort_inv_count(arr: list) -> int: """Given an unsorted array, finds the number of inversions/swaps required to get a sorted array - MergeSort Method""" inv_count = mid = 0 if len(arr) > 1: # Find the mid-point of the array mid = len(arr) // 2 # Divide the array into two par...
def _clean_list(boris_seq): """ Deletes [x, 0, start], [x, 0, stop], [x, 0, start], [x, 0, stop]""" new_seq = [] j = 0 while j < (len(boris_seq) - 3): new_seq.append(boris_seq[j]) if not (boris_seq[j][1] == boris_seq[j+1][1] and boris_seq[j][1] == boris_seq[j+2][1] and boris_seq[j]...
def match_first_degree(name_list1, name_list2): """ First immediate matching between two possible name lists (exact equality between one item of list1 and of list2 :param name_list1: First list of names to match :param name_list2: Second list of names where to find a match :return init_match1: ...
def wheel(pos): """ Taken from https://badge.team/projects/rainbow_name Input a value 0 to 255 to get a color value. The colours are a transition r - g - b - back to r. :param pos: input position :return: rgb value """ if pos < 0: return 0, 0, 0 if pos > 255: pos -= 2...
def is_process(process): """Return ``True`` if passed object is Process and ``False`` otherwise.""" return type(process).__name__ == 'Process'
def min_max(input): """ Returns a tuple of min and max of the input list. Assume input is a non empty numeric list Use only builtin functions from: https://docs.python.org/2/library/functions.html """ return min(input),max(input)
def get_trid_isrc_full_con(tr_id, tr_exc, exid2next_dic, nexts_cisrc_dic): """ Get intron-spanning read count for transcript with ID tr_id. Also return if transcript exons are fully connected by intron-spanning reads (True, False). tr_id: Transcript ID tr_exc: Transcript exon c...
def zigZagEncode(n): """ ZigZag-Encodes a number: -1 = 1 -2 = 3 0 = 0 1 = 2 2 = 4 """ return (n << 1) ^ (n >> 31)
def read_unsigned_int(data: bytes, offset: int) -> int: """Retrieve 2 byte (unsigned int) value from bytes at specified offset""" return int.from_bytes(data[offset:offset + 2], byteorder="big", signed=False)
def cmdline_str_to_value(value): """ Given a string describing a value from the command line, convert it to an scalar :params str value: value as read from the command line in the format *[FORMAT:]VALUE*, format being **i** for integer, **f** for float, **s** for string, **b** for bool; exa...
def slice2limits(slices): """ Create a tuple of min,max limits from a set of slices Parameters: * slices: list of slices Returns: Tuple of minimum and maximum indices """ mins = [s.start for s in slices] maxs = [s.stop-1 for s in slices] return mins,maxs
def _sign(x): """ Return the sign of x INPUTS ------ x: number value to get the sign of OUTPUTS ------- s: signed int -1, 0 or 1 if negative, null or positive """ if (x > 0): return 1 elif (x == 0): return 0 else: return -1
def fontname(name=None): """ Sets the current font used when drawing text. """ global _fontname if name is not None: _fontname = name return _fontname
def atoi(s): """Convert the string 's' to an integer. Return 0 if s is not a number.""" try: return int(s or '0') except ValueError: return 0
def is_valid_int(int_to_test): """ Check if int_to_test is a valid integer Parameters ---------- int_to_test : str Returns ------- 'True' if int_to_test if a valid int, otherwise 'False' Examples -------- >>> is_valid_int('73') True >>> is_valid_int('5g8vdFp') ...
def _apply_nested(structure, fn): """Recursively apply a function to the elements of a list/tuple/dict.""" if isinstance(structure, list): return list(_apply_nested(elem, fn) for elem in structure) elif isinstance(structure, tuple): return tuple(_apply_nested(elem, fn) for elem in structure)...
def unique_array(items): """ If an item is duplicated, it appends a numeric suffix to it. f(items=(a, b, a, c)) => (a, b, a1, c) """ counts = dict() result = list() for i in items: counts[i] = counts.get(i, -1) + 1 result.append(str(i) + str(counts[i]) if counts[i] > 0 el...
def calMassTransferCoefficientEq1(Sh, GaDiCoi, CaPaDi): """ calculate mass transfer coefficient [m/s] args: Sh: Sherwood number GaDiCoi: gas component diffusivity coefficient [m^2/s] CaPaDi: catalyst particle diameter [m] """ # try/except try: # characteristic le...
def ternary_class_func(y): """Transform the data into a ternary task, as in Kannan Ambili.""" if y in (1,2): return 1 elif y in (3,4,5): return 2 elif y in (6,7): return 3 else: raise ValueError("The input value " + y + " is invalid")
def find_corners(points): """Top left and bottom right corners of the points provided""" xmin = xmax = points[0][0] ymin = ymax = points[0][1] for point in points: xmax = max(xmax, point[0]) xmin = min(xmin, point[0]) ymax = max(ymax, point[1]) ymin = min(ymin, point[1]) ...
def process_message_buffer(curr_message_buffer): """ Description =========== Helper function to process the communication between the master _hole_finder_multi_process and _hole_finder_worker processes. Since communication over a socket is only guaranteed to be in order, we have ...
def array_reverse_order_transform_next_index_to_current_index(position, move): """Transforms the position depending on the move. Works with the array_swap move type. This function transforms the position so that it can be used as the indice in the unaltered array, yet return the value it would have had...
def get_base_version(version): """ Given a version string, return the first two places. Ex: '3.2.1' --> '3.2' :param str version: The version string """ return ".".join(version.split(".")[0:2])
def dcpower_ssc_s(dcpower_tsm_s): """Returns LabVIEW Array equivalent data""" # func needs to be defined. dcpower_ssc = [] for dcpower_tsm in dcpower_tsm_s: dcpower_ssc.extend(dcpower_tsm.ssc) return dcpower_ssc
def tostring(s): """ Convert to a string with quotes. """ return "'" + str(s) + "'"
def get_annotations(o: object): """ Internal function to get the annotations of an object. Parameters ---------- o : object The object to get the annotations of. Returns ------- dict[str, Any] The annotations of the object. """ return o.__annotations__ if hasatt...
def __next_power_of_2(x): """ Returns the smallest r such that x < 2^r. """ return 1 if x == 0 else 1 << (x - 1).bit_length()
def pulse(CurrTime, force, duration, StartTime = 0.0,impulse_sign=1): """ Function to create a bang-bang or bang-coast-bang acceleration command Arguments: CurrTime : The current timestep (or an array of times) Amax : maximum acceleration of the command Vmax : maximum velocity of the resu...
def all_states(N, subspace='gef'): """ List all states in the desired subspace for N pigments Assumes hard-core bosons (no double-excitations of the same state) Parameters ---------- N : int Number of sites. subspace : container, default 'gef' Container of any or all of 'g'...
def lonely_integer(a): """Hackerrank Problem: https://www.hackerrank.com/challenges/lonely-integer/problem You will be given an array of integers. All of the integers except one occur twice. That one is unique in the array. Given an array of integers, find and print the unique element. For example, a...
def function(arg1,arg2=None): """ One line general description of what the function does. Parameters ---------- arg1 : data type and shape of arg1 High level description of what arg1 is. arg2 : data type and shape of arg2, followed by optional keyword H...
def linearize_colmajor(i, j, m, n): # calculate `u` """ Returns the linear index for the `(i, j)` entry of an `m`-by-`n` matrix stored in column-major order. """ return i + j*m
def blech32_polymod(values): """Internal function that computes the blech32 checksum.""" generator = [0x7d52fba40bd886, 0x5e8dbf1a03950c, 0x1c3a3c74072a18, 0x385d72fa0e5139, 0x7093e5a608865b] # new generators, 7 bytes chk = 1 for value in values: top = chk >> 55 # 25->55 chk = ((chk & 0x...
def efficiency_capacity_demand_difference(slots, events, X, **kwargs): """ A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in. """ overflow = 0 for row, event in enumerate(events): for col, slot in enumerate(slots): ...
def sparse_dot(vector1, vector2): """ >>> sparse_dot({1: 3, 3: 4}, {2: 4, 3: 5, 5: 6}) 20 """ dot = 0 for key1 in vector1: if key1 in vector2: dot = dot + vector1[key1] * vector2[key1] return dot
def get_csv_with_rev_path(csv_file): """Takes a csv file path and returns the name for a new version of the file, after addition of columns with info about reverse search results. """ return csv_file.rsplit('.', 1)[0] + '_1.csv'
def _colorize(t): """Convert (r, g, b) triple to "#RRGGBB" string For use with ``visualize(color=...)`` Examples -------- >>> _colorize((255, 255, 255)) '#FFFFFF' >>> _colorize((0, 32, 128)) '#002080' """ t = t[:3] i = sum(v * 256 ** (len(t) - i - 1) for i, v in enumerate(t...
def ensure_list(item): """Convert given item to list >>> from pyams_table.column import ensure_list >>> ensure_list(1) [1] >>> ensure_list('string') ['string'] >>> ensure_list(['a', 'b', 'c']) ['a', 'b', 'c'] """ if not isinstance(item, (list, tuple)): return [item] ...
def showHelpPopup(open_click, close_click): """ Display and hide the help popup depending on the clicked button. Code is based on https://community.plot.ly/t/any-way-to-create-an-instructions-popout/18828/3 by mbkupfer Positional arguments: open_click -- Open the popup close_click -- Close ...
def is_sequence(x): """ Returns whether x is a sequence (tuple, list). :param x: a value to check :returns: (boolean) """ return (not hasattr(x, 'strip') and hasattr(x, '__getitem__') or hasattr(x, '__iter__'))
def tokens2options(tokens): """Split the list of tokens into the options it specifies, even if there is a single option. Arguments: `tokens` -- the list of tokens to split, as provided by the tokenizer. Returns: A list of options, suitable for parsing. """ options = [] option = [] ...
def discrete_log(a, b, mod): """ returns smallest non-negative x s.t. pow(a, x, mod) == b % mod or None if no such x exists. Note: works even if a, b and mod are not pairwise coprime. Also note that it is assumed 0^0 is undefined although Python treats 0^0 as 1 (https://en.wikipedia.org/wiki/Zero_t...
def create_delete_query(table, match_key, match_val): """Summary Args: table (TYPE): Description match_key (TYPE): Description match_val (TYPE): Description Returns: TYPE: Description """ return """ DELETE FROM {} WHERE {} = {} """.format( ...
def renamed_prefix(cfg, old, new): """ Returns a new dictionary that has all keys of `cfg` that begin with `old` renamed to begin with `new` instead. """ renamed = dict(cfg) for k in cfg.keys(): if k.startswith(old): renamed[new + k[len(old):]] = renamed.pop(k) return ren...
def collect_codelist_enums(path, data, pointer=''): """ Collects values of ``codelist``, ``enum`` and ``openCodelist`` from JSON Schema. Adapted from collect_codelist_values """ codelists = {} if isinstance(data, list): for index, item in enumerate(data): codelists.update(co...
def extract_positions(line): """This method returns the position of each header in a KGTK file""" positions = {'id': line.index('id'), 'node1': line.index('node1'), 'node2': line.index('node2'), 'label': line.index('label')} return positions
def _validate_arg(value, expected): """Returns whether or not ``value`` is the ``expected`` type. """ if type(value) == expected: return True return False
def baryocentric_coords(pts,pt): """See e.g.: http://en.wikipedia.org/wiki/Barycentric_coordinate_system_%28mathematics%29""" xs,ys=list(zip(*pts)) x,y=pt det=(ys[1]-ys[2])*(xs[0]-xs[2])+(xs[2]-xs[1])*(ys[0]-ys[2]) l1=((ys[1]-ys[2])*(x-xs[2])+(xs[2]-xs[1])*(y-ys[2]))/float(det) l2=((ys...
def indices(a, func): """ Get indices of elements in an array which satisfies func >>> indices([1, 2, 3, 4], lambda x: x>2) [2, 3] >>> indices([1, 2, 3, 4], lambda x: x==2.5) [] >>> indices([1, 2, 3, 4], lambda x: x>1 and x<=3) [1, 2] >>> indices([1, 2, 3, 4], lambda x: x in [2, 4]) ...
def is_exception_class(name): """ Determine if a class name is an instance of an Exception. This returns `False` if the name given corresponds with a instance of the 'Exception' class, `True` otherwise """ try: return name in [cls.__name__ for cls in Exception.__subclasses__()] exce...
def calculate_pr(true,predicted): """ Calculate precision and recall from true and predicted data """ #true=[(true[2*i],true[2*i+1]) for i in range(int(len(true)/2))] #predicted=[(predicted[2*i],predicted[2*i+1]) for i in range(int(len(predicted)/2))] true=set(true) predicted=set(predicted) true_inter_pred=true &...
def binomial(n, k): """Compute n factorial by a direct multiplicative method.""" if k > n - k: k = n - k # Use symmetry of Pascal's triangle accum = 1 for i in range(1, k + 1): accum *= (n - (k - i)) accum /= i return accum
def get_dist_sq(point_a, point_b): """returns the distance squared between two points. Faster than the true euclidean dist""" return (point_a[0] - point_b[0])**2 + (point_a[1] - point_b[1])**2
def esi_radius(a, q): """ Calculate equivalent step index (esi) radius for a graded-index fiber. Args: a : radius of the fiber [m] q : parameter for graded index fiber [-] Returns: equivalent step index radius [m] """ return a * (1...
def get_feature_index(feature, features): """Get index from a feature in a list of features. Time is a static feature, it's represented by a value it's not needed for preprocessing Params: * feature: str feature to be preprocessed * feature: tuple<str> tuple of...
def update_c_delete_licensemd_export(main, file): """ Remove export of LICENSE.md """ updated = False content = "" complete = ['exports = ["LICENSE.md"]', "exports = ['LICENSE.md']"] incomplete = ['exports = ["LICENSE.md", ', "exports = ['LICENSE.md', ", 'exports = ["LICENSE.md",', ...
def get_extrude_profiles(timeline, entities): """Get the profiles used with extrude operations""" profiles = set() for timeline_object in timeline: entity_key = timeline_object["entity"] entity = entities[entity_key] if entity["type"] == "ExtrudeFeature": for profile in e...
def build_dictionary( levels, update_data): """" Creates a json-like level based dictionary for the whole path starting from /entry1 or whatever the first child of the root in the datatree is. """ for level in levels[::-1]: update_data = dict({level:update_data}) return update_data
def to_camelcase(name): """Convert snake_case name to CamelCase name. Args: name (str): The name of the tool. Returns: str: The CamelCase name of the tool. """ return "".join(x.title() for x in name.split("_"))
def create_batches_list(lst, batch_size): """Return list of batches. """ batches = [lst[i:i + batch_size] for i in range(0, len(lst), batch_size)] return batches
def has_errors(result): """This function checks if a GqlResponse has any errors. Args: result (GqlResponse): [data, errors] Returns: (boolean): Returns `True` if a transaction has at least one error. """ _, errors = result return len(errors) > 0
def is_gui_mode(argv): """Use GUI mode if no command line options are found.""" return len(argv) == 1
def int_to_bytes(x): """ 32 bit int to big-endian 4 byte conversion. """ assert(x < 2**32 and x >= -2**32) return [(x >> 8*i) % 256 for i in (3,2,1,0)]
def __is_valid_pos(pos_tuple, valid_pos): """This function checks token's pos is with in POS set that user specified. If token meets all conditions, Return True; else return False """ # type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool def is_valid_pos(valid_pos_tuple): """""" ...
def quicksort(vec): """ x is an integer array of length 0 to i. quicksort returns an array of length i in ascending order by recursively partitioning around a pivot until all elements are in the desired order. """ # Initialize vectors to hold partitioned values left = [] right = [] ...
def tolist(val): """ a convenience method to return an empty list instead of None """ if val is None: return [] else: return [val]
def is_terminal(x): """Returns whether a token is a terminal value.""" return type(x) == str and x.isalpha() or type(x) == float
def bbox_to_pixel_offsets(gt, bbox): """Helper function for zonal_stats(). Modified from: https://gist.github.com/perrygeo/5667173 Original code copyright 2013 Matthew Perry """ originX = gt[0] originY = gt[3] pixel_width = gt[1] pixel_height = gt[5] x1 = int((bbox[0] - originX) / ...
def dl_to_ld(dl): """dict of list to list of dict""" ld = [{key: value[index] for key, value in dl.items()} for index in range(max(map(len, dl.values())))] return ld
def is_bit_flag(n): """ Verifies if the input number is a bit flag (i.e., an integer number that is an integer power of 2). Parameters ---------- n : int A positive integer number. Non-positive integers are considered not to be "flags". Returns ------- bool ...
def mult_one(p,c,i): """\ Return a new plist corresponding to the product of the input plist p with the single term c*x^i """ new = [0]*i # increment the list with i zeros for pi in p: new.append(pi*c) return new
def bool_ext(rbool): """ Solve the problem that raw bool type is always True. Parameters ---------- rbool: str should be True of False. """ if rbool not in ["True", "False"]: raise ValueError("Not a valid boolean string") return rbool == "True"
def np_get_index(ndim,axis,slice_number): """ Construct an index for used in slicing numpy array by specifying the axis and the slice in the axis. Parameters: ----------- 1. axis: the axis of the array. 2. slice_number: the 0-based slice number in the axis. 3. ndim: the ndim of the ...
def create_unique_name(prefix, names, separator="_"): """ Creates a name starting with 'prefix' that is not in 'names'. """ i = 1 name = prefix while name in names: name = prefix + separator + str(i) i += 1 return name
def int_to_hex(input_int:int) -> str: """ Convert integer to hex string""" return '{:02x}'.format(input_int)
def ditto(lst,old,mark="."): """Show 'mark' if an item of lst is same as old. As a side-effect, update cache of 'old' values.""" out = [] for i,now in enumerate(lst): before = old.get(i,None) # get old it if exists out += [mark if before == now else now] old[i] = now # next time, 'now' is the...
def quote(string): """Quote a variable so it can be safely used in shell.""" return string.replace("'", "'\\''")
def get_sha_hash(input_string): """ Method returns the sha hash digest for a given string. Args: input_string (str): the input string for which sha has to be computed """ import hashlib return hashlib.md5(input_string).digest()
def get_prefix_less_dict(elements): """ Returns a dict containing each element with a stripped prefix This Function will return a dict that contains each element resulting on the element without the found prefix :param elements: List of all your shapes :type elements: list :return: The matchi...
def str_replace(str_in, sub_str, new_sub_str): """ This is an example; it is not meant to replace the built-in replace method of the str class. Within str_in, find and replace all occurrences of sub_str with new_sub_str :param str_in: :param sub_str: :param new_substr: :return:...
def is_palindrome(n): """ Reverse number and check with current number :param n: :return: """ # store locally temp = n rev = 0 while n > 0: # get digit one by one digit = n % 10 # find reverse number rev = rev * 10 + digit # divide the number ...
def triangle_area(base, height): """Returns the area of a triangle""" # You have to code here # REMEMBER: Tests first!!! return (1/2) * base * height
def get_ovs_flows(compute_node_list, ovs_br_list, of_protocol="OpenFlow13"): """ Gets, as input, a list of compute nodes and a list of OVS bridges and returns the command console output, as a list of lines, that contains all the OVS flows from all bridges and nodes in lists. """ cmd_out_lines = ...
def _replace_special_keys(key): """Replaces special keywords the user can use with their character equivalent.""" if key.lower() == "plus": return "+" if key.lower() == "comma": return "," if key.lower().startswith("delay"): return key.lower() return key
def voxel_content_mesh_index(batch_idx: int, mesh_idx: int) -> int: """Sets the voxel content to the mesh index.""" _ = batch_idx return mesh_idx + 1
def calls_for_current_steps(chain, current_steps): """The number of dynamodb calls that are required to iterate the given chain in the given number of steps. Here, steps is the number of values returned from next(iterator). In the table below, the first 3 next() calls are all served by the first response ...
def remove_outer_braces(braced_expr): """Remove the outer braces from a braced expression.""" return braced_expr[1:-1]
def _get_morphometry_data_suffix_for_surface(surf): """ Determine FreeSurfer surface representation string. Determine the substring representing the given surface in a FreeSurfer output curv file. For FreeSurfer's default surface 'white', the surface is not represented in the output file name pattern. For ...
def get_copy_dataset_type(dataset_type: str) -> str: """Return corresponding copy dataset type.""" if dataset_type in ['FewShotVOCDataset', 'FewShotVOCDefaultDataset']: copy_dataset_type = 'FewShotVOCCopyDataset' elif dataset_type in ['FewShotCocoDataset', 'FewShotCocoDefaultDataset']: copy_...
def validate_content_handling_strategy(content_handling_strategy): """ Property: Integration.ContentHandlingStrategy Property: IntegrationResponse.ContentHandlingStrategy """ valid_handling_strategy_values = ["CONVERT_TO_TEXT", "CONVERT_TO_BINARY"] if content_handling_strategy not in valid_hand...