content
stringlengths
42
6.51k
def color2gray(image): """ Converts a color image to grayscale """ # we use HDTV grayscale conversion as per https://en.wikipedia.org/wiki/Grayscale image = [[x for x in row] for row in image] return [[int(0.2126*p[0] + 0.7152*p[1] + 0.0722*p[2]) for p in row] ...
def path_in_tree(root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ def recursion_core(node, sum): """ :param node:subtree root :param sum: sub sum :return: [path(list)] if has path else [] """ if not node.left and not ...
def count_words(sequences, num): """ To count the most common words of sequences. sequences: sequences need to be counted num: return top num words. """ counts = {} # To count words for x in sequences: if x in counts: counts[x] += 1 else: counts[...
def __sbox_single_byte(byte, sbox): """S-Box substitution of a single byte""" row = byte // 16 col = byte % 16 return sbox[row][col]
def dict_to_table(d): """Convert dict into a two-column table (one col for key, one col for value).""" keys, vals = [list(l) for l in zip(*list(d.items()))] return {'key': keys, 'val': vals}
def split_id(url_id): """ Data for the response is encoded in the ID URL """ parts = url_id.split("/") data = {} for i in range(1,len(parts)-1,2): data[parts[i]] = parts[i + 1] return data
def _reverse(object2idx): """ Reverse 1-to-1 mapping function. Return reversed mapping. :param object2idx: Mapping of objects to indices or vice verse. :type object2idx: `dict` :rtype: `dict` """ return dict(list(zip(list(object2idx.values()), list(object2idx.keys()))))
def get_last_id(list_of_id, width): """ Gets the last identifier given a list of identifier. :param list_of_id: list of identifier :param width: the width of the identifier. :return: the last identifier. """ last_number = 0 for identifier in list_of_id: if identifier == "": ...
def does_include(text, chars): """Check if text contains any character from chars.""" return any(char in text for char in chars)
def prepare_execute_without_interaction(stage): """Advance through the PrepareStage without any interactivity. Returns: a ``PrepareResult`` instance """ result = None while stage is not None: next_stage = stage.execute() result = stage.result if result.failed: ...
def crop_fixed_params_gp(params, fixed_params): """Remove p and rawp, for p in fixed_params""" params_list = set(params.keys()) for param in params_list: if param[:4] == 'raw_': param = param[4:] if param in fixed_params: params.pop(param, None) params.pop...
def _is_sunder(name): """Returns True if a _sunder_ name, False otherwise.""" return ( name[0] == name[-1] == "_" and name[1:2] != "_" and name[-2:-1] != "_" and len(name) > 2 )
def extension_to_type(ext): """ Return the notebook type for a given file extension """ if ext == 'ipynb': return 'jupyter' raise RuntimeError(f"unknown file extension {ext}")
def NoTestRunnerFiles(path, dent, is_dir): """Filter function that can be passed to FindCFiles or FindHeaderFiles in order to exclude test runner files.""" # NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which # are in their own subpackage, from being included in boringssl/BUILD files. ...
def pround(val): """Round a number with a precision determined by the magnitude.""" precision = 1 if val >= 100: precision = 0 if val < 1: precision = 3 return f"{val:.{precision}f}"
def get_zone(score, bin_size=10): """ A simple function to return the corresponding zone of the given score. Zone format: "<lower_limit> - <upper_limit>" lower_limit is inclusive and upper_limit is exclusive. # Arguments: score: a number in the range of [0, 100]. # Returns: A st...
def decreasing(args): """ Ensure that the values in args are decreasing. """ return [args[i-1] >= args[i] for i in range(1,len(args))]
def _replace_stmt_with_buf_var_names(buffer_info_map): """helper to replace tir.allocates with buffer names""" new_buffer_info_map = dict() for k, v in buffer_info_map.items(): new_buffer_info_map[v.buffer_var.name] = k return new_buffer_info_map
def fast_tabulated_fibonacci(n): """Returns the nth fibonacci number Time complexity: O(n) Parameters ---------- n : int the nth fibonacci position Returns ------- int the nth fibonacci number ------- >>> fast_tabulated_fibonacci(0) 0 >>> fast_tabulat...
def product(list): """Return the product of all elements in input list. Helper function. """ p = 1 for i in list: p *= i return p
def inverse_complement(sequence, dna=True): """compute inverse complement sequence.""" if dna: A_complement = "T" else: A_complement = "U" complement = { "A": A_complement, A_complement: "A", "G": "C", "C": "G" } return "".join([complement[b] for b...
def which(program): """which() acts like the unix utility which, but is portable between os. If the program does not exist in the PATH then 'None' is returned. """ import os def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(progr...
def IN2(a, b): """ >>> IN2(1, [1,2,3]) False >>> IN2([1,2,3], 1) True >>> IN2([2,3], 1) False >>> IN2("hello abc world", "abc") True >>> IN2("hello abc world", "xyz") False """ try: return b in a except TypeError: return False
def get_vlan_untag_ports(config_facts): """ get all untag vlan ports """ vlan_untag_ports = [] vlans = config_facts.get('VLAN_INTERFACE', {}).keys() for vlan in vlans: vlan_member_info = config_facts.get('VLAN_MEMBER', {}).get(vlan, {}) if vlan_member_info: for port_n...
def getApproximateValue(value): """ Return an approximate representation of any numerical value. Handles lists of values, and does not modify the value if it is not numerical. Args: value: Any object or value Returns: An approximate version of the value if it is numeric, or ...
def points_2_xywh(box): """ Converts [xmin, ymin, xmax, ymax] to [xmin, ymin, width, height]. """ box = [box[0], box[1], box[2] - box[0], box[3] - box[1]] box = [int(round(x)) for x in box] return box
def sum_rec(nums): """ Returns the sum of a list of numbers using recursion Examples: >>> sum_rec([3,1,4,1,5,9,2,6,5]) 36 >>> sum_rec(range(101)) 5050 >>> sum_rec(range(901)) 405450 >>> sum_rec([x**3 - 2*x**2 + x - 13 for x in range(901)])...
def ex2_pickle_name(n, bin_size): """build name for pickle file Parameters ------ n, bin_size : float `n` population and `bin_size` aggregate square size Returns ------ f_name : str return `f_name` file name to save pickle as """ f_name =...
def Feet_To_Meters(Feet): """Converts Feet into Meters""" Meter = Feet * 3.28084 return Meter
def partition(arr: list, low: int, high: int) -> int: """Partition the array Args: arr (list): the array to partition low (int): the left-most index high (int): the right-most index Returns: int: the new pivot location """ i = low - 1 pivot = arr[high] # Sw...
def limit_es(expected_mb): """Protection against creating too small or too large chunks.""" if expected_mb < 1: # < 1 MB expected_mb = 1 elif expected_mb > 10**7: # > 10 TB expected_mb = 10**7 return expected_mb
def take_keys(keys, data_dict): """Take keys from dict Arguments: keys {List[str]} -- Keys it include in output dict data_dict {Dict} Returns: [Dict] """ return {k: v for k, v in data_dict.items() if k in keys}
def merge_sorted_arrays(list1: list, list2: list) -> list: """ Merge Two Sorted Arrays: """ index1 = 0 index2 = 0 merged_array = [] while index1 < len(list1) and index2 < len(list2): tmp1 = list1[index1] tmp2 = list2[index2] if tmp1 < tmp2: merged_array.a...
def append_name(name, postfix): """ append name with postfix """ if name is None: ret = None elif name == '': ret = postfix else: ret = '%s_%s' % (name, postfix) return ret
def user_units_to_meters(value: float, units: str) -> float: """Convert a user units value to meters""" if units == 'english': return value / 3.2808 else: return value
def _ptu_TDateTime_to_time_t(TDateTime): """Convert the weird time encoding used in PTU files to standard time_t.""" EpochDiff = 25569 # days between 30/12/1899 and 01/01/1970 SecsInDay = 86400 # number of seconds in a day return (TDateTime - EpochDiff) * SecsInDay
def find_peaks(signal, Fs): """ This function finds all local maxima within a given signal :param list signal: inut signal :return int peak_count: number of peaks detected """ import logging as log log.debug("Finding peaks in signal.\n") L = len(signal) threshold = 0.6 * max(signal...
def capitalize_geo_string(string: str) -> str: """ Capitalizes the first letter of each word in the geo string (excluding the terms 'and' and 'of'). :param string: The string to capitalize. :return: The capitalized string. """ return ' '.join(token if token in {'and', 'of'} else token.capitaliz...
def clean_keys_of_slashes(record): """ Replaces the slashes found in a dataset keys with underscores :param record: list containing a couple of dictionaries :return: record with keys without slashes """ for key in list(record): value = record[key] if '/' in key: # rep...
def searchAcqus(initdir): """ search the acqus file in sub-directory of initdir""" import os, fnmatch pattern = 'acqus' liste = [] for path, dirs, files in os.walk(os.path.abspath(initdir)): for filename in fnmatch.filter(files, pattern): l...
def get_index_name(app_id, namespace, name): """ Gets the internal index name. Args: app_id: A str, the application identifier. namespace: A str, the application namespace. name: A str, the index name. Returns: A str, the internal name of the index. """ return '{}_{}_{}'.format(app_id, namesp...
def uniqueify(items): """Return a list of the unique items in the given iterable. Order is preserved. """ _seen = set() return [x for x in items if x not in _seen and not _seen.add(x)]
def recursive_matches_strict(src, key, val, **kwargs): """ Searches the 'input' recursively for nested elements provided in 'key' with dot notation. In case some levels are iterable (list, tuple) it checks every element. In case the full path is inaccessible raises AttributeError or KeyError. :para...
def _reduce_xyfp(x, y): """ Rescale FP xy coordinates [-420,420] -> [-1,1] and flip x axis """ a = 420.0 return -x/a, y/a
def is_even(num): """ is an int is even or not """ if num % 2 == 0: return True else: return False
def highlight_cluster(query, cluster): """Colour assigned cluster in Microreact output""" if str(cluster) == str(query): colour = "red" else: colour = "blue" return colour
def failed_add_fav_msg(bus_stop_code): """ Message that will be sent if user gives an invalid bus stop code and tries to add it to favourites """ return '{} is not a valid Bus Stop Code! \n\nTo add to favourites, ' \ 'type: /add_favourites [BUS STOP CODE]\n\n e.g: /add_favourites 14141'.form...
def value(s): """Parse float """ if s is None or s == "-" or s == "": return None s = s.replace(",",".").replace(" ","").replace(" ","") if s.endswith("%"): s = s.replace("%", "") return float(s) / 100.0 else: return float(s) raise Exception(u"Unable to parse...
def get_interface_by_name(interfaces, name): """ Return an interface by it's devname :param name: interface devname :param interfaces: interfaces dictionary provided by interface_inspector :return: interface dictionary """ for interface in interfaces: if interface['devname'] == name:...
def md_getAzimuth(field): """Get azimuth""" return field.split(',')[0].strip()
def find_supersets(fsets): """In a set of frozensets, find those that aren't subsets of another.""" uniqpalettes = sorted(set(fsets), key=len, reverse=True) return [ palette for numpreceding, palette in enumerate(uniqpalettes) if not any(prev.issuperset(palette) fo...
def fold(s): # function fold: auxiliary function: shorten long option values for output """auxiliary function: shorten long option values for output""" offset = 64 * " " maxlen = 70 sep = "|" parts = s.split(sep) line = "" out = "" ...
def f_relevant_part_func(r, k, m, b_z, b_theta): """ Return relevant part of f for singularity detection. Could be complied be with numba. Parameters ---------- r : ndarray of floats radial points k : float axial periodicity number m : float azimuthal periodicity...
def snitch_last_contained(metadata): """Return the frame when snitch was last contained.""" last_contain = 0 for _, movements in metadata['movements'].items(): contain_start = False for movement in movements: if movement[0] == '_contain' and movement[1] == 'Spl_0': ...
def split_list(alist, wanted_parts=1): """ split list Parameters ---------- alist: list the split list wanted_parts: int the number of parts (default: {1}) Returns ------- list """ length = len(alist) # return all parts in a list, like [[...
def selected_arms(hist): """ Return a list of the arms as they were selected (in chronological order). """ return [id_ for id_, _ in hist]
def partialDOIMatch(d1, d2): """ Assumes d1 is a "full DOI", like '10.1145/1166253.1166292', and d2 is a partial DOI, like '1166292' or '1166253.1166292'. Returns true if they match and false otherwise. Note that in the previous case, a partial like '292' would be a negative match. The partia...
def reverse_string(phrase): """Reverse string""" return phrase[::-1]
def dydx_2(x0, x1, y0, y1): """ Return :param x0: :param x1: :param y0: :param y1: :return: """ return ((y1 - y0) / (x1 - x0))
def x_ss(n, s, t): """Spin observable: x-direction """ if s == t: return 0 else: return 1
def shift_uint(value: int, full_bitlength: int, bit_offset: int, bitlen: int) -> bytes: """Shifts an unsigned integer and returns the byte array of the shifted value.""" shift = full_bitlength - bitlen - bit_offset output = bytearray(full_bitlength // 8) for i in range(len(output)): byteshift = ...
def _generate_overlap_table(prefix): """ Generate an overlap table for the following prefix. An overlap table is a table of the same size as the prefix which informs about the potential self-overlap for each index in the prefix: - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...] ...
def summarize_condor_log(log_file, external_id): """ """ log_job_id = external_id.zfill(3) s1 = s4 = s7 = s5 = s9 = False with open(log_file, 'r') as log_handle: for line in log_handle: if '001 (' + log_job_id + '.' in line: s1 = True if '004 (' + log_...
def f_price(p): """ Format price to fixed length string """ return f'{p:.2f}'.rjust(6, ' ')
def convert_image_coordinates_to_graph(x, y, im_width, im_height): """ Function used to convert image coordinates in graph coordinates. The y coordinate in a PySimplegui Graph element is inverted compared to the usual definition for images. Parameters ---------- x : int y : in...
def merge_groups(adjs): """Merge all sets in adjs with common members.""" groups = [] while adjs: group = set(adjs.pop()) lastlen = -1 while len(group) > lastlen: lastlen = len(group) for adj in adjs[:]: for p in adj: if p i...
def nextpow2(n): """Give next power of 2 bigger than n.""" return 1 << (n-1).bit_length()
def is_complex_requirement(line): """Allows to save importing pip for very simple requirements.txt files""" return line and (line.startswith("-") or ":" in line)
def uri_pathlist(p): """Split a path into a list. p path return list of path elements """ l = [] for x in p.split('/'): if x == '': continue l.append(x) return l
def ellipsis2slice(input_, shape): """Converts ellipsis to slice.""" input_slice = input_ result = [] if isinstance(input_, type(...)): input_slice = (input_,) ell_count = 0 for _, element in enumerate(input_slice): if not isinstance(element, type(...)): result.append...
def reformat(d, i, facetname): """ Reformats the dictionaries into facets. """ new = {} new["term"] = d.get("term") new["name"] = d.get("termLabel") new["identifiers"] = {} # "https://www.wikidata.org/wiki/Q4661045" -> "Q4661045" new["identifiers"]["wikidata"] = d.get("wikidataID").s...
def _extract_app(github_url): """Extract app identifier from gihtub url""" splits = github_url.split('github.com/')[1].split('/') return splits[0]+"/"+splits[1]
def partition(data, left, right): """ Partition data around a middle-most element """ pivot = data[(int)((left+right)/2)] while left <= right: if data[left] > pivot and data[right] < pivot: data[left], data[right] = data[right], data[left] while data[left] < pivot: le...
def is_uid_in_all_keys(uid, uids): """ Check if uid is found in each of the uid lists for each SQL table :param uid: study instance uid :type uid: str :param uids: lists of study instance uids organized by SQL table :type uids: dict :return: True only if uid is found in each of the tables ...
def count_two_mers(sequence, two_mers): """Returns dictionary, keys are possible couplesl of letters, values are number of their occurances in a given sequence. """ dictionary = {} for mer in two_mers: dictionary[mer] = sequence.count(mer) return dictionary
def update_time_frame(timeframe): """correction for index id :!caps not allowed""" if timeframe == "1m": timeframe = "1minute" elif timeframe == "1M": timeframe = "1month" return timeframe
def mat33_mat33_mult(A, B): """Multiply a 3x3 matrix with a 3x3 matrix. Parameters ---------- A : 'list' ['list' ['float']] 3x3 matrix. B : 'list' ['list' ['float']] 3x3 matrix. Returns ------- res : 'list' ['float'] 3x3 matrix. """ res = [[0, 0, 0], ...
def snrirnarrowred(b4, b8a): """ Simple Ratio NIR narrow and Red (Blackburn, 1998). .. math:: SRNIRnarrowRed = b8a/b4 :param b4: Red. :type b4: numpy.ndarray or float :param b8a: NIR narrow. :type b8a: numpy.ndarray or float :returns SRNIRnarrowRed: Index value .. Tip:: B...
def get_token_pairs(window_size, sentences): """Build token_pairs from windows in sentences""" token_pairs = list() for sentence in sentences: for i, word in enumerate(sentence): for j in range(i + 1, i + window_size): if j >= len(sentence): break ...
def is_hashable(obj): """Determine if obj is hashable.""" try: hash(obj) except Exception: return False else: return True
def square (intValue): """Squares an integer. Assignment: This function returns the square of intValue. :param intValue: Integer to be squared :type intValue: int :return: Square of intValue :rtype: int :raise TypeError: String arguments are not supported """ squaredInt = intV...
def incmean(prevmean, n, x): """Calculate incremental mean""" newmean = prevmean + int(round((x - prevmean) / n)) return newmean
def hex_to_rgb(hex_string): """Converts HEX values to RGB values """ h = hex_string.lstrip('#') return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
def _from_little_endian(data, index, n_bytes): """Convert bytes starting from index from little endian to an integer.""" return sum([data[index + j] << 8 * j for j in range(n_bytes)])
def sample_function(value=True): """ This is a sample function which returns a different str depending on the flag value. Args: - value (:obj:`bool`): it can either be True or False. Returns: :obj:`str` - result This function returns a :obj:`str` which has a different ...
def pathify(pth): """ Adds posix separator if needed """ if not pth.endswith("/"): pth += "/" return pth
def extraNumber(a, b, c): """ You're given three integers, a, b and c. It is guaranteed that two of these integers are equal to each other. What is the value of the third integer? """ if a == b: return c elif a == c: return b elif b == c: return a
def second_level(keys): """Return a dictionary with the nested keys, e.g. returns {'I':['a', 'b']} when keys=['I.a', 'I.b']""" sub_keys = {} for key in keys: if "." in key: left, right = key.split(".", 1) sub_keys.setdefault(left, []).append(right) return sub_keys
def rho_NFW(r, rhos, rs): """ returns density of a NFW profile with characteristic density rhos and scale radius rs note that the units for r are set by rs, and the density is returned in units of rhos """ return rhos / (r / rs * (1.0 + r / rs) ** 2)
def computeWindowLength(window_duration, sample_rate): """ Convert window duration (units of time) to window length (units of samples). NOTE: This assumes uniform sampling. """ return round(window_duration * sample_rate)
def render_network_key(ssid, address): """ssid:address""" return ssid + ':' + address
def capitalize(s, ind): """ Given a string and an array of integers representing indices, capitalize all letters at the given indices. :param s: a string value. :param ind: a array of integers representing indices. :return: capitalize all letters at the given indices in place. """ return ""....
def check_cal_objects_for_nav_cal(service, err_msg_list): """ This function checks a navigator's list of google calendars for the 'Navigator-Consumer Appointments (DO NOT CHANGE)' calendar. Returns True if calendar is found and False otherwise. Returns calendar id if calendar is found. :param service: ...
def option_to_cublas(x): """As above, but for clBLAS data-types""" return { 'layout': "Layout", 'a_transpose': "cublasOperation_t", 'b_transpose': "cublasOperation_t", 'ab_transpose': "cublasOperation_t", 'side': "cublasSideMode_t", 'triangle': "cublasFillMode_t",...
def _is_balanced(root): """Calculates the height of the tree, or returns -1 when the tree is not balanced.""" # Return 0 for leafs if root is None: return 0 # Get height or unbalanced (-1) for left subtree left_height = _is_balanced(root[1]) if left_height == -1: return -1 ...
def hexbytes(s): # formatting helper function """Convert string to string of hex character values.""" ba = bytearray(s) return ''.join('\\x{:02x}'.format(b) for b in ba)
def deep_copy(inList: list) -> list: """Makes a deep copy of a list of lists""" if isinstance(inList, list): return list( map(deep_copy, inList) ) return inList
def bitrange_mask(imin, imax): """Return bit mask with bits set in ``range(imin, imax)``""" return (1 << imax) - (1 << imin)
def unescape_arg( data ): """Unescapes strings in data.""" # Remove all escaped \'s c = 0 while c < len( data ) - 1: if '\\' == data[c]: data = "%s%s" % ( data[:c], data[c+1:] ) c += 1 return data
def length_of_last_word(s): """ length_of_last_word :param s: :return: """ return len(s.strip().split(' ')[-1]) if s else 0