content
stringlengths
42
6.51k
def _list_to_index_dict(lst): """Create dictionary mapping list items to their indices in the list.""" return {item: n for n, item in enumerate(lst)}
def update_position(length, pos): """Increments actual cursor position in salt or seed""" return 0 if pos + 1 == length else pos + 1
def first(func, items): """Return the first item in the list for what func returns True""" for item in items: if func(item): return item
def as_int(raw): """Return an int for the given raw value. Return None for "falsey", non-zero values. """ if raw == 0: return 0 elif not raw: return None else: return int(raw)
def factorial(n): """ factorial :param n: :return: """ return 1 if n < 2 else n * factorial(n-1)
def find_largest_digit(n): """ :param n: int, the number send to be processed :return: int, the maximum digit of a number """ # calculate Big O # global x # x += 1 n = abs(n) # get the remainder of n/10 num = n % 10 # Only one digit left if int(n/10) == 0: return n # two digits left else: return ma...
def filter_dict(dict, keywords): """ Returns only keywords that are present in a dictionary """ return [key for key in keywords if key in dict]
def filter_images_with_like(images, user_id): """Takes a list of pictures and removes the ones which do not have likes from user identified by `user_id`, returning a new filtered list """ filtered = [] for image in images: if 'likes' not in image: continue if user_id in...
def _subs(expr, X, X_subs): """helper function for multiple substitutions expr is the expression whose variables are to be substituted X is a list or Matrix with the regarded variables in order X_subs are the new values in order """ i = 0 while i < len(X): expr = expr.subs(X[i], X_su...
def get_best_response_actions_as_string(best_response_actions): """Turns a dict<bytes, int> into a bytestring compatible with C++. i.e. the bytestring can be copy-pasted as the brace initialization for a {std::unordered_,std::,absl::flat_hash_}map<std::string, int>. Args: best_response_actions: A dict map...
def find_substring_occurences(xs, item): """Can be used to get the indexes of the required substring within a list of strings. >>> find_substring_occurences(['ab', 'bcd', 'de'], 'd') [1, 2] """ idxs = [i for (i, x) in enumerate(xs) if item in x] return idxs
def DecimalDegrees(degrees, minutes, seconds): """Convert DMS to decimal degrees input: 33 8' 59.53" (33, 8, 59.53) output: 33.149869444444441 Args: degrees: int minutes: int seconds: float Returns: decimal_degrees: float """ minutes = minutes + seconds/60. decimal = minutes/60. ...
def _ApplyTestFilter(testfilter, bot_spec): """Applies testfilter from CLI. Specifying a testfilter strips off any builder-specified tests (except for compile). """ if testfilter: return [(botname, set(testfilter) | (tests & set(['compile']))) for botname, tests in bot_spec] else: retur...
def _make_ts_label(raw_data, tsid, dimensions): """ Make a label for a timeseries data point returned from SignalFX :param raw_data: a processed data stream from SFX :param tsid: the timeseries ID for a datapoint in the SFX stream :param dimensions: a list of dimensions to create the label from :re...
def secant(x1, x2, f, steptol=1e-12, roottol=1e-12, maxIter=30, callback=None): """ Find an approximation to a point xf such that f(xf)=0 for a scalar function f using the secant method. The method requires two initial points x1 and x2, ideally close to a root, and proceeds iteratively. Param...
def split_script(pk_op): """ Gievn hex encoded string, return list of op_codes and data to push to stack """ # Define the OP_CODES dict OP_CODES = {172: "OP_CHECKSIG", 118: "OP_DUP", 169: "OP_HASH160", 136: "OP_EQUALVERIFY"} # Create list to s...
def is_list_of_strings(li: list) -> bool: """Return true if input is a list of strings.""" return all(isinstance(elem, str) for elem in li)
def get_remaining(data_keys1, data_keys2, new_mappings, asserting=True, printing=True): """ Prints stats and returns keys of both snapshots to be matched """ remaining_keys1 = set(data_keys1) - set(new_mappings.keys()) remaining_keys2 = set(data_keys2) - set(new_mappings.values()) if asserting: ...
def TSA_h_g( temperature_ground, temperature_vegetation, temperature_air, roughness_ground, roughness_vegetation, roughness_air ): """ Chen et al., 2005. IJRS 26(8):1755-1762. Estimation of daily evapotranspiration using a two-layer remote sensing model. Sensible heat flux for ground TSA_h_g( temperature_ground, t...
def real_accept_prob(real_acpt_cnt, real_reqs_cnt, acpt_cnt, reqs_cnt, phi): """ real_acpt_cnt: # user j's acceptances of friend requests from users with known 'real' labels real_reqs_cnt: # all 'real' friend requests that known users sent to user j acpt_cnt: # user j's accept of friend requests req...
def _cum_aggregate_apply(aggregate, x, y): """ Apply aggregation function within a cumulative aggregation Parameters ---------- aggregate: function (a, a) -> a The aggregation function, like add, which is used to and subsequent results x: y: """ if y is None: ret...
def menu_option_names_to_titles(menu_option_infos): """Build a dictionary mapping menu option names to titles.""" return dict((menu_option_info[0], menu_option_info[1]) for menu_option_info in menu_option_infos)
def base_domain_name_guesses(domain): """Return a list of progressively less-specific domain names. One of these will probably be the domain name known to the DNS provider. :Example: >>> base_domain_name_guesses('foo.bar.baz.example.com') ['foo.bar.baz.example.com', 'bar.baz.example.com', 'baz.ex...
def getnodetext(node): """returns the node's text by iterating through the child nodes""" if node is None: return "" return "".join([t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE])
def get_bp_content(input_sequence): """Method that takes an input_sequence string and returns a dictionary of normalized bp content""" total_nts = len(input_sequence) bp_content = {} for nt in input_sequence: if nt not in bp_content: bp_content[nt] = 1. else: bp_c...
def filter_event(event, happening_before): """Check if the following keys are present. These keys only show up when using the API. If fetching from the iCal, JSON, or RSS feeds it will just compare the dates """ status = True visibility = True actions = True if 'status' in event: ...
def encode(command): """ Takes a command as list and returns a string. """ def needs_quote(word): """ Returns true if arguments needs to be protected by quotes. Previous implementation was shlex.split method, but that's not good for this job. Currently is running through the string wit...
def pick_wm_1(probability_maps): """ Returns the gray matter probability map from the list of segmented probability maps Parameters ---------- probability_maps : list (string) List of Probability Maps Returns ------- file : string Path to segment_prob_1.nii.gz is ret...
def multVectors(vector1, vector2): """ Multiplies two vectors and returns the result as a new vector. :param vector1: List :param vector2: List :return: vector """ new_vector = [] for i in range(len(vector1)): new_vector.append(vector1[i] * vector2[i]) return new_vector
def S_proximity_data(_data_list, _percent_similarity=0.95): """ Calculates average of smallest distances between data points when samples are translated to positive values percent similarity parameter is used for determining closeness between data points. Returns smallest distances along X and Y axes ...
def is_equation(text): """test if a piece of text is a latex equation, by how it is wrapped""" text = text.strip() if any( [ text.startswith("\\begin{{{0}}}".format(env)) and text.endswith("\\end{{{0}}}".format(env)) for env in [ "equation", ...
def name_val_table(text, dtype=float): """ designed to parse optVariables text block e.g. '''uu_0 1.0770e+00 1 1 ON 0 uu_1 6.7940e-01 1 1 ON 1 uu_2 4.3156e-01 1 1 ON 2 ud_0 1.6913e+00 1 1 ON 5 ud_1 1.0443e+00 1 1 ON 6 ud_2 6.1912e-01 1 1 ON 7 ''' return variable-value map, only the first two columns are pa...
def is_zipfile(path): """ Check if a file is a zip file """ if path.endswith(".zip"): return True return False
def strip_list(items): """ Strip each element of the array """ return [x.strip() for x in items]
def format_trec_results(qid: str, doc: str, rank: int, score: float, run_id='RunId'): """ Produce a TREC formatted str of results. :param qid: Query Id :param doc: Document :param rank: Rank position :param score: Ranking score :param run_id: Name for this run :return String in TREC form...
def _generate_end_sequence(leds: int) -> bytes: """ Generate a byte sequence, that, when sent to the APA102 leds, ends a led update message. :param leds: number of chained LEDs. :return: terminating byte sequence. """ edges_required = ((leds - 1) if leds else 0) bytes_required = 0 o...
def tostr( data ): """Converts a string or byte array to a string. """ if isinstance( data, str ): return data else: return ''.join( map( chr, data ) )
def mean_representation(distribute): """Computes representation vector for input images.""" mean, std = distribute return mean
def bash_quote(*args): """Quote the arguments appropriately so that bash will understand each argument as a single word. """ def quote_word(word): for c in word: if not (c.isalpha() or c.isdigit() or c in '@%_-+=:,./'): break else: if not word: ...
def gnu_hash(s): """gnu_hash(str) -> int Function used to generated GNU-style hashes for strings. """ h = 5381 for c in s: h = h * 33 + ord(c) return h & 0xffffffff
def minWindow(s, t): """ :type s: str :type t: str :rtype: str """ substring_list = [] list_t = list(t) list_s = list(s) temp_length = float('inf') temp_list = [] for i in range(len(list_s)): for j in range(len(substring_list)): substring_li...
def split(my_path, pdb_file): """Split the given PDB file into models, each model becomes a separate PDB file placed in the "temp" folder""" try: my_pdb = open(pdb_file) except FileNotFoundError: print("ERROR -> the uploaded PDB file was not found") raise SystemExit except...
def get_title_to_id_dict(titles): """Creates a dict mapping each title with an id. :param titles: list of titles :type titles: list :return: dict mapping a title to an id. :rtype: dict """ title_to_id = {title: i for i, title in enumerate(titles)} return title_to_id
def remap_vals(vals, val_map): """Return a list with vals in val_map remapped.""" return [val_map.get(val.lower(), val) for val in vals]
def transcribe(DNA): """This command takes a seq as a string and returns its transcription.""" DNA = DNA.upper() for i in DNA: if i not in 'AGCT': return 'Invalid Seq' return DNA.replace('T', 'U')
def opt_mod(num, div): """returns nonnegative or negative modulo residue depending on whichever one has a lower absolute value (if both equal, returns nonnegative)""" res = num % div return res if res <= (div/2) else res-div
def app_labels(apps_list): """ Returns a list of app labels of the given apps_list """ return [app.split('.')[-1] for app in apps_list]
def get_rel_part(poly): """Returns a part of a polynomial which contains relative errors only (no absolute errors)""" result = [m.copy() for m in poly if not m.abs_errs and m.rel_errs] return result
def gen_urdf_material(color_rgba): """ :param color_rgba: Four element sequence (0 to 1) encoding an rgba colour tuple, ``seq(float)`` :returns: urdf element sequence for an anonymous material definition containing just a color element, ``str`` """ return '<material name=""><color rgba="{0} {1} {2} ...
def sortDict(dictionary: dict): """Lambdas made some cringe and stupid thing some times, so this dirty thing was developed""" sortedDictionary = {} keys = list(dictionary.keys()) keys.sort() for key in keys: sortedDictionary[key] = dictionary[key] return sortedDictionary
def parse_out_keys_arg(out_feat_keys, all_feat_names): """ Checks if all out_feature_keys are mapped to a layer in the model. Ensures no duplicate features are requested. Returns the last layer to forward pass through for efficiency. Adapted from (https://github.com/gidariss/FeatureLearningRotNet) ...
def get_output_path(file_path): """ Helper Function That Returns Output Filepath At The Same Location Of Source With Changed Extension """ output_path = file_path.split(".") output_path[-1] = ".azw3" return "".join(output_path)
def _writefile(mylist, filename): """ Export in a file the list. mylist could be a list of list. Example ------- >>> L = [[2,3],[4,5]] >>> pykov.writefile(L,'tmp') >>> l = [1,2] >>> pykov.writefile(l,'tmp') """ try: L = [[str(i) for i in line] for line in mylist] ...
def get_best_of_n_avg(seq, n=3): """compute the average of first n numbers in the list ``seq`` sorted in ascending order """ return sum(sorted(seq)[:n])/n
def tceConverter(tce): """Convert <-xx> style TCE designation to <TCE_x> format""" tce_dict = { "01": "TCE_1", "02": "TCE_2", "03": "TCE_3", "04": "TCE_4", "05": "TCE_5", "06": "TCE_6", "07": "TCE_7", "08": "TCE_8", "09": "TCE_9", ...
def upper_first(text): """Converts the first character of string to upper case. Args: text (str): String passed in by the user. Returns: str: String in which the first character is converted to upper case. Example: >>> upper_first('fred') 'Fred' >>> upper_firs...
def fdtfile2fieldstring(fdtfile): """Make a string of field definitions separated by % (percent sign) reading from a fdtfile or just take the string and bring into shape: e.g. 1,AA,20,A,NC,NN%1,F4,4,F,NU,DT=E(UNIXTIME) :param fdtfile: fdtfile or field string :return: tuple (number of fields...
def effective_net_values(net_values): """ Args: net_values: net values of fund as a list return: effective net values of fund as a list """ # sort by date net_values.reverse() effective_net_values_list = [] effective_signal = 0 # Filter effective net values for i in rang...
def _markdown_list(items): """Transform a list of items into a markdown list.""" return "\n".join(["- {}".format(x) for x in items])
def _splitlist(s): """Given a string of the form [item item item], return a list of strings, one per item. WARNING: does not yet work right when an item has spaces. I believe in that case we'll be given a string like '[item1 "item2 with spaces" item3]'. """ if s[0] != '[' or s[-1] != ']': r...
def binary_search(l, n, t): """ :param l: list of sorted integer :param n: the length of the list l :param t: the target number want to find """ i = 0 r = n - 1 while i <= r: mid = (r + i) / 2 if l[mid] == t: return mid elif l[mid] > t: r =...
def dict_list_to_table(headings, dict_list): """ Converts dict to table-style list of rows with heading: Example: dict_list_to_table(('a', 'b', 'c'), [{'a': 1, 'b': 2, 'c': 3}, {'a': 11, 'b': 12, 'c': 13}]) results in the following (dict keys reordered for better readability): [ ...
def count_overlaps(vents): """ Count overlaping vents. :param vents: dictionary of vents :return: number of overlaping vents """ counter = 0 for n_vents in vents.values(): if n_vents > 1: counter += 1 return counter
def frepr(var, ffmt="%.16e"): """Similar to Python's repr(), but return floats formated with `ffmt` if `var` is a float. If `var` is a string, e.g. 'lala', it returns 'lala' not "'lala'" as Python's repr() does. Parameters ---------- var : almost anything (str, None, int, float) ffmt :...
def is_simple_requires(requires): """ Return True if ``requires`` is a sequence of strings. """ return ( requires and isinstance(requires, list) and all(isinstance(i, str) for i in requires) )
def score_blocks(block, debug=False): """Return status score.""" score = 0 SCORE_PER_BLOCK = 10 SCORE_PER_NOT_EQUAL = 1 for i in range(4): for j in range(4): if block[i][j] != 0: score += SCORE_PER_BLOCK else: continue if i...
def event_dict(ts_epoch): """An event represented as a dictionary.""" return { 'name': 'REQUEST_CREATED', 'error': False, 'payload': {'id': '58542eb571afd47ead90d25e'}, 'metadata': {'extra': 'info'}, 'timestamp': ts_epoch }
def _truncate_string_right(strg, maxlen): """ Helper function which truncates the right hand side of a string to the given length and adds a continuation characters, "...". """ if len(strg) > maxlen: rhs = maxlen - 4 return "%s ..." % strg[:rhs] else: re...
def get_right(sprites): """ :return: which sprite to use. """ return sprites["block"][0]
def get_difference(a, b): """ Get the difference between `a` and `b` preserving the order of elements in `a` """ if type(a) == str: a = a.split() if type(b) == str: b = b.split() diff = [] for word in a: if word not in b: diff.append(word) return diff
def check_header(header): """ Funzione per il controllo della riga d'intestazione del file csv """ count, valid_head = 0, set(["IPV4_SRC_ADDR", "IPV4_DST_ADDR"]) for head in header.split('|'): if head in valid_head: count += 1 if count == len(valid_head): ...
def MAM(a, b): """ Multiply, Add, Modulo """ return (17 * a + b) % (2**16)
def human_list(l): """Return a human-friendly version of a list. Currently seperates list items with commas, but could be extended to insert 'and'/'or' correctly. Args: l (list): The list to be made human-friendly. Returns: str: The human-friendly represention of the list. """ ...
def is_valid_service_exploit(e): """ Check whether service exploit is valid """ if type(e) != list or len(e) != 2: return False if type(e[0]) != float or (type(e[1]) != float and type(e[1]) != int): return False if e[0] < 0 or e[0] > 1 or e[1] < 0: return False return...
def remove_warning_label(msg): """ Standardize errors by removing obsolete "WARNING:" part in all languages """ if ':' in msg: return msg.split(':')[1].strip() return msg
def get_headers(token): """ Default to be used for GET/POST :param token: Artifactory API token :return: HTTP headers """ headers = {"Accept": "application/json", "Content-Type": "application/json"} if token: headers["Authorization"] = f"Bearer {token}" return headers
def is_strict_subclass (value, klass): """Check that `value` is a subclass of `klass` but that it is not actually `klass`. Unlike issubclass(), does not raise an exception if `value` is not a type. """ return (isinstance (value, type) and issubclass (value, klass) and value ...
def duration_from_seconds(s): """Module to get the convert Seconds to a time like format.""" s = s m, s = divmod(s, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) timelapsed = "{:01d}:{:02d}:{:02d}:{:02d}".format(int(d), int(h), ...
def is_pangram(s): """ (str) -> bool Return True if s is a pangram, False otherwise. """ alphabet = set('abcdefghijklmnopqrstuvwxyz') return alphabet <= set(s.lower())
def coerce_to_int(obj): """ Coerce a constant VBA object (integer, Null, etc) to a int. :param obj: VBA object :return: int """ # in VBA, Null/None is equivalent to 0 if ((obj is None) or (obj == "NULL")): return 0 else: return int(obj)
def dict_to_list(d): """Convert a dict whose keys are the ints 0..N-1 into a list of length N such that l[x] == d[x]. In the process, check that the keys are indeed such a range. """ l = [None]*len(d) try: for k, v in d.items(): l[k] = v except IndexError: raise...
def assert_greater(a, b): """ Wrapper to enable assertions in lambdas """ assert a > b return True
def to_rule(palette, group, background, foreground, term): """Returns a tuple containing the a highlight function call and its arguments.""" return ( "hi", group, "ctermbg={}".format(palette.get(background, background)), "ctermfg={}".format(palette.get(foreground, foreground)), ...
def _is_shipping_device(obj): """True if device is used as a shipping tracker""" if obj and obj.sg: return ('shipping' in obj.sg.slug.split('-')) or ('saver' in obj.sg.slug.split('-')) return False
def detailed_segment_results_to_list(detailed_segment_results): """ Converting detailed segment results to a list (position of each item is fixed). Can be used with normed values as well. Argument: detailed_segment_results (dictionary): as provided by the 3rd or 4th item in the results of eval_segments...
def border_style(keyword): """``border-*-style`` properties validation.""" return keyword in ('none', 'hidden', 'dotted', 'dashed', 'double', 'inset', 'outset', 'groove', 'ridge', 'solid')
def setup_googletest(env, shards, index): """Sets googletest specific environment variables.""" if shards > 1: assert not any(i['key'] == 'GTEST_SHARD_INDEX' for i in env), env assert not any(i['key'] == 'GTEST_TOTAL_SHARDS' for i in env), env env = env[:] env.append({'key': 'GTEST_SHARD_INDEX', 'va...
def weekday(day: str) -> bool: """ Checks if a string is the name of a weekday in the supported languages. :param day: Any string, ideally one that actually represents a day :return: True if it is a weekday. """ day = day.lower() if day[-1] in "ghy": return day[0] != "s" elif day...
def parse_pair(pair): """Parse pair from string to list with two elements.""" return [int(element) if element.isdigit() else element for element in pair.split('/')]
def next_collatz_seq(current_number): """Returns the next collatz sequence number after current_number""" next_number = 0 if current_number == 1: next_number = 0 elif current_number % 2 == 0: next_number = current_number / 2 else: next_number = (current_number * 3) + 1 r...
def flat_user_answer(user_answer): """ Convert nested `user_answer` to flat format. {'up': {'first': {'p': 'p_l'}}} to {'up': 'p_l[p][first]'} """ def parse_user_answer(answer): key = list(answer.keys())[0] value = list(answer.values())[0] if isinstanc...
def power(x, n): """Compute the value x**n for integer n.""" if n == 0: return 1 else: return x * power(x, n-1)
def _scoring_helper(scoring): """ Take a scoring system (either 'ppr', 'half', 'std') and return the correct FFC URL fragment. Note: helper functions are often prefixed with _, but it's not required. """ if scoring == 'ppr': return '/ppr' elif scoring == 'half': return '/hal...
def naive_max_perm(M, A=None): """ >>> M = [2, 2, 0, 5, 3, 5, 7, 4] >>> print(naive_max_perm(M)) {0, 2, 5} """ if A is None: A = set(range(len(M))) if len(A) == 1: return A B = {M[i] for i in A} C = A - B if C: A.remove(C.pop()) return naive_max_p...
def as_hms(value): """Given a floating-point number of seconds, translates it to an HH:MM:SS string.""" long_seconds = int(value) (long_minutes, seconds) = divmod(long_seconds, 60) (hours, minutes) = divmod(long_minutes, 60) return "%d:%02d:%02d" % (hours, minutes, seconds)
def calcularDiferencias(lista): """ por la descripcion del ejercicio, lo mas logico parece ordenar primero la lista """ adaptadores = sorted(lista) adaptadores.append(adaptadores[len(adaptadores)-1]+3) contadorDiferencias = dict() i=0 while i < len(adaptadores)-1: diferencia = ad...
def fmt_bytes(bytes: int) -> str: """ Prints out a human readable bytes amount for a given number of bytes """ if bytes > 1000000000: return '{:.2f} GB'.format(bytes / 1000000000) if bytes > 1000000: return '{:.2f} MB'.format(bytes / 1000000) if bytes > 1000: return '{:.2...
def range_overlap( left_range: range, right_range: range, ) -> bool: """ Checks if two ranges have an overlap. Here each range is assumed to be consecutive, i.e., `step` field of `range` is always 1. Parameters ---------- left_range right_range Returns ------- True or F...
def get_area_average(arr, start_row, start_col, width, height): """ Return average value of area. Sizes of area are in cell_size :param arr: array :param start_row: int :param start_col: int :param width: int :param height: int :return: float >>> get_area_average([[[100, 100, 100],...
def factorial_v2(num): """ (int) -> float Computes num! Returns the factorial of <num> """ if isinstance(num, int) and num >= 0: product = 1 # Init if num == 0: return product for a_num in range(num, 0, -1): product *= a_num return...