content
stringlengths
42
6.51k
def inversion_slow(arr): """ Counting the number of inversion by O(N*N). """ cnt = 0 for i in range(0, len(arr) - 1): for j in range(i + 1, len(arr)): if arr[i] > arr[j]: cnt += 1 return cnt
def _id_to_box(id_, dim): """Convert id to box ID""" row = id_ // (dim ** 3) col = (id_ % (dim ** 2)) // dim return row * dim + col
def get_size(origin_size = None, crop_size = None, resize_size = None): """ Get the resulting image size after cropping and resizing """ if resize_size is not None: image_size = resize_size elif crop_size is not None: image_size = crop_size elif origin_size: image_size = origin_s...
def doubles(digits): """ Return number of adjacent doubles. """ count = 0 for i in range(5): if digits[i] == digits[i+1]: count += 1 return count
def most_common(lst): """Returns the most common element in a list Args: lst (list): list with any datatype Returns: an element of lst (any): the most common element if commonests tie, randomly selected Raises: ValueError: if lst is None or empty...
def __id(self): """Return identifier of the dictionary.""" return getattr(self, "_id", None)
def get_goods_linked_to_destination_as_list(goods, country_id): """ Instead of iterating over each goods list of countries without the ability to break loops in django templating. This function will make a match for which goods are being exported to the country supplied, and return the list of goods...
def equals(data, expected): """ equals(data, expected) -> True if data and expected list are equals. """ if len(data) != len(expected): return False for index, item in enumerate(data): if expected[index] != item: return False return True
def check_result_add(Var: list): """ This check goes through Var list (1,a)(2,a)(3,b) ... and test if 1>=2>=3>=4 and a>=b>=c>= It means it fails if it not grows :param Var: result from add operation :return: True if need RaiseException, false - eveything ok """ prevNum = 1 prevAl...
def meta_value(file_name, meta_file, meta_table_key, key): """Get metadata value specifed in metadata file. Args: file_name: File in pipeline. meta_file: Metadata file to query. Has keys of top-level metadata such as "mesh_meta", "anim_meta", etc. meta_table_key: Key of the metadata tabl...
def swap_places_colon(ingredient): """Split string `ingredient` by colon and swap the first and second tokens.""" components = ingredient.split(':') if len(components) <= 1: return ingredient else: return '{} {}'.format( swap_places_colon(':'.join(components[1:])), components...
def all_not_none(*args): """ Returns a boolean indicating if all arguments are not None. """ return all(arg is not None for arg in args)
def tick(price, tick_size=0.05): """ Rounds a given price to the requested tick """ return round(price / tick_size) * tick_size
def get_label(s): """ >>> get_label('>Rosalind_4120') 'Rosalind_4120' """ return s[1:]
def avg(first_num, second_num): """computes the average of two numbers""" return (first_num + second_num) / 2.0
def merge_and_sort(first_half, second_half): """ This will merge two sorted subarrays. The subarrays are sorted from lowest to highest. This must handle when both merged elements are equal!! *** """ j = 0 # this is a counter assigned to first_half k = 0 # this is a counter assigned t...
def reversed_domain(s): """ >>> reversed_domain("aaa.bbb.ccc") 'ccc.bbb.aaa' """ return ".".join(reversed(s.split(".")))
def pseudoGPU(gpuRank,rank): """This is a temporary function to assign gpu's based on rank.""" if rank < 2: return gpuRank elif rank < 4: return list() #gpuRank elif rank < 6: return list() elif rank < 8: return list()
def pl_nap(time, nap_min): """power law nap time""" if(time<nap_min): return nap_min a = 2. b = 0.5 nap_max = 3600 #1 hour return (a*time**b)%nap_max
def get_unique_list(input_list): """Remove duplicates in list and retain order Parameters ---------- input_list : list any list of objects Returns ------- list input_list without duplicates """ rtn_list_unique = [] for value in input_list: if value not ...
def _parse_violations(pep8_output): """ Parse the pep8 output and count the number of violations. """ return len(pep8_output.splitlines())
def product(iterable): """ Returns the product of the elements of an iterable """ res = 1 for i in iterable: res *= i return res
def sticky_option(ctx, param, value): """parses sticky cli option""" if value: return 'SOURCE_IP' return None
def month_converter(month): """ brendan gave this to me - give it a 3 char month, returns integer """ months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] return months.index(month) + 1
def pivot_index(A, i0): """Finds a line of index >= i with the highest coefficient at column i in absolute value""" i_max = i0 for i in range(i0 + 1, len(A)): if abs(A[i]) > abs(A[i_max]): i_max = i return i_max
def seperate_messsage_person(message_with_person): """ Seperates the person from the message and returns both """ # Split by the first colon split_colon = message_with_person.split(":") # Get the person out of it and avoid the first whitespace person = split_colon.pop(0)[1:] # Stitch the...
def str_encode(dt, encoding="utf-8"): """ check dt type, then encoding """ if isinstance(dt, str): return dt.encode(encoding) if encoding else dt elif isinstance(dt, bytes): return dt else: raise TypeError("argument must be str or bytes, NOT {!r}".format(dt))
def onOffFromBool(b): """Return 'ON' if `b` is `True` and 'OFF' if `b` is `False` Parameters ---------- b : boolean The value to evaluate Return ------ 'ON' for `True`, 'OFF' for `False` """ #print(b) r = "ON" if b else "OFF" return r
def to_numeric(lit): """Return value of a numeric literal string. If the string can not be converted then the original string is returned. :param lit: :return: """ # Handle '0' if lit == '0': return 0 # Hex/Binary litneg = lit[1:] if lit[0] == '-' else lit if litneg[0] ...
def is_marked_match(marked_string_list, begin, length): """The function returns true if the match consists in the marked list, else false. @marked_string_list - list with marked indexes @begin - start index of match @length - length of match """ if begin in marked_string_list or \ (...
def get_variant_prices_from_lines(lines): """Get's price of each individual item within the lines.""" return [ line.variant.get_price() for line in lines for item in range(line.quantity)]
def harvest(varlist, advance): """Return set of best variables from list of best varlist is a list each element of which is a comma-separated list of variable names advance is how many winners to advance - at least the number of combinations""" # may return more or fewer variables than...
def set_bit(bitboard, bit): """ sets bit at position bit of bitboard to 1 """ return bitboard | (1 << bit)
def count_texts(text): """Return a tuple containing num of words, characters and lines.""" return len(text.split()), len(text), len(text.splitlines())
def play(board, turn): """ Plays next moviment based on the received current state(board) of the game. This function must returns the integer related to the position. So, if you want to play on p3, you must return 3, and so on. You are only allowed to play on positions which are currently None. ...
def add_postfix_to_keys(d: dict, postfix: str) -> dict: # pylint:disable=invalid-name """Update keys of a dictionary from "key" to "key_postfix""" d_ = {} # pylint:disable=invalid-name postfix = str(postfix) for key, value in d.items(): d_[key + '_' + postfix] = value return d_
def final(iterator): """Returns the final element of an iterator.""" ret = None for x in iterator: ret = x return ret
def tolist(x): """Convert a python tuple or singleton object to a list if not already a list """ if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif isinstance(x, set): return list(x) else: return [x]
def split_sbts_nodes_comms(dataset): """ Returns processed database :param dataset: list of sentence pairs :return: list of paralel data e.g. (['first source sentence', 'second', ...], ['first target sentence', 'second', ...]) """ sbts = [] nodes = [] comms = [] edges = [] f...
def _remove_namespace(subject: str) -> str: """If a namespace is present in the subject string, remove it.""" return subject.rsplit('}').pop()
def separate_time(undivided_time, is_seconds = False): """ Given the time in hours or seconds, returns the time in common divisions, i.e. days, hours, minutes, seconds """ if is_seconds is True: _undivided_time = undivided_time else: _undivided_time = undivided_time * 3600 d...
def IsInt(value: str) -> bool: """Check if a string can be safely casted to an int. Args: value (str): The string to check. Returns: bool: True if the string can be casted to an int. """ try: _ = int(value) except ValueError: return False return True
def tupleEqualNoOrder(t1: tuple, t2: tuple) -> bool: """Check if two two-element tuples have the same elements.""" assert len(t1) == 2 assert len(t2) == 2 if(t1[0] == t2[0]): return t1[1] == t2[1] else: return t1[0] == t2[1] and t1[1] == t2[0]
def get_method(name, attrs, bases, exclude=None): """ Gets a method of a class by name. :param name: Name of method to get. :type name: str :param attrs: Dictionary of class attributes. :type attrs: dict :param bases: Bases for the class to use for lookup. :type bases: list :param ex...
def get_range( samp ): """ Creates range object from input Parameters: * samp (list, array, tuple): array object with three elements [start, stop, step] Returns: * range: (start, stop, step) object Notes: * stop position is increased by addition with the step to allow for complete iteratio...
def loop_binary_search(data, target, low_index, high_index): """ Binary Search Iterativa """ while(low_index < high_index): mid_index = (low_index + high_index) // 2 if target == data[mid_index]: return True elif target < data[mid_index]: high_index = (mid_index -...
def get_model_vars(models, model_dir): """Method for getting model_vars if a Mallet object does not exist. Parameters: - models (list): A list of model numbers - model_dir (str): Path to the directory containing the models Returns: - model_vars (dict): A dict containing the model numbe...
def splice_signatures(*sigs): """Creates a new signature by splicing together any number of signatures. The splicing effectively flattens the top level input signatures. For instance, it would perform the following mapping: - `*sigs: sd1, (sd2, sd3, sd4), (), sd5` - return: `(sd1, sd2, sd3, sd4, sd5)` ...
def remove_duplicates(seq): """ Removes duplicates from a list. As seen in: http://stackoverflow.com/a/480227 """ seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)]
def rgb565(r, g=0, b=0): """Convert red, green and blue values (0-255) into a 16-bit 565 encoding.""" try: r, g, b = r # see if the first var is a tuple/list except TypeError: pass return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3
def column_value(item, args): """Return the value stored in a column. YAML usage: outputs: outcol: function: identity arguments: [col(KEYCOL)] value: column_value value_arguments: [col(VALUECOL)] """ return item[...
def within(value, min_value, max_value): """ Deterimine whether or not a values is within the limits provided. """ return (value >= min_value and value < max_value)
def create_popup_id_query_selector(iteration): """ :param iteration: :return: """ return '#' + 'popup' + iteration
def merge_two_dicts(into, merge_me): """Given two dicts, merge them into a new dict as a shallow copy.""" new_dict = into.copy() new_dict.update(merge_me) return new_dict
def is_right_censored(lc, frange): """ Returns true if the light curve is cutoff on the right. """ return len(lc['t0'])-1 in frange
def filter_type(findings, allowlist): """ Filter list of findings to return only those with a type in the allowlist. **Parameters** ``findings`` List of dictionary objects (JSON) for findings ``allowlist`` List of strings matching severity categories to allow through filter """...
def to_bool(value): """A slight modification of bool(). This function converts string literals 'True' and 'False' to boolean values accordingly. Parameters ---------- value The value to be converted to boolean. Raises ------ ValueError If literal value is not convertibl...
def _normalize_pkg_style(style): """ Internally, zip and fastzip internally behave similar to how an `inplace` python binary behaves in OSS Buck. """ if not style: return None # Support some aliases that are used internally, otherwise return the style # directly if it is unrecognize...
def _process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (List of Dictionaries) raw structured data to process Returns: List of Dictionaries. Each Dictionary represents a row in the csv file. """ # No further processing retu...
def str2float(item): """Convert string type to float type """ if item == 'NR': return None elif item: try: return float(item) except ValueError: return None else: return None
def d(d): """Decode the given bytes instance using UTF-8.""" return d.decode('UTF-8')
def _unsplit_name(name): """ Convert "this_name" into "This Name". """ return " ".join(s.capitalize() for s in name.split('_'))
def sliding_sum(report): """Meh >>> sliding_sum([199, 200, 208, 210, 200, 207, 240, 269, 260, 263]) [607, 618, 618, 617, 647, 716, 769, 792] """ return [sum(report[n : n + 3]) for n in range(len(report) - 2)]
def line2dict (feat_names, feat_vals, ignore_blank): """ Create dictionary from the input line.""" result = dict() if len(feat_names) != len(feat_vals): raise ValueError("Feature vector length does not match: expected=%s got=%s" % (len(feat_names),len(feat_vals))) for i in range(len(feat_names))...
def colnum_string(n): """ colnum_string: get column letter Args: n (int) index of column to get letter for Returns: str letter(s) of column """ string = "" while n > 0: n, remainder = divmod(n - 1, 26) string = chr(65 + remainder) + string return string
def filter_action_servers(topics): """ Returns a list of action servers """ action_servers = [] possible_action_server = '' possibility = [0, 0, 0, 0, 0] action_topics = ['cancel', 'feedback', 'goal', 'result', 'status'] for topic in sorted(topics): split = topic.split('/') if(l...
def smooth_color_func(niter, func): """Version of :func:`smooth_color` that accepts a function. Can be used to pre-calculate a color list outside of a loop. Parameters ---------- niter : int number of iterations func : callable Examples -------- >>> from pwtools import mpl...
def add_sub_token(sub_tokens, idx, tok_to_orig_index, all_query_tokens): """add sub tokens""" for sub_token in sub_tokens: tok_to_orig_index.append(idx) all_query_tokens.append(sub_token) return tok_to_orig_index, all_query_tokens
def dustSurfaceDensitySingle(R, Rin, Sig0, p): """ Calculates the dust surface density (Sigma d) from single power law. """ return Sig0 * pow(R / Rin, -p)
def fixedGradient(q, k, dx, U1): """ Neumann boundary condition Assume that the resulted gradient at BC is fixed. Please see any numerical analysis text book for details. Return: float """ Ug = q / k * 2 * dx + U1 return Ug
def exact_solution(t, x): """ Exact solition Solution. Parameters ---------- t x mode """ return 1 / (1 + x**2)
def mul2D(v1,v2): """Elementwise multiplication of vector v1 with v2""" return (v1[0] * v2[0], v1[1] * v2[1])
def get_texts_by_category(texts, categories, choose_category): """ :param texts: :param category: :return: """ text_chosen = [] for i in range(len(texts)): if categories[i] == choose_category: text_chosen += [texts[i]] return text_chosen
def escape(string, escape_chars, escape_with="\\"): """ Escapes all chars given inside the given string. :param string: The string where to escape characters. :param escape_chars: The string or Iterable that contains the characters to escape. Each char inside this string ...
def length_str(msec: float) -> str: """ Convert a number of milliseconds into a human-readable representation of the length of a track. """ seconds = (msec or 0)/1000 remainder_seconds = seconds % 60 minutes = (seconds - remainder_seconds) / 60 if minutes >= 60: remainder_minut...
def indicator(function_array_to_be_indicated, its_domain, barrier): """the indicator influences the function argument, not value. So here it iterates through x-domain and cuts any values of function with an argument less than H""" indicated = [] for index in range(len(its_domain)): if its_domain...
def ColonizeMac(mac): """ Given a MAC address, normalize its colons. Example: ABCDEF123456 -> AB:CD:EF:12:34:56 """ mac_no_colons = ''.join(mac.strip().split(':')) groups = (mac_no_colons[x:x+2] for x in range(0, len(mac_no_colons), 2)) return ':'.join(groups)
def normalize_program_type(program_type): """ Function that normalizes a program type string for use in a cache key. """ return str(program_type).lower()
def find_stem(arr): """ Find longest common substring in array of strings. From https://www.geeksforgeeks.org/longest-common-substring-array-strings/ """ # Determine size of the array n = len(arr) # Take first word from array # as reference s = arr[0] ll = len(s) res = "" ...
def _find_ancestors(individual, index): """ Find the ancestors of the node at the given index. :param individual: The individual to find the nodes in. :param index: The index of the node to find the ancestors of. :return: A list of indices that represent the ancestors. """ visited = 0 an...
def format_indentation(string): """ Replace indentation (4 spaces) with '\t' Args: string: A string. Returns: string: A string. """ return string.replace(" ", "&nbsp;&nbsp;&nbsp;&nbsp;")
def page_not_found(e): """Return a custom 404 error.""" return '<h1>Sorry, nothing at this URL.<h1>', 404
def intZASuffix( ZA_ii ) : """ZA_ii can be an integer (e.g., 92235) or a string of the from "zaZZZAAA_suffix" (e.g., "za095242m"). Returns the tuple integer ZA and _suffix from ZA_i. For examples, ZA_i = 92235 would return ( 92235, "" ) and ZA_i = "za095242m" would return ( 95242, "m" ).""" try :...
def remove_the_last_person(queue): """Remove the person in the last index from the queue and return their name. :param queue: list - names in the queue. :return: str - name that has been removed from the end of the queue. """ return queue.pop()
def get_light_events(events): """ :param events: :return: """ # Filter to keep only lights on and lights off events light_events = list(filter(lambda e: "light" in e[-1].lower(), events)) # Make sure events are sorted by init time light_events = sorted(light_events, key=lambda x: x[0])...
def is_cube(n): """Returns if a number is a cube""" return round(n ** (1/3)) ** 3 == n
def computeSignalValueInFrame(startbit, ln, fmt, value): """ compute the signal value in the frame """ import pprint frame = 0 if fmt == 1: # Intel # using "sawtooth bit counting policy" here pos = ((7 - (startbit % 8)) + 8*(int(startbit/8))) while ln > 0: # How...
def interval_trigger_dict(ts_epoch): """An interval trigger as a dictionary.""" return { 'weeks': 1, 'days': 1, 'hours': 1, 'minutes': 1, 'seconds': 1, 'start_date': ts_epoch, 'end_date': ts_epoch, 'timezone': 'utc', 'jitter': 1, }
def _preview_eval(value): """ Evaluate with mid and end""" mid = 0 end = 0 return eval(value,{"__builtins__":None},{"mid":mid,"end":end})
def controlPoints(cmd, data): """ Checks if there are control points in the path data Returns the indices of all values in the path data which are control points """ cmd = cmd.lower() if cmd in ['c', 's', 'q']: indices = range(len(data)) if cmd == 'c': # c: (x1 y1 x2 y2 x...
def is_dementia(code): """ ICD9 294.10, 294.11 , 294.20, 294.21 290.- (all codes and variants in 290.- tree) ICD10 F01.- All codes and their variants in this trees F02.- All codes and their variants in this trees F03.- All codes and their variants in this trees ...
def insertionSort(array): """ input: array of integers return : sorted array """ for i in range(1, len(array)): target = array[i] hole = i while hole > 0 and array[hole - 1] > target: array[hole] = array[hole - 1] hole = hole - 1 array[hole] ...
def vector(p0, p1): """Return the vector of the points p0 = (xo,yo), p1 = (x1,y1)""" a = p1[0] - p0[0] b = p1[1] - p0[1] return (a, b)
def get_phys_by_index(vnic, vnics, nics): """ Uses information stored in the OCI VNIC metadata to find the physical interface that a VNIC is associated with. Parameters ---------- vnic : dict The virtual interface card name. vnics : dict The list of virtual interface cards. ...
def numonlynoblank(tovalidate): """Returns T or F depending on whether the input is a single character in 0-9, or .""" return tovalidate.isdecimal() | (tovalidate == '.')
def xor(a: bool, b: bool) -> bool: """Boolean XOR operator. This implements the XOR boolean operator and has the following truth table: ===== ===== ======= a b a XOR b ===== ===== ======= True True False True False True False True True False False False ===== ===== ...
def replace(data, match, repl): """Replace variable with replacement text""" if isinstance(data, dict): return {k: replace(v, match, repl) for k, v in data.items()} elif isinstance(data, list): return [replace(i, match, repl) for i in data] else: return data.replace(match, repl)
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression """ result = {} for dictionary in dict_args: ...
def find_combos_internal_cache(adapters, position, cache): """Part 2 - recursion, using dynamic programming (cache/memoization) - wrote this afterwards""" # successful combo - we made it to the end! if position == len(adapters) - 1: return 1, cache # if the value is in the cache, grab it ...
def joule_to_kwh(joule): """ Convert joule to kilo Watt/hour How to Use: Give arguments for joule parameter *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: joule (int):energy in Joule ...