content
stringlengths
42
6.51k
def sort_key(model): """key function for case-insensitive sort by name and type""" iname = model['data']['name'].lower() type_key = { 'directory' : '0', 'notebook' : '1', 'file' : '2', }.get(model['data']['type'], '9') return u'%s%s' % (type_key, iname)
def format_quote(q, num, n_quotes): """Returns a formatted string of a quote""" ctime, nick, msg = q return "[{}/{}] <{}> {}".format(num, n_quotes, nick, msg)
def str2bool(v): """ converts a string to a boolean """ return v.lower() in ("yes", "true", "t", "1")
def as_int(obj, quiet=False): """Converts an arbitrary value into a integer.""" # Try "2" -> 2 try: return int(obj) except (ValueError, TypeError): pass # Try "2.5" -> 2 try: return int(float(obj)) except (ValueError, TypeError): pass # Eck, not sure what ...
def handle(event, context): """handle a request to the function Args: event (dict): request params context (dict): function call metadata """ return { "message": "Hello From Python3 runtime on Serverless Framework and Scaleway Functions" }
def _describe_instances_response(response): """ Generates a response for a describe instance request. @param response: Response from Cloudstack. @return: Response. """ return { 'template_name_or_list': 'instances.xml', 'response_type': 'DescribeInstancesResponse', 'respo...
def maxSubArray(nums) -> int: """ https://leetcode-cn.com/problems/maximum-subarray/ :param nums: :return: """ n = len(nums) matrix = [0 for i in range(n)] ans = matrix[0] = nums[0] for j in range(1, n): matrix[j] = max(matrix[j - 1] + nums[j], nums[j]) print(matrix) ...
def into_path(item, after, last_title): """ (Pdb) pp item, after, last_title ('features/termcasts/zab/baz.md', 'features/termcasts/index.md', '3.Features.3.TermCasts.0.Overview') Then we return '3.Features.3.TermCasts.0' """ while not item.startswith(after): after = after.rsplit('/', 1)...
def str_to_hex(string): """ Returns a string in readable hex encoding. Args: string: A string to convert to readable hex. Returns: A string in hex format. """ return ":".join(x.encode('hex') for x in string)
def _remove_by_index_list(text, index_list): """Remove all substrings inside a string, thanks to the given list of indexes """ len_removed = 0 for i in index_list: i_start = i[0] - len_removed i_end = i[1]-len_removed text = text[:i_start] + text[i_end:] len_removed += i[1]-i...
def get_games_per_worker(games, max_workers): """Calculates the number of games each processor should play. Args: games (int): Total number of games to be played. max_workers (int): Number of processors that will play those games. Returns: list[int]: Number of games each processor...
def _children_key(key): """Create a key that corresponds to the group's children Parameters ---------- key : str The group key Returns ------- str The augmented key """ return key + ':children'
def condense_classification(classification): """Returns a condensed classification string""" return { 'classif': [_.strip() for _ in classification.split(",")] }
def dictionary_filter(dictionary, cols) -> dict: """Can be used to filter certain keys from a dict :param dictionary: The original dictionary :param cols: The searched columns :return: A filtered dictionary """ return {key:value for (key,value) in dictionary.items() if key in cols}
def join_regex(regexes): """Combine a list of regexes into one that matches any of them.""" if len(regexes) > 1: return "(" + ")|(".join(regexes) + ")" elif regexes: return regexes[0] else: return ""
def remove_duplicates(seq, keep=()): """ Remove duplicates from a sequence while perserving order. The optional tuple argument "keep" can be given to specificy each string you don't want to be removed as a duplicate. """ seq2 = [] seen = set() for i in seq: if i in (keep): ...
def iops(parameter='nodisk'): """ Get amount of IOs per second """ return 'disk', '0'
def update_detections(visualizer, old_det_geometries, new_det_geometries): """Update detections that has a previous geometry object.""" for geometry in old_det_geometries: visualizer.remove_geometry(geometry, False) for geometry in new_det_geometries: visualizer.add_geometry(geometry, False...
def sort_toc(toc): """ Sort the Table of Contents elements. """ def normalize(element): """ Return a sorting order for a TOC element, primarily based on the index, and the type of content. """ # The general order of a regulation is: regulation text sections, # appendices, and t...
def freq(mylist, item): """Return the relative frequency of an item of a list. :param mylist: (list) list of elements :param item: (any) an element of the list (or not!) :returns: frequency (float) of item in mylist """ return float(mylist.count(item)) / float(len(mylist))
def windows(lst): """Return a list of 3-element sliding windows from a list""" return list(zip(lst, lst[1:], lst[2:]))
def is_number(string): """String is a number.""" try: float(string) return True except ValueError: return False
def is_even(x): """True if x is even, False if x is odd""" return x % 2 == 0
def list2cmdline(lst): """ convert list to a cmd.exe-compatible command string """ nlst = [] for arg in lst: if not arg: nlst.append('""') else: nlst.append('"%s"' % arg) return " ".join(nlst)
def diff_lists(list1,list2, option=None): """ if option equal 'and', return a list of items which are in both list1 and list2. Otherwise, return a list of items in list1 but not in list2. """ if option and option == 'and': return [x for x in list1 if x in list2] else: return [x...
def loop_erasure(path): """Return the loop-erasure of a discrete sample path. Parameters ---------- path : sequence A sequence of hashable values. Returns ------- tuple The loop erasure of `path`. """ if len(path) == 0: return () last_index = {x: k for ...
def integer_log2_round_up(x): """ Returns the number of bits required to represent `x` distinct values---i.e. log2(x) rounded up. """ assert x > 0 bits = 1 representable = 2 ** bits while representable < x: bits += 1 representable *= 2 return bits
def parentIdx(idx): """ >>> parentIdx(1) 0 >>> parentIdx(2) 0 >>> parentIdx(3) 1 >>> parentIdx(4) 1 """ return (idx - 1) // 2
def get_origin(array, plot_origin): """Get the (y,x) origin of the ccd data if it going to be plotted. Parameters ----------- array : data.array.scaled_array.ScaledArray The array from which the origin is extracted. plot_origin : True If true, the origin of the data's coordinate sys...
def quick_pow(n: int, k: int, p: int) -> int: """Find n^k % p quickly""" if k == 0: return 1 tmp = quick_pow(n, k // 2, p) ** 2 return tmp % p if k % 2 == 0 else tmp * n % p
def rescale(start, stop, length_sequence): """Rescales negative strand start-stop positions to positive strand indexing""" rescaled_start = length_sequence - stop - 1 rescaled_stop = length_sequence - start - 1 return(rescaled_start, rescaled_stop)
def basic_detokenizer(words): """ This is the basic detokenizer helps us to resolves the issues we created by our tokenizer""" detokenize_sentence =[] pos = 0 while( pos < len(words)): if words[pos] in '-/.' and pos > 0 and pos < len(words) - 1: left = detokenize_sentence.pop() detokenize_sentence.append(l...
def mu(alpha, beta): """The mean of the Beta distribution.""" return alpha / (alpha + beta)
def add_predecessor(predecessor_list, xml_data_list, output_xml): """ Check if input lists is not empty, write in xml for each list and return update list if some updates has been made Parameters: predecessor_list ([Data, Data(predecessor)]) : Data object to set new predessor and ...
def add_labels_to_predictions_strict(preds, golds, strict=True): """ Returns predictions and missed gold annotations with a "label" key, which can take one of "TP", "FP", or "FN". """ pred_spans = {(s["start"], s["end"]) for s in preds} gold_spans = {(s["start"], s["end"]) for s in golds} ou...
def bucket_sort(arr, k): """ Based on Data Structures and Algorithms in Python This can't handle decimals :param arr: Sequence of integer keys :param k: an integer such that all keys are in the range [0, k-1] :return: arr in sorted order """ output = [] # n space...
def isPrefixOf(xs, ys): """ isPrefixOf :: Eq a => [a] -> [a] -> Bool The isPrefixOf function takes two lists and returns True iff the first list is a prefix of the second. """ return xs == ys[:len(xs)]
def serialize_dimensions(dims): """ >>> serialize_dimensions({}) "" >>> serialize_dimensions({'time': 'foo', 'eleveation': '100m'}) "elevation=100m,time=foo" """ if not dims: return "" return ','.join(k + '=' + dims[k] for k in sorted(dims.keys()))
def _validate_condition(password, fn, min_count): """ Validates the password using the given function. This is performed by iterating through each character in the password and counting up the number of characters that satisfy the function. Parameters: password (str): the password f...
def CleanUpUserInput(mask): """Removes spaces from a field mask provided by user.""" return mask.replace(" ", "")
def to_left(d): """return direction as vector, rotated 90 degrees left""" return -d[1], d[0]
def merge_street_address(*address_vals): """Merge the different pieces of a street address into a single, space-separated string. Returns ------- str The merged address """ valid_vals = [str(c).strip() for c in address_vals if str(c) not in ("nan", "None")] return " ".join(valid_val...
def _extract_prop_set(line): """ Extract the (key, value)-tuple from a string like: >>> 'set foo = "bar"' :param line: :return: tuple (key, value) """ token = ' = "' line = line[4:] pos = line.find(token) return line[:pos], line[pos + 4:-1]
def slice_params(axis, factor): """Get the start and stop indices to slice a dimension of size `axis` into a multiple of `factor`, keeping it centered.""" new_size = (axis // factor) * factor start = (axis - new_size) // 2 end = axis - (axis - new_size - start) return start, end
def make_interval_weight(num_intervals): """ Used to calculate loss event rate. """ return [ (1 if i < num_intervals / 2 else 2 * (num_intervals - i) / (num_intervals + 2)) for i in range(num_intervals)]
def make_pin_name(port, index): """ Formats a pin name of a multi-bit port """ return "{}_b{}".format(port, index)
def irc_split(buf): """ Split a protocol line into tokens (without decoding or interpreting). """ buf = buf.rstrip(b"\r\n").split(b" ") i, n = 0, len(buf) parv = [] # Skip leading whitespace while i < n and buf[i] == b"": i += 1 # Get @tags if present if i < n and buf[i...
def make_slack_msg(target_list, player_list): """Emit a message suitable for posting to the assassing slack channel.""" msg = '\n'.join(["This week's assassins and targets are assigned, and emails have been sent.", 'The roster is:', '*Targets*: "{}"', ...
def all_equal(iterable): """Return True if all elements of iterable are equal. iterable must contain at least one element. >>> all_equal([1, 1.0]) True >>> all_equal([1, 2]) False """ iterator = iter(iterable) first = next(iterator) for element in iterator: if element !...
def merge_dicts(x, y): """ Merge two dicts together, returns a new dict """ z = x.copy() # start with x's keys and values z.update(y) # modifies z with y's keys and values & returns None return z
def validate_extended(mwtabfile, data_section_key): """Validate ``EXTENDED_MS_METABOLITE_DATA``, ``EXTENDED_NMR_METABOLITE_DATA``, and ``EXTENDED_NMR_BINNED_DATA`` sections. :param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`. :type mwtabfile: :class:`~mwtab.mwtab.MWTabFile` or ...
def _insert(lst: list, i: int) -> None: """ Move L[i] to where it belongs in L[i + 1] Precondition: L[:i] is sorted from smallest to largest. >>> L = [7, 3, 5, 2] >>> _insert(L, 1) >>> L [3, 7, 5, 2] """ # The value to be inserted into the sorted part of the list value = lst[i] ...
def _exclusions_1_3(bonds_mol): """ Based on the information inside bonds_mol determine the 1-3 exclusions ToDo: write a non-naive version of this """ angles_mol = [] for idx, i in enumerate(bonds_mol): a, b = i for j in bonds_mol[idx + 1:]: c, d = j if ...
def get_media_urls_from_list(tweets,limit): """ Returns the set of media URLs from a list of tweets """ cnt = 0 media_files = set() for status in tweets: media = status.entities.get('media',[]) if (len(media) > 0): # each status may have multiple for i in range (0, le...
def normalize(value, value_min, value_max): """Map value from [value_min, value_max] to [-1, 1]""" return 2 * ((value - value_min) / (value_max - value_min)) - 1
def clean_value(value): """ Clean the value; if N/A or empty :param value: original value :return: cleaned value """ if value: value = value.strip() if value.lower() == 'n/a': value = None if value == '': value = None return value
def getMeasureString(measureName, value): """Returns the string represenation of one measure with its value.""" return "measure{\n key: \"" + measureName + "\"\n value: \"" + str(value) + "\"\n}"
def get_uid_cidx(img_name): """ :param img_name: format output_path / f'{uid} cam{cidx} rgb.png' """ img_name = img_name.split("/")[-1] assert img_name[-8:] == " rgb.png" img_name = img_name[:-8] import re m = re.search(r'\d+$', img_name) assert not m is None cidx = int(m.group(...
def prepare_droid_list(device): """ Convert single devices to a list, if necessary. :param device: Device to check. :type device: str """ if isinstance(device, list): devs = device else: devs = [device] return devs
def is_valid_event(event): """ Check the validation of the s3 event. """ s3_bucket_name = event["s3"]["bucket"]["name"] if s3_bucket_name: return True else: return False
def str_list(pyList, interface): """ method str_list Return a string containing the str( ) of the items in the given pyList Arguments: pyList - python list to be converted to string """ new_str = "" for list_item in pyList: new_str += str(list_item.__repr__(interface)) retu...
def replace_with_flag(locale): """The filter replaces the locale with the CSS flag classes of the flag-icon-css library.""" locale = locale.replace('-', '_').lower().rsplit('_', maxsplit=1) if len(locale) == 2: return f'flag-icon flag-icon-{locale[-1]}' return ''
def rsa_compare_keys(a, b): """ Compares the base64 encoded DER structure of the keys """ # Filter removes possible empty lines. # We then slice away header and footer. a_b64 = "".join(list(filter(None, a.splitlines()))[1:-1]) b_b64 = "".join(list(filter(None, b.splitlines()))[1:-1]) ret...
def __get_key(peak1, peak2): """Generates a "key" from two peaks. Parameters ---------- peak1, peak2 : List[Tuple[int, int]] The two peaks to generate a key from, where each peak is given by Tuple[<time>, <freq>]. Assumes `peak2` occurs concurrently or after `peak1`. Return...
def clamp(test, lower, upper): """Force a number to be within a given range, with minimal efficiency.""" return max(lower, min(upper, test))
def add_multi_amounts(ma1,ma2): """ Add two multi amounts. """ # Union all possible currencies: currencies = set(ma1.keys()) currencies.update(set(ma2.keys())) # Initialize resulting multi amount: ma = {} # Initialize all currencies to be 0: for c in currencies: ma[c] =...
def per_shortest(total, x, y): """Divides total by min(len(x), len(y)). Useful for normalizing per-item results from sequences that are zipped together. Always returns 0 if one of the sequences is empty (to avoid divide by zero error). """ shortest = min(len(x), len(y)) if not shortest: ...
def ffs(n): """find first set bit in a 32-bit number""" r = 0 while r < 32: if (1<<r)&n: return r r = r+1 return -1
def add_to_tuple(var, *args, **kw): """ Append new items inside a tuple. This utility method should be used to modify settings tuples and lists. Features: * Avoid duplicates by checking whether the items are already there; * Add many items at once; * Allow to add the items before some oth...
def lift_list(input_list): """ List of nested lists becomes a list with the element exposed in the main list. :param input_list: a list of lists. :return: eliminates the first nesting levels of lists. E.G. >> lift_list([1, 2, [1,2,3], [1,2], [4,5, 6], [3,4]]) [1, 2, 1, 2, 3, 1, 2, 4, 5, 6, 3...
def rational_function(X): """ Benchmark rational function f(x) = x/(x + 1)*2 """ return X/((X+1)**2)
def str_skip_bytes(s, dels): """ """ if not dels: return s return ''.join(c for i, c in enumerate(s) if i not in dels)
def oraclechr_encode(encvalue): """ Oracle chr encode the specified value. """ charstring = "" for item in encvalue: val = "chr(" + str(ord(item)) + ")||" charstring += val return(charstring.rstrip("||"))
def insertion_sort(l, r): """ Sorts a list using Insertion Sort Algorithm """ k = 0 l = l.copy() for i in range(1, r, 1): k = l[i] j = i - 1 while j >= 0 and k < l[j]: l[j + 1] = l[j] j -= 1 l[j + 1] = k return l
def severity_to_level(severity): """ Maps severity to a level represented by number. """ if severity == 'Informational': return 0.5 elif severity == 'Low': return 1 elif severity == 'Medium': return 2 elif severity == 'High': return 3 return 0
def sort_addresstuple(cube_dimensions, unsorted_addresstuple): """ Sort the given mixed up addresstuple :param cube_dimensions: list of dimension names in correct order :param unsorted_addresstuple: list of Strings - ['[dim2].[elem4]','[dim1].[elem2]',...] :return: Tuple: ('[dim1].[elem2]','[d...
def extract_id(argument: str, strict: bool=True): """Extract id from argument.""" """ Parameters ---------- argument: str text to parse Returns ---------- str the bare id """ ex = ''.join(list(filter(str.isdigit, str(argument)))) if strict: if len(ex)...
def is_quoted_identifier(identifier, sql_mode=""): """Check if the given identifier is quoted. Args: identifier (string): Identifier to check. sql_mode (Optional[string]): SQL mode. Returns: `True` if the identifier has backtick quotes, and False otherwise. """ if "ANSI_QUO...
def bases_overlap(frst, scnd): """ Get the number of overlapping bases. :param frst: a tuple representing the first region with chromosome, start, end as the first 3 columns :param scnd: a tuple representing the second region with chromosome, s...
def _EvaluateCondition(condition): """Evaluates |condition| using eval(). Args: condition: A condition string. Returns: The result of the evaluated condition. """ return eval(condition, {'__builtins__': {'False': False, 'True': True}})
def prep_carrier_query(npc, device, upg, forced): """ Prepare carrier query XML. :param npc: MCC + MNC (see `func:return_npc`) :type npc: int :param device: Hexadecimal hardware ID. :type device: str :param upg: "upgrade" or "repair". :type upg: str :param forced: Force a softwar...
def parsesplittedproperty(property, separator=';'): """ :param property :return: a list single properties, possibly empty """ properties = [] if property and len(property) > 0: for splittedproperty in property.split(separator): properties.append(splittedproperty.strip()) ...
def fuzzbuzz(num): """ >>> fuzzbuzz(4) 4 >>> fuzzbuzz(3) 'fuzz' >>> fuzzbuzz(5) 'buzz' >>> fuzzbuzz(9) 'fuzz' >>> fuzzbuzz(10) 'buzz' >>> fuzzbuzz(15) 'fuzzbuzz' """ if num % 3 == 0 and num % 5 == 0: return 'fuzzbuzz' elif num % 3 == 0: return 'fuzz' elif num % 5 == 0: retu...
def index_of_first_negative(numbers): """ What comes in: -- a sequence of numbers What goes out: Returns the INDEX of the first negative number in the given sequence of numbers, or -1 if the sequence contains no negative numbers. Note: "first" negative number means the negative numbe...
def _get_received_for(received_header): """ Helper function to grab the 'for' part of a Received email header WARNING: If 'for' is not there, the entire Received header is returned. """ received_header = received_header.replace('\r', '').replace('\n', '') info = received_header.split('for ') ...
def check_coarse_pipeline(msgs): # type: (str) -> bool """ Check if coarse pipeline is enabled as expected """ for msg in msgs: if msg.find('\"coarse_grained_pipeline": \"off') != -1: return False return True
def all_subclasses(cls): """Returns a set of all the subclasses of the given class""" subs = cls.__subclasses__() return set(subs).union([s for c in subs for s in all_subclasses(c)])
def reverse_integer(integer): """ runtime complexity of this algorithm is O(n) """ reversed = 0 # Pop the last digit of the integer after each iteration # Then update the value of the integer while integer > 0 : remainder = integer % 10 reversed = reversed*10 + remainder i...
def intro(word, attempt_left): """ :param word: str, the word randomly selected from our word bank. :param attempt_left: int, the guessing attempts left for players, before guessing. :return: str, number of alphabets in the given words, presented in '-' """ ans = '' for i in range(len(word))...
def update_output_frame_video_rate_metric(ml_output_names): """Update the metrics of the "Output Video Frame Rate (avg)" dashboard dashboard widget""" result = [] for output in ml_output_names: if output["Pipeline"] == "0": entry = ["MediaLive", "OutputVideoFrameRate", "ChannelId", ...
def ordinal(n): """Return the ordinal for an int, eg 1st, 2nd, 3rd. From user Gareth on codegolf.stackexchange.com """ suffixes = {1: "st", 2: "nd", 3: "rd"} return str(n) + suffixes.get(n % 10 * (n % 100 not in [11, 12, 13]), "th")
def sphinx_lang(env, default_value='en'): """ Returns the language defined in the configuration file. @param env environment @param default_value default value @return language """ if hasattr(env, "settings"): settings = env.settings ...
def leastSignificant(sum, base): """Takes the sum and returns only the one's place of its value in the chosen base.""" return (sum % base)
def cleanup_functions(instructions): """Remove functions that are not called""" # This is an iterative processor. Once a function is removed, # there may be more unused functions while True: # find function calls live_functions = {} for instruction in instructions: ...
def until(p, f, a): """ until :: (a -> Bool) -> (a -> a) -> a -> a until(p, f, a) yields the result of applying f until p(a) holds. """ while not p(a): a = f(a) return a
def plugin_send(raw_data, stream_id): """ Empty translator """ data_sent = () new_position = 0 num_sent = 0 return data_sent, new_position, num_sent
def common_elem(start, stop, common, solution): """ Return the list of common elements between the sublists. Parameters: start -- integer stop -- integer common -- list of Decimal solution -- list of Decimal Return: sub -- list of Decimal """ sub = [elem for elem in common[start:stop] if elem in so...
def find(word, letter, start): """Modify find so that it has a third parameter, the index in word where it should start looking.""" if start > len(word): return -1 index = start while index < len(word): if word[index] == letter: return index index = index + 1 ret...
def _el_orb_tuple(string): """Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (`str`): The selected elements and orbitals in in the form: `"Sn.s.p,O"`. Returns: ...
def get_value_or_list(current_value, additional_value): """ Add a new value to another existing value/s. If a value doesn't exist it returns the new value otherwise returns a list with the existing value/s and the new value. :param current_value: the current value :param additional_value: the new va...