content
stringlengths
42
6.51k
def matmul2(Ma, Mb): """ @brief Implements boolean -> integer matrix mult . """ assert len(Ma[0]) == len(Mb), \ "Ma and Mb sizes aren't compatible" size = len(Mb) Mres = [[0 for i in range(size)] for j in range(size)] for i in range(size): for j in range(size): ...
def getUShort(data, index): """Returns two bytes from data as an unsigned 16-bit value""" return (data[index+1] << 8) + data[index]
def binary_to_hex(binary_data, byte_offset, length): """Converts binary data chunk to hex""" hex_data = binary_data[byte_offset:byte_offset + length].hex() return ' '.join(a+b for a,b in zip(hex_data[::2], hex_data[1::2]))
def metadataset2dataset_key(metadataset_name): """Return the dataset name corresponding to a metadataset name Metadatasets are not ever stored in the HDF5 and instead are only used to store data needed to correctly calculate dataset values. This function maps a metadataset name to its corresponding da...
def evaluate_accuracy(predictions, targets): """Evaluate accuracy Args predictions: (list of string) targets: (list of list os string) """ correct = 0 total = len(targets) for prediction, target in zip(predictions, targets): if prediction in target: correct ...
def convert_coordinates(q, conversion, axisorder): """ Convert a 3-tuple in data coordinates into to simplex data coordinates for plotting. Parameters ---------- q: 3-tuple the point to be plotted in data coordinates conversion: dict keys = ['b','l','r'] values = lam...
def average_price(quantity_1, price_1, quantity_2, price_2): """Calculates the average price between two asset states.""" return (quantity_1 * price_1 + quantity_2 * price_2) / \ (quantity_1 + quantity_2)
def x_encode(X): """ Onehot encoder of sequences in X list """ X_encoding_dict = {'*': 0} X_enc = [] for vec in X: enc_vec = [] for aa in vec: if aa not in X_encoding_dict: max_val = max(X_encoding_dict.values()) X_encoding_dict.updat...
def get_fid2fidx_mappings(ch_info_dic): """ Go through channel features, looking for numerical features in need of standard deviation calculation. Map feature ID to feature channel index. Return both-way mappings. >>> ch_info_dic = {'fa': ['C', [0], ['embed'], 'embed'], 'pc.con': ['N', [3], ['phast...
def einsteinA(S: float, frequency: float): """ Calculate the Einstein A coefficient for a transition with specified transition frequency and intrinsic linestrength. Parameters ---------- S : float Intrinsic linestrength; unitless frequency : float Transition frequency in...
def _get_more_static_shape(shape0, shape1): """Compare two shapes with the same rank, and return the one with fewer symbolic dimension. """ assert len(shape0) == len(shape1) num_sym_dim0 = 0 num_sym_dim1 = 0 for dim0, dim1 in zip(list(shape0), list(shape1)): if not isinstance(dim0, i...
def _is_char(c): """Returns true iff c is in CHAR as specified in HTTP RFC.""" return ord(c) <= 127
def myround(x, base=5): """ Round a number to nearest '5'. """ return int(base * round(float(x)/base))
def generate_kinesis_event(region, partition, sequence, data): """ Generates a Kinesis Event :param str region: AWS Region :param str partition: PartitionKey in Kinesis :param str sequence: Sequence Number as a string :param str data: Data for the stream :return dict: Dictionary representin...
def clean_dict(dictionary): """Removes any `None` entires from the dictionary""" return {k: v for k, v in dictionary.items() if v}
def _adjust_n_months(other_day, n, reference_day): """Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided. """ if n > 0 and other_day < reference_day: n = n - 1 elif n <= 0 and other_day > reference_day: n = n + 1 ...
def extract_tag(tags, prefix): """Extracts a tag and its value. Consumes a tag prefix, and extracts the value corresponding to it. Args: tags (list): the list of tags to check prefix (str): the tag prefix Returns: A tuple of tag and tag value. """ for tag in tags: if...
def get_nearest_value(iterable, value): """ simple return nearest value inside given iterable object """ return min(iterable, key=lambda x: abs(int(x.split(".")[0]) - value))
def num_trees(n): """Returns the number of unique full binary trees with exactly n leaves. E.g., 1 2 3 3 ... * * * * / \ / \ / \ * * * * * * / \ / \ * * * * >>> num_trees(1) 1 >>> num...
def parse_print_dur(print_dur): """ Parse formatted string containing print duration to total seconds. >>> parse_print_dur(" 56m 47s") 3407 """ h_index = print_dur.find("h") hours = int(print_dur[h_index - 2 : h_index]) if h_index != -1 else 0 m_index = print_dur.find("m") min...
def get_status_message(status): """Returns the message of the given Mesos task status, possibly None :param status: The task status :type status: :class:`mesos_pb2.TaskStatus` :returns: The task status message :rtype: string """ if hasattr(status, 'message'): return status.message ...
def mean(x): """ Calculate Arithmetic Mean without using numpy """ return sum([float(a) for a in x]) / float(len(x))
def cleanfield(value): """ remove spaces """ if not value: return None value = str(value) value = value.strip() return value
def pre_process_station_name(x): """ Standarized the station names. This step is necesary to merge different data sets later """ x = x.lower() x = x.split() return x[0]
def require_any(json, keys): """ Require that the given dict-from-json-object contains at least one of the given keys. """ for k in keys: if k in json: return True return False
def quandl_apikey_set(apikey, filename=None): """Store the Quandl Token in $HOME/.updoon_quandl Parameters: ----------- apikey : str The API Key from the Quandl Website. See https://www.quandl.com/account/api filename : str Absolute path to the text where the Quandl...
def summing_it(data): """ Calculates sum of database dumps :param data: accepts multi-dimensional iterable data type :return: returns total amount in a FLOAT """ if data is None: print("Something's gone horribly wrong.") return 0 total = 0 for entry in data: ...
def binary_tree_to_dll(node, head, tail): """This function converts a binary tree to a doubly linked list with recursive approach input: tree root or node, head and tail pointer of DLL returns : the head and tail of the the linked lists """ if node == None : return head, tail ...
def combine_variables(os_environ, args_variables): """Utility function to update environment with user-specified variables .. note: When there is a key clash the user-specified args take precedence :param os_environ: os.environ dict :param args_variables: variables parsed from command line :return...
def _extract_hostname(url: str) -> str: """Get the hostname part of the url.""" if "@" in url: hn = url.split("@")[-1] else: hn = url.split("//")[-1] return hn
def to_lutron_level(level): """Convert the given HASS light level (0-255) to Lutron (0.0-100.0).""" return float((level * 100) / 255)
def use_c(c_val: str) -> str: """ Prints a string """ print(c_val) return c_val
def insertion_sort(arr): """Refresher implementation of inserstion sort - in-place & stable. :param arr: List to be sorted. :return: Sorted list. """ for i in range(1, len(arr)): tmp = arr[i] j = i # find the position for insertion for j in range(i, len(arr)): ...
def nearest_square(y): """ Takes an integer argument limit, and returns the largest square number that is less than limit. A square number is the product of an integer multiplied by itself, for example 36 is a square number because it equals 6*6. """ x = 0 ...
def _q(alpha, d, e, M): """ Solve Eq. 9 """ return 2. * alpha * d * (1. - e) - M**2
def json_to_one_level(obj, parent=None): """ Take a dict and update all the path to be on one level. Arguments: output (dict): The dict to proceed. parent (str): The parent key. Used only with recursion. Return: dict: The updated obj. """ output = {} for key, value i...
def remove(condition, all, names): """ Remove experiments that fulfill a boolean condition. Example:: all = remove('w < 1.0 and p = 1.2) or (q in (1,2,3) and f < 0.1', all, names) (names of the parametes must be used) """ import copy for ex in copy.deepcopy(all): # iterate over a co...
def removePrefixes(word, prefixes): """ Attempts to remove the given prefixes from the given word. Args: word (string): Word to remove prefixes from. prefixes (collections.Iterable or string): Prefixes to remove from given word. Returns: (string): Word with prefixes removed. ...
def loc_sum(vals): """in case 'sum' does not exist, such as on old machines""" try: tot = sum(vals) except: tot = 0 for val in vals: tot += val return tot
def header_token(token): """ Set token in header :param token: :return Dict: """ return {'Authorization': '{0} {1}'.format('JWT', token)}
def get_samples_from_datalist(datalist): """ return a samples object from a list of data dicts """ return [[x] for x in datalist]
def paragraphs(linelist): """ Break a list of lines at blank lines into a list of line-lists. """ plist = [] newlinelist = [] for line in linelist: line = line.strip() if line: newlinelist.append(line) elif newlinelist: plist.append(newlinelist) ...
def view_schedules(description, bus_stop_code, bus_selected, time): """ Message that will be sent when user wants to view their scheduled messages """ return '<b>Bus Stop: </b>{}\n<b>Bus Stop Code: </b>/{}\n<b>Buses: </b>{}<b>\nTime:</b> {}H\n' \ '<b>Frequency:</b> Daily'.format(description,...
def select_choice(current, choices): """ For the radiolist, get us a list with the current value selected """ return [(tag, text, (current == tag and "ON") or "OFF") for tag, text in choices]
def _flatten(obj_to_vars): """ Object section is prefixed to variable names except the `general` section [general] warning = red >> translates to: warning = red [panel] title = white >> translates to: panel_title = white """ all_vars = dict() for obj, vars_ in obj_t...
def leap_check(year) -> str: """ Check if a year is a leap year """ if ((year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)): return f"{year} is a leap year!" else: return f"{year} is not a leap year!"
def string_to_array(s): """Convert pipe separated string to array.""" import math if isinstance(s, str): out = s.split("|") elif math.isnan(s): out = [] else: raise ValueError("Value must be either string of nan") return out
def get_datatype(value): """ Determine most appropriate SQLite datatype for storing value. SQLite has only four underlying storage classes: integer, real, text, and blob. For compatibility with other flavors of SQL, it's possible to define columns with more specific datatypes (e.g....
def RPL_YOUREOPER(sender, receipient, message): """ Reply Code 381 """ return "<" + sender + ">: " + message
def idfn(fixture_value): """ This function creates a string from a dictionary. We use it to obtain a readable name for the config fixture. """ return str( "-".join(["{}:{}".format(k, v) for k, v in fixture_value.items()]) )
def call(f, *args, **kwargs): """Call f with args and kwargs""" return f(*args, **kwargs)
def add_annotation(x, y, z): """ Create plotly annotation dict. """ return { "x": x, "y": y, "z": z, "font": {"color": "black"}, "bgcolor": "white", "borderpad": 5, "bordercolor": "black", "borderwidth": 1, "captureevents": True, "...
def get_permission(code): """Get permission.""" permission = { 0: "deny", 2: "ro", 3: "rw" } return permission.get(code, None)
def is_clean_packet(packet): # pragma: no cover """ Returns whether or not the parsed packet is valid or not. Checks that both the src and dest ports are integers. Checks that src and dest IPs are valid address formats. Checks that packet data is hex. Returns True if all tests pass, False other...
def pad_sentences(sentences, sentence_length, padding_word="<PAD/>"): """ Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. """ padded_sentences = [] for i in range(len(sentences)): sentence = sentences[i] num_padding ...
def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale """ return round(kelvin *...
def _find_replica_groups(global_x, inner_x, inner_y, outer_group_size): """Find replica groups for SPMD.""" groups_x = global_x // inner_x inner_replica_groups = [] for group_id in range(outer_group_size): sub_group_ids = [] row_group_id = group_id // groups_x col_group_id = group_id % groups_x ...
def yesify(val): """Because booleans where not invented 150 years ago.""" return "yes" if val else "no"
def buildResultString(data): """ Creates a line for the algorithm result text file. Parameters ---------- dict : dictionary The dictionary which contains the data for a repititon of an algorithm. Returns ---------- A string which represents one line of the algorithm result ...
def hgvs_str(gene_symbols, hgvs_p, hgvs_c): """ """ if hgvs_p[0] != "None": return hgvs_p[0] if hgvs_c[0] != "None": return hgvs_c[0] return "-"
def sort_protein_group(pgroup, sortfunctions, sortfunc_index): """Recursive function that sorts protein group by a number of sorting functions.""" pgroup_out = [] subgroups = sortfunctions[sortfunc_index](pgroup) sortfunc_index += 1 for subgroup in subgroups: if len(subgroup) > 1 and sor...
def build_url_params(params): """ Tag that takes a dict in a template and turns it into a url params string, including the ?. Only accepts things that can be converted into a string Arugments obj: a dictionary """ data = [] # put our params into our extra data for item in p...
def sizeof_fmt(num) -> str: """Print size of a byte number in human-readable format. Args: num: File size in bytes. Return: str: File size in human-readable format. """ for unit in ["B", "K", "M", "G", "T", "P", "E", "Z"]: if abs(num) < 1024.0: if abs(num) < 100...
def kernel_sigmas(n_kernels): """ get sigmas for each gaussian kernel. :param n_kernels: number of kernels (including exactmath.) :param lamb: :param use_exact: :return: l_sigma, a list of simga """ bin_size = 2.0 / (n_kernels - 1) l_sigma = [0.001] # for exact match. small...
def titleize(text): """Capitalizes all the words and replaces some characters in the string to create a nicer looking title. """ if len(text) == 0: # if empty string, return it return text else: text = text.lower() # lower all char # delete redundant empty space chu...
def identity(*args): """ Return whatever is passed in Examples -------- >>> x = 1 >>> y = 2 >>> identity(x) 1 >>> identity(x, y) (1, 2) >>> identity(*(x, y)) (1, 2) """ return args if len(args) > 1 else args[0]
def compile_playable_podcast(playable_podcast): """ @para: list containing dict of key/values pairs for playable podcasts """ items = [] for podcast in playable_podcast: items.append({ 'label': podcast['title'], 'thumbnail': podcast['thumbnail'], 'path': ...
def delimit(delimiters, content): """ Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") # doctest: +SKIP '[foo]' >>> delimit('""', "foo") # doctest: +SKIP '"foo"' """ if len(delimiters) != 2: raise ValueError( "`delimit...
def make_sampling_histogram(unique_words): """Helper function for test_stochastic_sample (below). Given a list of words, return a dictionary representing a histogram. All values begin at zero. Param: unique_words(list): every distinct type of word, will be a key Return: histogram_empty(d...
def pay_minimums(principal, payment): """Make the minimum payments first.""" if principal - payment <= 0: payment = principal return principal - payment, payment
def _make_url(term): """ Retrun a url """ return f"http://rest.kegg.jp/get/{term}"
def update_jstruct(jstruct, elem_struct, val, keep): """ Update json structure (recursive function) :param jstruct: jstruct to update :param elem_struct: nested field represented as list :param val: value of the nested field :param keep: if true write None values ins...
def coord_map(dimensions, coordinate, mode): """ Wrap a coordinate, according to a given mode. :param dimensions: int, maximum coordinate. :param coordinate: int, coordinate provided by user. May be < 0 or > dimensions :param mode: {'W', 'S', 'R', 'E'}, Whether to wrap, symmetric reflect, reflect o...
def insertionSort(myList: list): """ Sorts the list by inserting the numbers in a specific index. """ for index in range(1, len(myList)): actualValue = myList[index] actualPosition = index while actualPosition > 0 and myList[actualPosition - 1] > actualValue: myList...
def jk_from_i(i, olist): """ Given an organized list (Wyckoff positions or orientations), determine the two indices which correspond to a single index for an unorganized list. Used mainly for organized Wyckoff position lists, but can be used for other lists organized in a similar way Args: ...
def human_readable_time(time): """ Convert global time in the system to the human-readable time :return: human-readable time as a string """ hours = str(time // 3600 % 24) minutes = str((time // 60) % 60) seconds = str(time % 60) if len(minutes) != 2: minutes = "0" + minutes ...
def dehexify(data): """ A URL and Hexadecimal Decoding Method. Credit: Larry Dewey. In the case of the SIEM API, this is used only when dealing with the pricate API calls. """ hexen = { "\x1c": ",", # Replacing Device Control 1 with a comma. "\x11": "\n", # Replacing De...
def bioconductor_experiment_data_url(package, pkg_version, bioc_version): """ Constructs a url for an experiment data package tarball Parameters ---------- package : str Case-sensitive Bioconductor package name pkg_version : str Bioconductor package version bioc_version : ...
def str_to_bool(string): """ Parses string into boolean """ string = string.lower() return True if string == "true" or string == "yes" else False
def valid(circuit, param): """ checks validity of parameters Parameters ---------- circuit : string string defining the circuit param : list list of parameter values Returns ------- valid : boolean Notes ----- All parameters are considered valid if they ar...
def _left_decorator(item): """ Removed packages """ return u'-' + item
def calculate(nth_number): """Returns the difference between the sum of the squares and the square of the sum of the specified number of the first natural numbers""" sums = sum(number for number in range(1, nth_number + 1)) sum_of_squares = 0 for number in range(1, nth_number + 1): sum_of_sq...
def other_identifiers_to_metax(identifiers_list): """Convert other identifiers to comply with Metax schema. Arguments: identifiers_list (list): List of other identifiers from frontend. Returns: list: List of other identifiers that comply to Metax schema. """ other_identifiers = []...
def RawLintWhitespace(data): """Make sure whitespace is sane.""" ret = [] if not data.endswith('\n'): ret.append('missing newline at end of file') return ret
def dict_if_none(arg): """Return an empty dict if arg is None.""" return arg if arg is not None else {}
def str_as_bool(val): """ Interpret the string input as a boolean """ if val.lower() in ("false", "none", "no", "0"): return False return True
def is_hdfs_path(path): """ Check if a given path is HDFS uri Args: path (str): input path Returns: bool: True if input is a HDFS path, False otherwise >>>is_hdfs_path("/tdk") False >>>is_hdfs_path("hdfs://aa:123/bb/cc") True """ return path.startswith("hdfs://")
def imply(pred1,pred2): """ Returns True if pred1 implies pred2 , i.e. not pred1 or pred2. pred1, pred2 are bool vars """ return (not pred1) or pred2
def hex2rgb(color): """Turns a "#RRGGBB" hexadecimal color representation into a (R, G, B) tuple. Arguments: color -- str Return: tuple """ code = color[1:] if not (len(color) == 7 and color[0] == "#" and code.isalnum()): raise ValueError('"%s" is not a valid color' % color...
def convert_string_to_bool(string): """Converts string to bool. Args: string: str, string to convert. Returns: Boolean conversion of string. """ return False if string.lower() == "false" else True
def find_duplicates(items): """ Takes a list and returns a list of any duplicate items. If there are no duplicates, return an empty list. Code taken from: https://stackoverflow.com/questions/9835762/how-do-i-find-the-duplicates-in-a-list-and-create-another-list-with-them """ seen = {} d...
def in_answer(a): """ Manipulation rule for answers 'inside' in QA pairs. """ entailment = f'the image is {a}.' contradiction = f'the image is not {a}.' return (entailment, contradiction), None
def ellipsis(data, length=20): """ Add a "..." if a string y greater than a specific length :param data: :param length: length taking into account to cut the string :return: """ data = str(data) return (data[:length] + '..') if len(data) > length else data
def fibonacci(n): """returns a list of the first n fibonacci values""" n0 = 0 n1 = 1 fib_list = [] if type(n) != type(0) or n<=0: raise Exception("'%s' is not a positive int" % str(n)) for i in range(n): fib_list.append(n1) (n0, n1) = (n1, n0+n1) return fib_list
def applescript_escape(string): """Escape backlsahes and double quotes for applescript""" return string.replace('\\', '\\\\').replace('"', '\\"')
def merge_dicts(*dicts): """ Merge dictionaries into a new dict (new keys overwrite the old ones). Args: dicts (tuple[dict]): Dictionaries to be merged together. Returns: merged (dict): The merged dict (new keys overwrite the old ones). Examples: >>> d1 = {1: 2, 3: 4, 5: 6...
def fetch_param(ctx, name): """ Try to fetch a click.Parameter from a click.Context (or its parents) """ # Try to raise error parent = ctx while parent is not None: params = {p.name: p for p in parent.command.params} if name in params: return parent, params[name] ...
def answer(maze): """ I can largely re-use my code from foobar2-1. We'll traverse the maze like a graph. I debated converting it to one, but determined it won't do much to make the algorithm more intuitive. To solve this question, I perform a depth-first search and then look up the distance to the...
def _ifconfig_cmd(netif, params=[]): """Construct commands to manipulate ifconfig.""" cmd = ['ifconfig', netif] cmd.extend(params) return cmd
def bytes_(s, encoding='latin-1', errors='strict'): """ This function is a copy of ``pyramid.compat.bytes_`` If ``s`` is an instance of ``text_type``, return ``s.encode(encoding, errors)``, otherwise return ``s``""" if isinstance(s, str): # pragma: no cover return s.encode(encoding, errors) ...