content
stringlengths
42
6.51k
def getTypedParameter(dictionary, name, expectedType, default=None): """ Get parameter from the specified dictionary while making sure it matches the expected type :param dictionary: dictionary :type dictionary: dict :param name: parameter name :type name: str :param expectedType: expec...
def isNull(text): """ Test if a string 'looks' like a null value. This is useful for querying the API against a null key. Args: text: Input text Returns: True if the text looks like a null value """ return str(text).strip().lower() in ['top', 'null', 'none', 'empty', 'fals...
def mean(num_list): """ Computes the mean of a list Parameters ------------- num_lists: list list to calculate mean of Returns ------------- mean: float Mean of list of numbers """ list_mean=sum(num_list)/len(num_list) return list_mean
def assert_relationship_error(pointer, errors): """Walk through the dictionary and determine if a specific relationship pointer exists """ pointer = '/data/relationships/{}/data'.format(pointer) for error in errors: if pointer == error['source']['pointer']: return True return...
def reduce_to_dict( arr, key_name, col_name_primary, col_name_secondary=None ): """returns dict with selected columns as key and value from list of dict Args: arr: list of dicts to reduce key_name: name of column to become key col_name_primary: colum will become value if it ...
def selectsort(alist: list) -> list: """ Not-inplace select sort. Destroys original list and returns new sorted list""" output = [] # Find minimum n times and add it to the new list for i in range(len(alist)): # Choose first list element as a minimum candidate amin = alist[0] aminidx = 0 # Iterate over li...
def usage(progname): """ print program usage """ print(("Usage: %s /path/to/tables " "/path/to/generated output[_amalgamation.cpp]") % progname) return 1
def build_response(data, num_total_results, qparams, func): """"Fills the `response` part with the correct format in `results`""" # LOG.debug('Calling f= %s', func) results = func(data, qparams) response = { 'id': '', 'setType': '', 'exists': bool(data), 'resultsCount':...
def is_num(l): """returns True if `l` is a number, False if not""" return type(l) in [float, int, int]
def pages(count, key="page"): """ Renders a pages block [<<] [1] [2] [3] [>>] :param count: Maximum of pages :param key: A key from the context to determine the current page. """ return { "class": "pages", "key": key, "count": count }
def parse_parametres(parametre_list: list) -> list: """Parse Nones in a parameter dict""" parametre_copy = [] for el in parametre_list: new_dict = {} for k, v in el.items(): new_dict[k] = [par if par != "None" else None for par in v] parametre_copy.append(new_dict) ...
def Get_FigWidth_Inches(FigSizeFormat="default"): """ This function gets the figure width in inches for different formats Args: FigSizeFormat: the figure size format according to journal for which the figure is intended values are geomorphology,ESURF, ESPL, EPSL, JGR, big de...
def urlstring(f, baseUrl) : """Forms a string with the full url from a filename and base url. Keyword arguments: f - filename baseUrl - address of the root of the website """ if f[0]=="." : u = f[1:] else : u = f if len(u) >= 11 and u[-11:] == "/index.html" : ...
def scale_100_to_10(value): """Convert a value from 0-100 range to 0-10 range. Args: value: an integer from 0 to 100. Returns: an integer from 0 to 10 """ value = int(value or 0) if value == 0: return 0 else: return max(1, min(10, int(value) / 10))
def pgcd(a, b): #http://python.jpvweb.com/mesrecettespython/doku.php?id=pgcd_ppcm """Retourne le pgcd de a et b. Version etendu du pgcd avec le 1er coef de bezout (pour inversion modulaire de a). >>> pgcd(35, 21) 7 >>> pgcd(2016, 1996) 4 """ r, u = a, 1 rp, up = b, 0 while rp !=...
def flatten(m: list): """Flatten nested lists into a single level of list""" flat = [] for item in m: if isinstance(item, list): flat += flatten(item) else: flat.append(item) return flat
def steps_to_run(current_step, steps_per_eval, steps_per_loop): """Calculates steps to run on device.""" if steps_per_loop <= 0: raise ValueError('steps_per_loop should be positive integer.') if steps_per_loop == 1: return steps_per_loop remainder_in_eval = current_step % steps_per_eval ...
def parse_float(n): """ Securely converts a non-numeric value to float. """ try: return float(n) except ValueError: return float("nan")
def _get_dir_sector_mid_pts(sector_idx): """Accepts a list of direction sector as strings and returns a list of mid points for that sector of type float """ sectors = [idx.split('-') for idx in sector_idx] sector_mid_pts = [] for sector in sectors: sector[0] = float(sector[0]) se...
def str_int(v): """Handle argparse inputs to that could be str or int :param v: value to convert :return: v as int if int(v) does not raise ValueError >>> str_int('test') test >>> str_int(1) 1 """ try: int_v = int(v) return int_v except ValueError: retur...
def Msub(M1, M2): """Matrix subtraction (elementwise)""" return [[a-b for a, b in zip(c, d)] for c, d in zip(M1, M2)]
def xor_decode(encoded_text): """ Decode xor encoded text """ import base64 #remove initial {xor} if it exists if encoded_text[0:5].lower() == '{xor}': encoded_text = encoded_text[5:] #Convert to bytes, and then pass to base64.decodebytes try: decoded_bytes = b...
def GetFile(file_name): """Handles opening the file. Args: file_name: the name of the file to get Returns: A file """ the_file = None try: the_file = open(file_name, 'rb') except IOError: the_file = None return the_file
def get_constr_label(name): """ Labels for pheno constraints. """ name = f"${name}$" label = name.replace("->", "\\to") label = label.replace("e e", "e^+ e^-") label = label.replace("mu mu", "\mu^+ \mu^-") label = label.replace(" pi0", " \pi^0") label = label.replace(" pi", " \pi") ...
def filterForXml(value): """ Replaces control characters with replace characters :param value: The value to filter :type value: ``unicode`` :return: The filtered value :rtype: ``unicode`` """ try: regex = filterForXml._regex except AttributeError: import...
def lower_bound(data, val, level=0): """multi fields list lower bound. for single field list use `bisect.bisect_left` instead """ left = 0 right = len(data) while left < right: mid = (left + right) // 2 if val <= data[mid][level]: right = mid else: ...
def capitalize_first_character(some_string: str) -> str: """Description: Capitalizes the first character of a string""" return " ".join("".join([w[0].upper(), w[1:].lower()]) for w in some_string.split())
def _CK_UTF8CHAR_to_str(data): """Convert CK_UTF8CHAR to string.""" return data.rstrip(b'\0').decode('utf-8').rstrip()
def make_album (artist_name, album_name, number_track = ''): """ Storing information about artist (name, album, nb of tracks optionnaly) """ album = { 'artist_name' : artist_name.title(), 'album_name' : album_name.title(), } if number_track: album['number_track'] = n...
def get_ros_type(type_string): """Parses the type_string to get package and type""" parts = type_string.split("/") if len(parts) != 2: raise Exception("Type lookup requires two parts, split by a slash: Package and type") package = parts[0] ros_type = parts[1] return (package, ros_type)
def unicode_dict(d): """Return a new dict where all the text has been decoded to unicode This is only for Python 2.""" return { k.decode('utf-8'): v.decode('utf-8') for k, v in d.items() }
def update_indexes(conversation): """ Re-assigns indexes after smoothening (mostly for clarity purposes) Doesn't really matter since we never index by specifically using the "index" field of the json obj. :param conversation: The dialogue between USER and ASSISTANT with inconsistent indic...
def nonmatching_lens(xsearch_output): """Examines xsearch_output (a dict of {xsearch_name : [lines]}) and returns a dict of xsearch instances with non-matching output line lengths ({xsearch_name: [non_matching_xsearch_names]}) """ nonmatching = {} xs = sorted(xsearch_output.keys()) whi...
def get_unsigned_short(data, index): """Return two bytes from data as an unsigned 16-bit value""" return (data[index+1] << 8) + data[index]
def get_structure_index(structure_pattern,stream_index): """ Translates the stream index into a sequence of structure indices identifying an item in a hierarchy whose structure is specified by the provided structure pattern. >>> get_structure_index('...',1) [1] >>> get_structure_index('.[.].',1) ...
def check_log_success(log_str): """ Check log success. """ if 'BatchMin: normal termination' in log_str: return True return False
def cypher_prop_string(value): """Convert property value to cypher string representation.""" if isinstance(value, bool): return str(value).lower() elif isinstance(value, str): return f"'{value}'" elif isinstance(value, int): return f"{value}" else: raise ValueError(f'Unsupported property type: {type(value)...
def non_faculty_editors(editors): """ Get a sublist of non-faculty editors. """ return [e for e in editors if e["role"] != "Faculty"]
def booleanp(v): """Return true iff 'v' is a boolean.""" return isinstance(v, bool)
def offset_by_one(x, sequence_length: int = 3): """ Generate a list of small sequences offset by 1. Usage: ```python >>> offset_by_one([1, 2, 3, 4, 5], sequence_length=3) [([1, 2, 3], [2, 3, 4])] ``` Args: x: Python list sequence_length: Chunk size Returns: "...
def neville(datax, datay, x): """ Finds an interpolated value using Neville's algorithm. Input datax: input x's in a list of size n datay: input y's in a list of size n x: the x value used for interpolation Output p[0]: the polynomial of degree n """ n = len(dat...
def json_underscore_fields(root): """Convert fields to underscore.""" if isinstance(root, dict): for field, value in root.items(): del root[field] root[field.replace("-", "_")] = json_underscore_fields(value) elif isinstance(root, list): for i in range(0, len(root)):...
def parseFloat(val): """Parse float from given string""" return float('0' + str(val))
def counter(countables): """ Counter for counting the values inside a particular list or dict. This is just a scratch/vanilla version of collections.Counter Args: countables: List of countables to be counted. """ counts = dict() for k in countables: if not k in list(counts.keys(...
def _floatable(item): """Check if an item can be intepreted with float()""" try: float(item) return True except ValueError: return False
def is_valid_pid(passport_id): """Checks for valid Passport ID.""" if passport_id.isdigit() and len(passport_id) == 9: return True else: return False
def make_name(key): """Return a string suitable for use as a python identifer from an environment key.""" return key.replace('PLATFORM_', '').lower()
def clean_web_text(text): """Some rules used to clean web text.""" text = text.replace("<br />", " ") text = text.replace("&quot;", "\"") text = text.replace("<p>", " ") if "<a href=" in text: while "<a href=" in text: start_pos = text.find("<a href=") end_pos = text.find(">", start_pos) ...
def top_games(network): """Get the top 5 most liked games among users in the network. Keyword arguments: network -- a dictionary containing users' connections and games """ top_games, games = [], [] for user in network: for game in network[user]['games']: games.append(game) ...
def get_all_rules(data): """ Create list of rules from data in format: (color1, num, color2) '<color1> bags contain <num> <color2> bags' """ rules = [] for record in data: count = record.count(",") record = record.split() bag_from = record[0] + " " + record[1] ...
def calc_poissons_ratio(mod_bulk, mod_shear): """Compute the shear modulus from the bulk modulus and Poisson's ratioself. See https://en.wikipedia.org/wiki/Bulk_modulus#Further_reading Parameters ---------- mod_bulk : `array_like` or float bulk modulus (kPa) other units okay too mod_sh...
def convert_midi_to_pitchbend(midi): """ Will convert 0-127 to -8192 - 8191. """ if(midi >= 63): return int( (8191/63)*(midi-64) ) else: return int( (8192/64)*(64-midi) ) * -1
def array_chunk(array, size): """ Given an array and chunk size, divide the array into many subarrays, where each subarray is of length size. array_chunk([1,2,3,4], 2) --> [[1,2], [3,4]] array_chunk([1,2,3,4,5], 2) --> [[1,2], [3,4], [5]] """ counter = 0 outer_list = [] inner_lis...
def get_matches(known_values, new_values): """ Compare two lists, counts and returns the elements matching provided known values """ matched_elements = [] match_count = 0 print("\n[*] Checking for matches to provided list of known values") # TO DO for k_value in known_values: for n_ite...
def low_ordinal(n): """ For n<10, returns correct ordinal 1st, 2nd, ... ; otherwise, returns nth. >>> [low_ordinal(n) for n in range(5)] ['0th', '1st', '2nd', '3rd', '4th'] >>> low_ordinal(21) '21th' """ first_three = {1: '1st', 2: '2nd', 3: '3rd'} return first_three.get(n, '{0}th'....
def twoStrings(s1, s2): """ O(?) Difference s2-s1: O(len(s2)) """ my_set_1 = set(s1) my_set_2 = set(s2) my_sub_set = my_set_2 - my_set_1 return 'NO' if my_sub_set == my_set_2 else 'YES'
def noun_to_verb(sentence: str, index: int) -> str: """ A function takes a `sentence` using the vocabulary word, and the `index` of the word once that sentence is split apart. The function should return the extracted adjective as a verb. Args: sentence (str): str that uses the word in ...
def get_matching_tags_from_result(result, tag_key): """ :type result: dict :param result: The python dict form of one value as returned in the result content :type tag_key_list: list :param tag_key_ist: This is a list of indexes of the tags that we're interested in :type tag_value_list: list ...
def Jaccard(x,y): """returns the jaccard similarity between two lists """ intersection_cardinality = len(set.intersection(*[set(x), set(y)])) union_cardinality = len(set.union(*[set(x), set(y)])) return intersection_cardinality/float(union_cardinality)
def get_source(obj): """Get object's source code. Returns None when source can't be found. """ from inspect import findsource try: lines, lnum = findsource(obj) except (IOError, TypeError): return None return lines, lnum
def get_quality(line): """Determine signal quality from string""" try: # print("line " + line) # print("sig split" + line.split("Signal level=")[0]) # print("lq split" + line.split("Signal level=") # [0].split("Link Quality=")[1]) if line == "": return ...
def sign(value): """ Returns the sign of the inputted 'value'; i.e. 5 = 1, -9.1 = -1, 0 = 0 """ if value > 0: return 1 elif value < 0: return -1 else: return 0
def calculate_percent(numerator, denominator): """Return percentage value, round to 2 digits precision. Parameters: numerator (int): parts of the whole denominator (str): the whole Returns: float: percentage value rounded (00.00) """ percent = (numerator / denominator) * 10...
def value_to_bits(v, bits): """ Convert a value to a list of booleans """ b = [] for i in range(bits): b.append(bool((1 << i) & v)) return b
def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if "time" in str(type(obj)): return obj.isoformat() return str(obj)
def _cleanse(text): """Lowercase a string and remove punctuation and whitespace """ return ''.join([character for character in text if character.isalnum()]).lower()
def is_tool(name): """ Check if name `name` is on PATH and marked as executable. Parameters: ----------- name : str file/app/execution file Returns: ------- rue/False """ from shutil import which return which(name) is not None
def day_sessions(day): """returns (seconds, ticks) for a day""" seconds = 0 ticks = 0 sessions = day.get("org.mozilla.appSessions.previous", None) if sessions: seconds += sum(sessions.get("cleanTotalTime", [])) seconds += sum(sessions.get("abortedTotalTime", [])) ticks += sum...
def most_common(items): """Wanted functionality from Counters (new in Python 2.7) """ counts = {} for i in items: counts.setdefault(i, 0) counts[i] += 1 return sorted(counts.items(), key=lambda x: x[1])[-1]
def _get_current_engagement(d, assignment): """ helper for WTAP solver Calculates the current engagement :param d: device :param assignment: class Graph. :return: """ if d in assignment: for d, t, v in assignment.edges(from_node=d): return t return None
def mrr(ranks): """ Calculate mean reciprocal rank Function taken from: https://github.com/google/retrieval-qa-eval/blob/master/squad_eval.py :type ranks: list :param ranks: predicted ranks of the correct responses :return: float value containing the MRR """ return sum([1/v for v in r...
def get_list_of_block_numbers(item): """ Creates a list of block numbers of the given list/single event""" if isinstance(item, list): return [element['blockNumber'] for element in item] if isinstance(item, dict): block_number = item['blockNumber'] return [block_number] return l...
def merge(left, right): """ Merges two arrays in non-decreasing order. @type left: array @param left: one of the arrays to merge @type right: array @param right: the other array to merge @rtype: array @return: the merged array """ # Initialize merged array merged = [] ...
def childIdx(idx): """ >>> childIdx(0) (1, 2) >>> childIdx(1) (3, 4) >>> childIdx(2) (5, 6) """ base = idx * 2 return (base + 1, base + 2)
def is_subclass(obj, superclass): """Safely check if obj is a subclass of superclass.""" try: return issubclass(obj, superclass) except Exception: return False
def _zero_both_closed(x, y, c=None, l=None): """convert coordinates to zero-based, both strand, open/closed coordinates. Parameters are from, to, is_positive_strand, length of contig. """ return x, y + 1
def _is_sequence(obj): """Check if the object is a sequence (list, tuple etc.). :param object obj: an object to be checked :return: True if the object is iterable but is not a string, False otherwise :rtype: bool """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
def divide_separate_words(X): """ As part of processing, some words obviously need to be separated. :param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> divide_separate_words([['ita vero'], ['quid', 'est', 'veritas']]) [['ita', 'vero'], ['q...
def _q_stop(query_seq, q_seq): """ returns the ending python string index of query alignment (q_seq) in the query sequence (query_seq) :param query_seq: string :param q_seq: string :return: integer """ q_seq = q_seq.replace("-", "") q_start = query_seq.find(q_seq) q_stop = q_start ...
def sheight(s): """ Return the height of provided text block. Min height is one. """ return s.strip().count("\n") + 1
def del_from_dict(dictionary, srcip, dstip): """Removes an entry from the given dictionary. Assumed is that srcip and dstip exist in the dictionary. :param dictionary: dictionary to remove an entry from :type dictionary: dictionary :param srcip: source ip :type srcip: string :param dstip: destination ip ...
def pack_quotes(quotes, **kwargs): """ :param quotes: a list of BeautifulSoup tags containing quotes, and quote details :return: a dictionary of packaged quotes """ packed_quotes = {} for group in quotes: raw = group.select_one(kwargs.get('quotetag')) raw_quote = raw.string ...
def daysToSeconds(days = 1): """ Input number of days to backdate search Returns number of seconds Integers only, please Ex: daysToSeconds(days = 5) daysToSeconds(5) """ return 'f_TPR=r' + str(int(days) * 24 * 60 * 60)
def remove_cover_attachment_previews(cover_attachment): """ Remove the previews element from cover_attachment. It contains a lot of data. Then, return. """ del cover_attachment["previews"] return cover_attachment
def validate_linkedin(url): """Return the linkedin username from the url or the link""" if 'view?id' not in url: nick = url.rsplit('/', 1)[-1] return nick return url
def compName(n1, n2): """ Compare names: n1 n2 strings, blankspace separated names return value between -1 (mismatch) and 1 (match) return None if any of n1, n2 is empty can be used on names, normalised names """ if (not n1) or (not n2): return None nn1 = n1.strip().split() n...
def choose_dimensions(valid_dims, overrides={}): """For each dimension, choose a single valid option (except for 'time', where we use the wildcard '*' to get the whole time-series.) If not specified, choose the first valid option for each dimension. Parameters ---------- valid_dims : dict ...
def sum_ints_list(tokens): """ parse action to sum integers in a VBA expression with operator '+' """ # extract argument from the tokens: # expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...] integers = tokens[0][::2] return sum(integers)
def euclid(s,t,buffer): """ Returns s and t after recursion """ if (len(buffer) == 0): return s,t else: t1 = s + t * buffer[len(buffer)-1] del buffer[len(buffer)-1] return euclid(t, t1, buffer)
def ccdid_qid_to_rcid(ccdid, qid): """ """ return 4*(ccdid - 1) + qid - 1
def binary_search(input_array, value): """Your code goes here.""" index = int(len(input_array) / 2) range = index steps = 0 while steps < len(input_array) and value != input_array[index]: steps += 1 range = int(range / 2) if range < 1: range = 1 if value >...
def expand_noderange(value): """Expand a given node range like: '1-10,17,19'""" ranges = value.split(',') nodes = [] for r in ranges: if '-' in r: start, end = r.split('-') nodes += [str(i) for i in range(int(start), int(end) + 1)] else: nodes.append(r...
def zip_tasks_verbose_output(table, stdstreams): """Zip a list of strings (table) with a list of lists (stdstreams) :param table: a formatted list of tasks :param stdstreams: for each task, a list of lines from stdout/stderr tail """ if len(table) != len(stdstreams): raise ValueError('Can on...
def gcd(a, b): """Returns the greatest common divisor of a and b. Should be implemented using recursion. >>> gcd(34, 19) 1 >>> gcd(39, 91) 13 >>> gcd(20, 30) 10 >>> gcd(40, 40) 40 """ "*** YOUR CODE HERE ***" if a < b: return gcd(b, a) if a % b == 0: ...
def create_constraint_clause(label: str, node: str = 'node') -> str: """ Returns the *part* of a statement that creates a constraint. Parameters ---------- label : str The label (node type) on which to create the index node : str, optional Name of the node when referred in another statement Returns ------...
def derive_http_method(method, data): """Derives the HTTP method from Data, etc :param method: Method to check :type method: `str` :param data: Data to check :type data: `str` :return: Method found :rtype: `str` """ d_method = method # Method not provided: Determine method from ...
def ConvertNativeLibs(args): """Converts the --native_libs command line argument to an arch -> libs map.""" native_libs = {} if args is not None: for native_lib in args: abi, path = native_lib.split(":") if abi not in native_libs: native_libs[abi] = set() native_libs[abi].add(path) ...
def HasMetrics(line): """ The metrics files produced by aomenc are started with a B for headers. """ # If the first char of the first word on the line is a digit if len(line) == 0: return False if len(line.split()) == 0: return False if line.split()[0][0:1].isdigit(): return True return Fals...
def extract_properties_by_schema(group_objects_list, group_gid_number_attr, group_name_attr): """ Safeguard Authentication Services is designed to support any Active Directory schema configuration. If your Active Directory schema has built-in support for Unix attributes (Windows 2003 R2 schema, SFU sche...
def is_ebay_evtn(address_fragment): """Test if the address fragment provided is an eBay VTN.""" return address_fragment.startswith('ebay') and len(address_fragment) == 11