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])) except IOError: return None return tars
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 return dict((k, dict(v)) for k,v in counts.items())
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 i in range(len(list_dict)): if key in list_dict[i]: key_values.append(list_dict[i][key]) return key_values
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: r, g, b = l, l, l else: def converter( p, q, t ): if t < 0: t += 1 if t > 1: t -= 1 if t < 1/6: return p + (q - p) * 6 * t if t < 1/2: return q if t < 2/3: return p + (q - p) * (2/3 - t) * 6 return p q = l * (1 + s) if l < 0.5 else l + s - l * s p = 2 * l - q r = converter(p, q, h + 1/3) g = converter(p, q, h) b = converter(p, q, h - 1/3) return int(r * 255), int(g * 255), int(b * 255)
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: a dict, possibly empty, of headers that have been removed """ removed = {} keys = filter(condition, headers) removed.update((key, headers.pop(key)) for key in keys) return removed
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: list of objects of the predefined class :raise TypeError: if a faulty argument was provided """ def _raise_faulty_arg(): raise TypeError("Provided argument has to be a list[{o}] or a {o}, " "got '{a}'".format(o=obj_class.__name__, a=arg.__class__.__name__)) if isinstance(arg, obj_class): return [arg] elif isinstance(arg, list): if not all(isinstance(i, obj_class) for i in arg): _raise_faulty_arg() else: return arg else: _raise_faulty_arg()
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 s' is specified by the acceptance probability P(). * e ==> getCost(s) * e' ==> getCost(s') * T ==> Temperature [number of steps/iterations in our setting]. * * s and s' are configurations in our setting. * * According to the kirkpatrick 1983 paper: * P(e, e', T) = 1 if e' < e * exp( -(e' - e) / T ) otherwise */ """ if newConfigurationCost < previousConfigCost: return 1 else: acceptance_prob = pow(2.7, -(newConfigurationCost - previousConfigCost) / NumberOfSteps) return acceptance_prob
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 parts left_arr = arr[:mid] right_arr = arr[mid:] # Recursively sort the two parts inv_count = msort_inv_count(left_arr) inv_count += msort_inv_count(right_arr) i = j = k = 0 # For each element in the two arrays, compare the elements # at the same index and replace the original array while i < len(left_arr) and j < len(right_arr): if left_arr[i] <= right_arr[j]: arr[k] = left_arr[i] i += 1 else: arr[k] = right_arr[j] j += 1 inv_count = inv_count + (mid - i) k += 1 # Copy any elements remaining in the left array while i < len(left_arr): arr[k] = left_arr[i] i += 1 k += 1 # Copy any elements remaining in the right array while j < len(right_arr): arr[k] = right_arr[j] j += 1 k += 1 # Return the inversion count return inv_count
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][1] == boris_seq[j+3][1]): j += 1 else: j += 3 #append the last three entries. while j <= len(boris_seq)-1: new_seq.append(boris_seq[j]) j += 1 return new_seq
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: :return init_match2: :return ind_match1: Indices of second list that correspond to each given item of list 1 if exists (-1 otherwise) :return ind_match2: Indices of first list that correspond to each given item of list 2 if exists (-1) otherwise """ if name_list1 is None or name_list2 is None: return None, None, None, None init_match1 = [''] * len(name_list1) init_match2 = [''] * len(name_list2) ind_match1 = [-1] * len(name_list1) ind_match2 = [-1] * len(name_list2) flatten_list1 = [item for sublist in name_list1 for item in sublist] flatten_list2 = [item for sublist in name_list2 for item in sublist] indflat_1 = [i for i in range(0, len(init_match1)) for item in name_list1[i] if init_match1[i] == ''] indflat_2 = [i for i in range(0, len(init_match2)) for item in name_list2[i] if init_match2[i] == ''] for i in range(0, len(name_list1)): for name in name_list1[i]: if name in flatten_list2: init_match1[i] = name ind_match1[i] = indflat_2[flatten_list2.index(name)] break for i in range(0, len(name_list2)): for name in name_list2[i]: if name in flatten_list1: init_match2[i] = name ind_match2[i] = indflat_1[flatten_list1.index(name)] break return init_match1, init_match2, ind_match1, ind_match2
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 -= 255 if pos < 85: return int(255 - pos * 3), int(pos * 3), 0 if pos < 170: pos -= 85 return 0, int(255 - pos * 3), int(pos * 3) pos -= 170 return int(pos * 3), 0, int(255 - (pos * 3))
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 count. exid2next_dic: exon ID to NEXT ID mapping nexts_cisrc_dic: Connected NEXT IDs with format "NEXT1,NEXT2" and mapping: "NEXT1,NEXT2" -> connecting IS read count >>> exid2next_dic = {"t1_e1" : "NEXT1", "t1_e2" : "NEXT2", "t1_e3": "NEXT3", "t2_e1": "NEXT4"} >>> nexts_cisrc_dic = {"NEXT1,NEXT2": 4, "NEXT2,NEXT3": 2} >>> get_trid_isrc_full_con("t1", 3, exid2next_dic, nexts_cisrc_dic) (6, True) >>> nexts_cisrc_dic = {"NEXT2,NEXT3": 5} >>> get_trid_isrc_full_con("t1", 3, exid2next_dic, nexts_cisrc_dic) (5, False) >>> get_trid_isrc_full_con("t2", 1, exid2next_dic, nexts_cisrc_dic) (0, False) """ if tr_exc == 1: return 0, False isr_c = 0 fully_con = True # print("tr_id:", tr_id) for i in range(tr_exc-1): ex_nr1 = i + 1 ex_nr2 = i + 2 ex_id1 = tr_id + "_e%i" %(ex_nr1) ex_id2 = tr_id + "_e%i" %(ex_nr2) # print(ex_id1, ex_id2) next1 = exid2next_dic[ex_id1] next2 = exid2next_dic[ex_id2] nexts1 = next1 + "," + next2 nexts2 = next2 + "," + next1 nexts1_yes = False nexts2_yes = False isr_c_pair = 0 if nexts1 in nexts_cisrc_dic: nexts1_yes = True if nexts2 in nexts_cisrc_dic: nexts2_yes = True if nexts1_yes and nexts2_yes: assert False, "NEXT ID combination appears twice in nexts_cisrc_dic (%s, %s)" %(nexts1, nexts2) if nexts1_yes: isr_c_pair = nexts_cisrc_dic[nexts1] elif nexts2_yes: isr_c_pair = nexts_cisrc_dic[nexts2] isr_c += isr_c_pair if not nexts1_yes and not nexts2_yes: fully_con = False # print("isrc:", isr_c_pair) return isr_c, fully_con
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; examples:: i:33 i:-33 i:+33 f:3.2 f:-3.2 f:+3.2 b:true b:false s:somestring somestring :returns: value as int, float, bool or string """ if value.startswith("i:"): return int(value.split(":", 1)[1]) if value.startswith("f:"): return float(value.split(":", 1)[1]) if value.startswith("b:"): val = value.split(":", 1)[1] if val.lower() == "true": return True if val.lower() == "false": return False raise ValueError("value %s: bad boolean '%s' (true or false)" % (value, val)) if value.startswith("s:"): # string that might start with s: or empty return value.split(":", 1)[1] return value
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') False """ try: int_obj = int(int_to_test) except ValueError: return False return str(int_obj) == int_to_test
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) elif isinstance(structure, dict): return dict([(k, _apply_nested(v, fn)) for k, v in structure.items()]) else: return fn(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 else i) return result
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 length [m] ChLe = CaPaDi/2 return (Sh*GaDiCoi)/ChLe except Exception as e: raise
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]) return ((xmin,ymin),(xmax,ymax))
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 to process an arbitrary number of bytes depending on the message format. The message format is as such: the first byte gives the number of 8-byte fields in the message. So a first byte of 3 means the message on the head of the buffer should be 1 + 3*8 = 25 bytes long. Right now there are 3 types of message: type 0 - "status" messages from the workers, where field 0's value should be 2 for 2 fields, field 1 is the number of results the worker has written, and field 2 (currently unused) was the number of new holes the worker has found type 1 - "worker finished" message type 2 - "sync acknowledge" message Parameters ========== curr_message_buffer : bytes the current string of bytes to process Returns ======= messages : list list of parsed messages curr_message_buffer : bytes any remaining data in the current message buffer which was not yet able to be parsed, likely due to a socket read ending not perfectly on a message border """ messages = [] if len(curr_message_buffer) > 0: messages_remaining_in_buffer = True else: messages_remaining_in_buffer = False while messages_remaining_in_buffer: #https://stackoverflow.com/questions/28249597/why-do-i-get-an-int-when-i-index-bytes #implicitly converts the 0th byte to an integer msg_fields = curr_message_buffer[0] msg_len = 1 + 8*msg_fields if len(curr_message_buffer) >= msg_len: curr_msg = curr_message_buffer[1:msg_len] messages.append(curr_msg) curr_message_buffer = curr_message_buffer[msg_len:] if len(curr_message_buffer) > 0: messages_remaining_in_buffer = True else: messages_remaining_in_buffer = False else: messages_remaining_in_buffer = False return messages, curr_message_buffer
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 if the move was actually performed and the position was used as indice. Parameters ---------- position : int The index that one wants to use in the array if the move was performed. move : tuple of int A tuple with that represents a single, unique move. Returns ------- int The index in the unaltered array that has the same value as the location in an array where the move was performed. Examples -------- Some simple examples, the move remains the same, but the position changes: .. doctest:: >>> from lclpy.evaluation.deltaeval.delta_qap \\ ... import array_reverse_order_transform_next_index_to_current_index \\ ... as transform_next_index_to_current_index ... # tests >>> transform_next_index_to_current_index(0, (1, 4)) 0 >>> transform_next_index_to_current_index(1, (1, 4)) 4 >>> transform_next_index_to_current_index(2, (1, 4)) 3 >>> transform_next_index_to_current_index(3, (1, 4)) 2 >>> transform_next_index_to_current_index(4, (1, 4)) 1 >>> transform_next_index_to_current_index(5, (1, 4)) 5 """ # check if position is altered by the move if (position >= move[0]) & (position <= move[1]): # alter the position offset = position - move[0] position = move[1] - offset return position
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 hasattr(o, "__annotations__") else {}
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 resulting command Distance : How far the system would move from this command StartTime : When the command should begin Returns : The acceleration commmand for the current timestep CurrTime or if an array of times was passed, the array representing the input over that time period. """ # These are the times for a bang-coast-bang input t1 = StartTime t2 = duration + t1 accel = impulse_sign*force*(CurrTime > t1) - impulse_sign*force*(CurrTime > t2) return accel
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', 'e' and 'f' indicating the desired subspaces on which the operator is defined. Returns ------- states : list List of all states defined in the desired subspace, where each state is defined as a list of sites in the excited state """ states = [] if 'g' in subspace: states.append([]) if 'e' in subspace: for i in range(N): states.append([i]) if 'f' in subspace: for i in range(N): for j in range(i + 1, N): states.append([i, j]) return states
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 = [1, 2, 3, 4, 3, 2, 1], the unique element is 4. Solve: Utilize XOR function for this answer. If each int occurs twice, applying XOR twice will always result in 0, and XOR once will return the integer, so the one value that occurs only once will be the resulting final answer Args: a (array): array of integers where all of them occur twice except for one Returns: int: the integer that only occurs once in the array """ val = 0 for i in a: val = val ^ i return val
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 High level description of what arg2 is. Returns ------- out1 : data type and shape of out1 High level description of what out1 is. out2 : data type and shape of out2 High level description of what out2 is. Raises ------ ValueError Condition that causes above error type to be raised. AttributeError Condition that causes above error type to be raised. """ out1 = arg1 out2 = arg2 return out1,out2
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 & 0x7fffffffffffff) << 5) ^ value # 0x1ffffff->0x7fffffffffffff for i in range(5): chk ^= generator[i] if ((top >> i) & 1) else 0 return chk
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): overflow += (event.demand - slot.capacity) * X[row, col] return overflow
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)) h = hex(int(i))[2:].upper() h = "0" * (6 - len(h)) + h return "#" + h
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] 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 the popup """ if open_click > close_click: return {"display": "block"} else: return {"display": "none"}
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 = [] for index in range(len(tokens)): if tokens[index] == '|': options.append(option) option = [] else: option.append(tokens[index]) options.append(option) return options
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_to_the_power_of_zero) If it is required otherwise, should be handled explicitly (Just adding `if b == 1 or mod == 1: return 0` should suffice) """ mp = {} e, n = 1, int(mod**0.5) + 2 for i in range(n + 3): if e == b: return i mp[b * e % mod] = i e = e * a % mod v = e = pow(a, n, mod) for i in range(2, n + 3): e = e * v % mod if e in mp: x = n * i - mp[e] return x if pow(a, x, mod) == b else None
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( table, match_key, match_val )
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 renamed
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(collect_codelist_enums(path, item, pointer='{}/{}'.format(pointer, index))) elif isinstance(data, dict): if 'codelist' in data: codelists[data.get('codelist')] = ((data.get('enum'), data.get('openCodelist'))) for key, value in data.items(): codelists.update(collect_codelist_enums(path, value, pointer='{}/{}'.format(pointer, key))) return codelists
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[2]-ys[0])*(x-xs[2])+(xs[0]-xs[2])*(y-ys[2]))/float(det) return l1, l2, 1-l1-l2
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]) [1, 3] >>> indices([1,2,3,1,2,3,1,2,3], lambda x: x > 2) [2, 5, 8] """ return [i for (i, val) in enumerate(a) if func(val)]
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__()] except AttributeError: # Needed in case a class don't uses new-style # class definition in Python 2 return False
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 & predicted print("Identical sets: {}".format(true == predicted)) print(f"Num. distinct executions in observations: {len(true)}\n") print(f"Num. distinct executions given learned exp.: {len(predicted)}\n") print(f"Size of intersection: {len(true_inter_pred)}") return((len(true_inter_pred)/len(predicted)),(len(true_inter_pred)/len(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 + q) / (2 + q)
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 features Returns: * ind: int index of feature in feature """ return features.index(feature) - int('time' in features)
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",', "exports = ['LICENSE.md',"] with open(file) as ifd: for line in ifd: updated_line = False if not updated: for pattern in complete: if line.strip() == pattern: updated = True updated_line = True break if not updated: for pattern in incomplete: if line.strip().startswith(pattern): content += line.replace(pattern, "exports = [") updated = True updated_line = True break if not updated_line: content += line if updated: main.output_result_update("Delete export of LICENSE.md file") with open(file, 'w') as fd: fd.write(content) return updated
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 entity["profiles"]: profiles.add(profile["profile"]) return profiles
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): """""" # type: (Tuple[text_type,...])->bool length_valid_pos_tuple = len(valid_pos_tuple) if valid_pos_tuple == pos_tuple[:length_valid_pos_tuple]: return True else: return False seq_bool_flags = [is_valid_pos(valid_pos_tuple) for valid_pos_tuple in valid_pos] if True in set(seq_bool_flags): return True else: return False
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 = [] equal = [] # Only run if vector contains multiple elements if len(vec) > 1: # Pick a pivot (first element in the vector) q = vec[int(len(vec)/2)] # Scan through the vector, assigning each element to new vectors # based on whether it is larger or smaller than the partition i = 0 while i < len(vec): if vec[i] < q: left.append(vec[i]) elif vec[i] > q: right.append(vec[i]) else: equal.append(vec[i]) i = i+1 # Do this recursively to the partitioned vectors return quicksort(left) + equal + quicksort(right) # in the case of empty/singleton vectors, just return it else: return vec
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) / pixel_width) x2 = int((bbox[1] - originX) / pixel_width) + 1 y1 = int((bbox[3] - originY) / pixel_height) y2 = int((bbox[2] - originY) / pixel_height) + 1 xsize = x2 - x1 ysize = y2 - y1 return (x1, y1, xsize, ysize)
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 ``True`` if input ``n`` is a bit flag and ``False`` if it is not. """ if n < 1: return False return bin(n).count('1') == 1
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 ndarray. """ full_idx = [slice(None)] * ndim full_idx[axis] = slice_number return full_idx
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 'old' value return out
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 matching prefix-less elements :rtype: dict .. note:: Because Flex is not part of a specific studio pipeline we cover two different ways to bring the source shapes inside your rig. You can either import the source group with the meshes or use a Maya reference. This function will strip the prefix whether your object is part of a namespace or a double name getting a full path naming. """ return dict([(n.split("|")[-1].split(":")[-1], n) for n in elements])
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: """ return str_in.replace(sub_str, new_sub_str)
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 n = n // 10 return temp == rev
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 = [] for compute_node in compute_node_list: for ovs_br in ovs_br_list: if ovs_br in compute_node.run_cmd("sudo ovs-vsctl show"): ovs_flows_cmd = ("sudo ovs-ofctl dump-flows {} -O {} | " "grep table=".format(ovs_br, of_protocol)) cmd_out_lines += (compute_node.run_cmd(ovs_flows_cmd).strip(). split("\n")) return 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 from Dynamo, but the 4th next() requires two more calls (second call is empty) For example, the chain [3, 0, 1, 4] has the following table: +-------+---+---+---+---+---+---+---+---+---+---+ | steps | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | +-------+---+---+---+---+---+---+---+---+---+---+ | calls | 1 | 1 | 1 | 1 | 3 | 4 | 4 | 4 | 4 | 4 | +-------+---+---+---+---+---+---+---+---+---+---+ """ required_steps = 0 call_count = 0 for call_count, page in enumerate(chain): required_steps += page if required_steps >= current_steps: break return call_count + 1
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 all others, it is represented by a dot followed by the name. Parameters ---------- surf: string A string representing a FreeSurfer surface, e.g., 'white' or 'pial'. Returns ------- string The empty string if `surf` is 'white'. A dot followed by the string in the input argument `surf` otherwise. Examples -------- >>> import brainload.freesurferdata as fsd >>> print fsd._get_morphometry_data_suffix_for_surface('pial') .pial """ if surf == 'white': return '' return '.' + surf
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_dataset_type = 'FewShotCocoCopyDataset' elif dataset_type in ['FewShotCocoODataset', 'FewShotCocoODefaultDataset']: copy_dataset_type = 'FewShotCocoOCopyDataset' else: raise TypeError(f'{dataset_type} ' f'not support copy data_infos operation.') return copy_dataset_type
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_handling_strategy_values: raise ValueError( "{} is not a valid ContentHandlingStrategy".format( content_handling_strategy ) ) return content_handling_strategy