content
stringlengths
42
6.51k
def inversePair(nums): """[7,5,6,4]-->[7,6], [7,5], [7,4], [6,4], [5,4]""" def helper(nums): nonlocal ret if len(nums) == 1 or len(nums) == 0: return nums mid = len(nums) >> 1 left = helper(nums[:mid]) right = helper(nums[mid:]) seq = [] while len(left) ...
def findORF(dna_seq): """ Finds the longest open reading frame in the DNA sequence. """ tmpseq = dna_seq.upper(); orf = '' for i in range(0, len(tmpseq), 3): codon = tmpseq[i:i+3] if codon == 'ATG': orf = tmpseq[i:] break for i in range(0, len(orf), 3)...
def bar_grad(a=None, b=None, c=None, d=None): """Used in multiple tests to simplify formatting of expected result""" ret = [("width", "10em")] if all(x is None for x in [a, b, c, d]): return ret return ret + [ ( "background", f"linear-gradient(90deg,{','.join([x f...
def amp_img(html_code): """Convert <img> to <amp-img>""" return html_code.replace("<img", "<amp-img")
def build_allele_freq_map(allele_seq, freq_seq): """ Construct a <allele, freq> map, sorted by <freq> ascendingly. 0 in `allele_seq`, if exists, will be removed. Returned data structure is a list of tuples, e.g. getAlleleFreqMap(['A','G'], [0.2,0.8]) => [('A', 0.2), ('G', 0.8)] """ ...
def to_number(value): """ Helper function to cast strings to to int or float. """ if not isinstance(value, str): return value try: return int(value) except ValueError: return float(value)
def fix_non_aware_datetime(obj): """ Ugh - for SOME REASON some of the DateTime values returned by the PBS MM API are NOT time zone aware. SO - fudge them by adding 00:00:00 UTC (if even a time is not provided) or assume the time is UTC. """ if obj is None: return None if ':' not in obj:...
def dict_raise_on_duplicates(ordered_pairs): """Reject duplicate keys in a dictionary. RFC4627 merely says that keys in a JSON file SHOULD be unique. As such, `json.loads()` permits duplicate keys, and overwrites earlier values with those later in the string. In creating Rulesets, we wish to forbid duplic...
def is_instance(instance): """ Detects whether some object is an integer. :param instance: The instance of which to check whether it is an integer. :return: ``True`` if the object is an integer, or ``False`` if it isn't. """ return type(instance) == int
def csv_from_gdrive(url): """Take the URL of a CSV file in Google Drive and return a new URL that allows the file to be downloaded using `pd.read_csv()`. url: str, the URL of a CSV file in Google Drive. Returns: str, a URL""" file_id = url.split('/')[-2] download_url = 'https://d...
def quadratic_vertex(x, a, b, c): """The vertex form of quadratic function :reference:https://en.wikipedia.org/wiki/Quadratic_function :param x: independent variable :param a: coefficient {a} of quadratic function :param b: the x coordinates of the vertex :param c: the y coordinates of the verte...
def enrich_paperinfo_abstract(_paperinfos:list, _abstracts:dict) -> list: """ Enrich the list of information on the papers with their abstracts. The matching happens on bibcode. """ # Fill with a try-and-except statement for ii, _paper in enumerate(_paperinfos): try: _abstract =...
def _normalize_last_4(account_number: str): """Convert authorize.net account number to Saleor "last_4" format. Example: XXXX1111 > 1111 """ return account_number.strip("X")
def irshift(a, b): """Same as a >>= b.""" a >>= b return a
def filter_open(locations): """Given an iterable of locations, returns a list of those that are open for business. Args: locations (iterable): a list of objects inheriting from the covid19sim.base.Location class Returns: list """ return [loc for loc in locations if loc.is_open_for_...
def activate(context, path): """ For use in navigation. Returns "active" if the navigation page is the same as the page requested. The 'django.core.context_processors.request' context processor must be activated in your settings. In an exception, django doesnt use a RequestContext, so we can't...
def flatten_list(alist): """ Given a list like [["a", "b", "c"], ["d", "e"]] we want to flatten it to have something like: ["a", "b", "c", "d", "e"] """ my_list = [] for some_list in alist: for item in some_list: my_list.append(item) return my_list
def _is_deep_planning_clone(object): """ Return True iff object should be deep planning cloned, False otherwise. :param object: The object to check if it should be deep planning cloned. :return: True iff object should be deep planning cloned, False otherwise. """ return hasattr(type(object), '__...
def sh_severity_mapping(severity: str): """ Maps AWS finding string severity (LOW, Medium, High) into AWS finding number severity Args: severity: AWS finding string severity Returns: The number representation of the AWS finding severity """ severity_mapper = { 'Low': 1, ...
def make_feed_dict(feed_target_names, data): """construct feed dictionary""" feed_dict = {} if len(feed_target_names) == 1: feed_dict[feed_target_names[0]] = data else: for i in range(len(feed_target_names)): feed_dict[feed_target_names[i]] = data[i] return feed_dict
def words2spaced(normal_words): """ Change normal words to words with spaces between letters e.g. hlaupa to h l a u p a """ separated = [] for word in normal_words: separated.append(' '.join(char for char in word)) return separated
def eval_f(f, xs): """Takes a function f = f(x) and a list xs of values that should be used as arguments for f. The function eval_f should apply the function f subsequently to every value x in xs, and return a list fs of function values. I.e. for an input argument xs=[x0, x1, x2,..., xn] the functi...
def codes_extract_helper(obj, key): """ Traverses parent tree and returns flattened list of parent club codes """ arr = [] def extract(obj, arr, key): if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, (dict, list)): extra...
def transfer(item, from_collection, to_collection, n=1): """Move an item from one dictionary of objects to another. Returns True if the item was successfully transferred, False if it's not in from_collection. For example, to have the player pick up a pointy stick:: if transfer('po...
def prettify_obj(obj, indent=0): """Pass.""" spaces = " " * indent sub_indent = indent + 2 if isinstance(obj, dict): lines = ["", f"{spaces}-----"] if not indent else [] for k, v in obj.items(): lines += [f"{spaces}- {k}:", *prettify_obj(v, sub_indent)] return lines ...
def starstararg_func(**kwargs): """ >>> starstararg_func(a=1) 1 """ return kwargs['a']
def ge(a, b): """Is a >= b?""" if a[0] > b[0]: return True if a[0] < b[0]: return False return a[1] >= b[1]
def decode_temps(packet_value: int) -> float: """Decode potential negative temperatures.""" # https://github.com/Thrilleratplay/GoveeWatcher/issues/2 if packet_value & 0x800000: return float((packet_value ^ 0x800000) / -100) return float(packet_value / 10000)
def intersect(p1, p2, p3, p4): """ Determine if two line segments defined by the four points p1 & p2 and p3 & p4 intersect. If they do intersect, then return the fractional point of intersection "sa" along the first line at which the intersection occurs. """ # Precompute these values -- no...
def InterResdueDistance(ires,jres): """ not used """ # shortest interatomic contact between two residues ires and jres return 'xxx'
def split_s3_full_path(s3_path): """ Split "s3://foo/bar/baz" into "foo" and "bar/baz" """ bucket_name_and_directories = s3_path.split('//')[1] bucket_name, *directories = bucket_name_and_directories.split('/') directory_path = '/'.join(directories) return bucket_name, directory_path
def fiboRec ( number ): """Dangerous fibonacci-finder.... Use small numbers only! """ if number > 0: return (fiboRec( number - 1 ) + fiboRec( number -2 ) ) else: return 1
def validate_rule_id(value): """Raise exception if resolver rule id has invalid length.""" if value and len(value) > 64: return "have length less than or equal to 64" return ""
def _splice( l, offset, count, el ): """ Insert a list of elements in a given position of a list after removing a given number of previous elements. :param l: Source list. :param offset: Where to start inserting the new elements. :param count: How many elements will be disregarded from the source list. :param el:...
def color(marks, index): """Compute color for given mark index.""" steps_of_color = int(256 / len(marks) * 2) - 1 index_of_yellow_label = int(len(marks) / 2) if index < index_of_yellow_label: r = abs(0 - index) * steps_of_color g = 255 return 'fill:rgb({} {} {});'.format(r, g, 0...
def unquote_ends(istr): """Remove a single pair of quotes from the endpoints of a string.""" if not istr: return istr if (istr[0]=="'" and istr[-1]=="'") or \ (istr[0]=='"' and istr[-1]=='"'): return istr[1:-1] else: return istr
def factorize(N:int, pairs=True): """find factors/factor pairs of N Args: N (int): number pairs (bool, optional): whether to generate list of factor pairs or list of factors. Defaults to True. Returns: list: factor pairs (if pairs==True) else factors """ if pairs: f...
def get_ip_context(data): """ provide custom context information about ip address with data from Expanse API """ return { "Address": data['search'], "Geo": { "Location": "{0}:{1}".format( data['locationInformation'][0]['geolocation']['latitude'], ...
def deser_unary(ser): """ unary_zero$0 = Unary ~0; unary_succ$1 {n:#} x:(Unary ~n) = Unary ~(n + 1); """ n = 0 while True: r = ser.pop(0) if r: n += 1 else: return n, ser
def model_fixed_param(varparam, fixedparam, fixedindex, func, *arg, **kw): """Allow modeling with some parameters held constant. :INPUTS: varparam : sequence Primary parameters (which can be varied). fixedparam : sequence Secondary parameters (which should be held fixed.) ...
def weight_name_to_layer_name(weight_name): """Convert the name of weights to the layer name.""" tokens = weight_name.split("_") type_name = tokens[-1] # Modern naming convention. if type_name == "weights" or type_name == "bias": if len(tokens) >= 3 and tokens[-3] == "input": re...
def get_bound_color(svg_config, fill, stroke): """Get bound color.""" if svg_config['background'] == fill: return stroke return fill
def _is_json(content_type): """detect if a content-type is JSON""" # The value of Content-Type defined here: # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 return content_type.lower().strip().startswith('application/json') if content_type else False
def get_piece(board, index): """Returns the nth piece of the provided board""" board = board if board >= 0 else -board return (board % 10 ** (index + 1)) // 10 ** index
def dtype_calc(max_val): """Returns the dtype required to display the max val. args: max_val: set to negative to return signed int """ dtype_list = [ ['int8', 'int16', 'int32', 'int64'], ['uint8', 'uint16', 'uint32', 'uint64'], ] if max_val < 0: max_val *= -2 ...
def rivers_with_station(stations): """ Given list of stations, return as set of all the rivers names contained within these stations """ return set([station.river for station in stations])
def _process_dims(dims, names): """ Check if an xarray's dims contain something that is in *names* Parameters ---------- dims : tuple of str names : str or container of str Returns ------- i : int The index in dims """ if isinstance(names, int): return n...
def flat_list(my_list): """ Transform list of lists to flat list :param my_list: list of lists ex: [[1],[1, 2], [a,v]] :return: [1, 1, 2, a, v] """ return [element for each_list in my_list for element in each_list]
def list_range(x): """ Returns the range of a list. """ return max(x) - min(x)
def apply_docker_mappings(mountinfo, dockerpath): """ Parse the /proc/1/mountinfo file and apply the mappings so that docker paths are transformed into the host path equivalent so the Azure Pipelines finds the file assuming the path has been bind mounted from the host. """ for line in mountinfo....
def sent2labels(sent): """ Returns a list of labels, given a list of (token, pos_tag, label) tuples """ return [label for token, postag, label in sent]
def json_comply(obj): """Replace invalid JSON elements (inf, -inf, nan) with unambiguous strings.""" if issubclass(dict, type(obj)): return {key: json_comply(obj[key]) for key in obj} elif issubclass(list, type(obj)): return [json_comply(elem) for elem in obj] elif type(obj) is float: ...
def _convert_from_european_format(string): """ Conver the string given in the European format (commas as decimal points, full stops as the equivalent of commas), e.g. 1,200.5 would be written as 1.200,5 in the European format. :param str string: A representation of the value as a string :return...
def get_full_html_page_url(html_page_url): """The printable page is the full page.""" if "?" in html_page_url: plink = "{}&printable=1".format(html_page_url) else: plink = "{}?printable=1".format(html_page_url) return plink
def get_boundingbox(face, width, height, scale=1.3, minsize=None): """ Expects a dlib face to generate a quadratic bounding box. Args: face: dlib face class width: frame width height: frame height scale: bounding box size multiplier to get a bigger face region minsize: set minimum bounding ...
def Armijo_Rule(f_next,f_initial,c1,step_size,pg_initial): """ :param f_next: New value of the function to be optimized wrt/ step size :param f_initial: Value of the function before line search for optimum step size :param c1: 0<c1<c2<1 :param step_size: step size to be tested :param pg: i...
def reverseIntegerB(x): """ :type x: int :rtype: int """ if x == 0: return 0 n=str(x) start=False if x> 0: result="" for i in range(len(n)-1,-1,-1): if n[i] != "0": result+=n[i] start=True elif n[i] == "0" and start == True: result+=n[i] result=int(result) return 0 if result > p...
def quality_check(data): """ Expects string, returns tuple with valid data or False when data was invalid """ valid = len(data.split(",")) == 18 if data != False and valid: return data else: return False
def intersect_lines(p1, p2, p3, p4): """ Calculates intersection point between two lines defined as (p1, p2) and (p3, p4). Args: p1: (float, float) Point 1 as (x, y) coordinates. p2: (float, float) Point 2 as (x, y) coordinates. p3: ...
def get_state_xy(idx, num_cols): """Given state index this method returns its equivalent coordinate (x,y). Args: idx: index uniquely identifying a state num_cols: number of colums Returns: values x, y describing the state's location in the grid """ y = int(idx % num_cols) x = int((idx - y) / num...
def lerp(a, b, t): """ Returns the linear interpolation between a and b for time t between 0.0-1.0. For example: lerp(100, 200, 0.5) => 150. """ if t < 0.0: return a if t > 1.0: return b return a + (b-a)*t
def is_more_options(text: str): """ A utility method to determine if we scroll to the next few options. """ sample_phrases = [ "more options", "none", "neither", "none of these", "neither of these", "none of them", "neither of them", "show me more" ] text = text.strip() retu...
def results_exist(parms_fixed, pool_results): """ Helper function to determine whether results exist. Parameters ---------- parms_fixed : list, Index of parameters to fix pool_results : dict, Contains both index of parameters fixed and the corresponding results Returns ...
def construct_package_url(base_url, dist, arch, sha256): """ Construct a package URL for a debian package using the 'by-hash' path. See: https://wiki.debian.org/DebianRepository/Format#indices_acquisition_via_hashsums_.28by-hash.29 Example: http://us.archive.ubuntu.com/ubuntu/dists/bionic/by-hash/SHA25...
def escape(filename): """Escape the filename >>> escape("(3-ethoxypropyl)mercury bromide.sk2") '{(}3-ethoxypropyl{)}mercury bromide.sk2' """ newfilename = filename.replace("(", "{(}").replace(")", "{)}") return newfilename
def get_datastore_version_id(client, datastore, version): """return the id of a datastore version arguments: client -- an authenticated trove client datastore -- the id of a datastore version -- the version to find returns: """ try: store = client.datastores.find(id=datastore) ...
def _maybe_correct_vars(vars): """Change vars from string to singleton tuple of string, if necessary.""" if isinstance(vars, str): return (vars,) else: return vars
def number_routs(cube_size=20): """Find routes using mathimatical summation of sum of paths for each node in a matrix structure""" L = [1] * cube_size for i in range(cube_size): for j in range(i): L[j] = L[j]+L[j-1] L[i] = 2 * L[i - 1] return L[cube_size - 1]
def string_address(address): """Make a string representation of the address""" if len(address) < 7: return None addr_string = '' for i in range(5): addr_string += (format(address[i], '02x') + ':') addr_string += format(address[5], '02x') + ' ' if address[6]: ...
def longest_increasing_sub_seq(arr): """ Ask the data type and corner cases. Interviewer says as below. - arr is not empty - all element is INT Let dp[i] denote the length of the longest increasing sequence ending at i. Search arr[j] < arr[i] where j in range(i). If not exist such j: d...
def sent_splitter_multi(doc, split_symb, incl_split_symb=False): """Splits `doc` by sentences where boundaries are based on multiple units in `split_symb`. For example, if a separator is a sequence of subword ids. Args: doc (list/array/tensor): tokens/ids. split_symb (list): subwords corres...
def phi_chain(n): """ For each number in 1 to n, compute the Smolyak indices for the corresponding basis functions. This is the :math:`n` in :math:`\\phi_n` Parameters ---------- n : int The last Smolyak index :math:`n` for which the basis polynomial indices should be found ...
def determine_state(n): """ Recursive Rule: - any n bellow 1 is cold because the player who go will loose - The number n is hot if at least one case (n-1 or n/2) is cold """ # base recursive case if n < 1: return "cold" else: state_1 = determine_stat...
def flatten(list_of_lists): """ Recursivey flattens a list of lists :return: List, flattened list elements in sub-lists """ if list_of_lists == []: return list_of_lists if isinstance(list_of_lists[0], list): return flatten(list_of_lists[0]) + flatten(list_of_lists[1:]) return...
def transformImages(images): """ Returns images all with size (28, 28) :param images: list of images :type images: List(PIL.Image.Image) :return: List(PIL.Image.Image) """ for i in range(len(images)): width, height = images[i].size if width != 28 or height != 28: ...
def compress_macro(macros): """ Convert a macros dictionary into a macro specification :param macros: dictionary :return: Macro specification in the format "key=value,key=value,..." """ return ",".join(["{}={}".format(key, value) for key, value in sorted(macros.items())])
def GCD(list_1): """ :param list_1: list of numbers :return: greatest common divisor gcd of numbers in the list_1 """ numbers_sorted = sorted(list_1) gcd = numbers_sorted[0] for i in range(1, int(len(list_1))): divisor = gcd dividend = numbers_sorted[i] remainder = ...
def is_enum_namestack(nameStack): """Determines if a namestack is an enum namestack""" if len(nameStack) == 0: return False if nameStack[0] == "enum": return True if len(nameStack) > 1 and nameStack[0] == "typedef" and nameStack[1] == "enum": return True return False
def _get_clause_and_remainder(pat): """Breaks a graph pattern up into two parts - the next clause, and the remainder of the string Parameters ---------- pat: str graph pattern fragment """ pat = pat.strip() opening = 1 # if there is a parentheses, we treat it as a clause and go ...
def get_string_range(float_range, x_buffer=0, y_buffer=0): """ Buffer is for the possible interface between pixel-node-registered and gridline-node-registered files :param float_range: list, [w, e, s, n] :type float_range: list :param x_buffer: possible interface between pixel-node-registered etc. ...
def httpPost(url, *args): """Retrieves the document at the given URL using the HTTP POST protocol. If a parameter dictionary argument is specified, the entries in the dictionary will encoded in "application/x-www-form-urlencoded" format, and then posted. You can post arbitrary data as well, but ...
def check_config_inputs(arg): """ Checks that all the data that should be numerical from that config can be represented as a float. Parameters ---------- arg: unknown any argument can be passed. Returns ------- is_number: Boolean Value is True if the arg is a number...
def horner_formula(coefs): """ A relatively efficient form to evaluate a polynomial. E.g.: horner_formula((10, 20, 30, 0, -50)) == '(10 + x * (20 + x * (30 + x * x * -50)))', which is 4 multiplies and 3 adds.""" c = coefs[0] if len(coefs) == 1: return str(c) else: ...
def _is_tachychardic(age: int, heart_rate: int): """ Determines if user is tacahychardic based on age and heart rate. Based on: https://en.wikipedia.org/wiki/Tachycardia Args: age (int): Age of the user. heart_rate (int): Heartrate of the user. Returns: bool: Whether or not the ...
def drop_id_prefixes(item): """Rename keys ending in 'id', to just be 'id' for nested dicts. """ if isinstance(item, list): return [drop_id_prefixes(i) for i in item] if isinstance(item, dict): return { 'id' if k.endswith('id') else k: drop_id_prefixes(v) for k, v...
def extract_header(msg_or_header): """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire message. h = msg_or_header["header"] except KeyError: try: # See if msg_or_header is just the heade...
def Dir(v): """Like dir(v), but only non __ names""" return [n for n in dir(v) if not n.startswith('__')]
def circular_mask_string(centre_ra_dec_posns, aperture_radius="1arcmin"): """Get a mask string representing circular apertures about (x,y) tuples""" mask = '' if centre_ra_dec_posns is None: return mask for coords in centre_ra_dec_posns: mask += 'circle [ [ {x} , {y}] , {r} ]\n'.format( ...
def _get_wind_direction(wind_direction_degree: float) -> str: """Convert wind direction degree to named direction.""" if 11.25 <= wind_direction_degree < 33.75: return "NNE" if 33.75 <= wind_direction_degree < 56.25: return "NE" if 56.25 <= wind_direction_degree < 78.75: return "...
def exif_offset_to_seconds(offset: str) -> int: """Convert timezone offset from UTC in exiftool format (+/-hh:mm) to seconds""" sign = 1 if offset[0] == "+" else -1 hours, minutes = offset[1:].split(":") return sign * (int(hours) * 3600 + int(minutes) * 60)
def sphere_function(vals, modgen): """ A very easy test function Parameters: vals - a list specifying the point in N-dimensionsla space to be evaluated modegen - a function """ total = 0.0 for i in range(len(vals)): if modgen != None: ...
def getAdjNodes(curr_node, validPoints, clearance): """ Definition --- Method to generate all adjacent nodes for a given node Parameters --- curr_node : node of intrest validPoints : list of all valid points clearance : minimum distance required from obstacles Returns --- ...
def getIndexDict(idx, labels, shape): """ Get the index tuple of an index in given shape, with the labels. Parameters ---------- idx : int The index that will be decomposed. labels : list of str The labels corresponding to each dimension. shape : tuple of int The sha...
def dec_byte(byte, pct): """decrements byte by percentage""" byte -= byte * pct / 100 return max(byte, 0)
def unfold_parallel(lists, n_jobs): """Internal function to unfold the results returned from the parallization Parameters ---------- lists : list The results from the parallelization operations. n_jobs : optional (default=1) The number of jobs to run in parallel for both `fit` and ...
def projectionArea(grid): """ :type grid: List[List[int]] :rtype: int """ z = 0 for col in grid: for row in col: if row != 0: z += 1 x = 0 for col in grid: maxx = 0 for row in col: maxx = max(row, maxx) x += maxx y = 0 ...
def sort_a_string(s: str) -> str: """Takes a string and returns a string with those words sorted alphabetically. Case should be ignored... and punctuation...""" word_list = sorted([eachWord.lower() + eachWord for eachWord in s.split()]) # print(word_list) cleaned_word_list = [eachWord[len(eachWord)/...
def procesar_transportes(tipo, lista): """Funcion que muestra los transportes mas utilizados en base a la cantidad de ventas""" lista_transportes = [] #lista que almacena los transportes mas utilizados lista_procesados = [] #lista que almacena los transportes ya procesados tipo_registro = tipo #alma...
def euclidean(x, y): """ finds the greatest common denominator of two numbers """ if y == 0: return x z = x % y return euclidean(y, z)
def check_duplicate_face(f, l): """Check if a face `f` is already in the list `l`. We need this function here because when some rotation r fixes a face f = (v1, v2, ..., v_k), r maps f as an ordered tuple to (v_k, v_1, ..., v_{k-1}) or (v_2, ..., v_k, v_1) where they all represent the sa...