content
stringlengths
42
6.51k
def find_1d_data(hash_table, buf): """ THIS HAS NOT BEEN TESTED DUE TO NO FILES WITH 1D DATA AVAILABLE.""" item = hash_table.pop("/MetaData/MeasurementSettings/SamplesToLog", None) if item is None: return None else: raise NotImplementedError
def point_in_rectangle(px, py, rectangle): """ Check if a point is included into a regular rectangle that aligned with the x-y axis :param px: x value of the point :param py: y value of the point :param rectangle: the coordinates of the 4 corners of the rectangle :return: True or False depending...
def is_error(value): """ Checks if `value` is an ``Exception``. Args: value (mixed): Value to check. Returns: bool: Whether `value` is an exception. Example: >>> is_error(Exception()) True >>> is_error(Exception) False >>> is_error(None) ...
def fib(x): """ assumes x an int >= 0 returns Fibonacci of x """ if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2)
def array_to_grader(array, epsilon=1e-4): """Utility function to help preparing Coursera grading conditions descriptions. Args: array: iterable of numbers, the correct answers epslion: the generated expression will accept the answers with this absolute difference with provided values ...
def calcDivisor(factors): """ Return the number from its prime factors. Args: factors: Dictionary of prime factors (keys) and their exponents (values). Returns: An integer. The number made of the prime factors. Usage: >>> calcDivisor({5: 3, 7: 2}) 6125 >>> calcDivisor({2: 3, 5: ...
def _is_dictionary_with_tuple_keys(candidate): """Infer whether the argument is a dictionary with tuple keys.""" return isinstance(candidate, dict) and all( isinstance(key, tuple) for key in candidate )
def getFileNameOnly(fileName): """ return the file name minus the trailing suffix """ return '.'.join(fileName.split('/')[-1].split('.')[:-1])
def strtolist(string): """ Converts a string to a list with more flexibility than ``string.split()`` by looking for both brackets of type ``(,),[,],{,}`` and commas. **Parameters** string: *string* The string to be split. **Returns** split list: *list* The split list ...
def _wlen(s): """Return number of leading whitespace characters.""" return len(s) - len(s.lstrip())
def sum_non_abundant(limit=28124): """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if...
def _get_youtube_y(insta_y, fa_insta_height, font_size): """ Get YouTube icon's y position given Instagram y for centre-alignment. """ return insta_y + fa_insta_height + font_size//10
def diff1(array): """ :param array: input x :return: processed data which is the 1-order difference """ return [j-i for i, j in zip(array[:-1], array[1:])]
def unformat_metric(metric): """Unformat a single metric. Parameters: metric (dict): The metric to unformat Returns: metric (dict): The new metric in the format needed for the log_event API. """ metric_keys = metric.keys() metric["metric_name"] = metric.pop("Me...
def _format_offset(off): """ Format a timedelta into "[+-]HH:MM" format or "" for None """ if off is None: return '' mins = off.days * 24 * 60 + off.seconds // 60 sign = '-' if mins < 0 else '+' return sign + '%02d:%02d' % divmod(abs(mins), 60)
def make_identifier(classname): """ Given a class name (e.g. CountryData) return an identifer for the data-table for that class. """ identifier = [ classname[0].lower() ] for c in classname[1:]: if c.isupper(): identifier.extend(["_", c.lower()]) else: ide...
def validate_color(color): """ Returns whether or not given color is valid in the hexadecimal format. """ return isinstance(color, str) and len(color) == 7 and color[0] == "#"
def xor(first: bool, second: bool) -> bool: """Return exclusive OR for boolean arguments""" return (first and not second) or (not first and second)
def _camel2snake(s: str) -> str: """from [1] [1]:https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case """ return "".join(["_" + c.lower() if c.isupper() else c for c in s]).lstrip("_")
def insert_fixed_parameters(parameters_dict, fixed_parameters): """Insert the fixed parameters into the parameters_dict.""" if fixed_parameters is not None: for key, value in fixed_parameters.items(): parameters_dict[key] = value return parameters_dict
def find_mismatches(listings, assessments, accuracy=.01): """Finds any listings that are listed as having different assessments. :param listings: article listings as generated by parse_article :param assessments: dict of assessments of all listed articles :param accuracy: minimum ratio of assessments t...
def convert_to_string(value): """Convert File,Directory or [File,Directory] into string or a list of string""" if type(value) is dict and value.get("class") in ["File", "Directory"]: return value["path"] elif type(value) is list or type(value) is tuple: converted_list = [] for item i...
def spl1n(string, sep): """Splits string once on the first occurance of sep returns [head, tail] if succesful, and returns (string, None) if not. Intended for scenarios when using unpacking with an unknown string. """ r = string.split(sep, 1) if len(r) > 1: return r else: ...
def recursion_limit(cnt=14, msgobj=None): """ node01 $ robustness recursion_limit 15 exec_lm_core LM_robustness->recursion_limit: maximum recursion depth exceeded :param cnt: 14 """ if cnt > 0: remain = recursion_limit(cnt-1) if msgobj is not None: msgobj("recalled ...
def compute_log_zT(log_rho, log_seebeck, log_kappa, log_temperature): """Returns the log of the thermoelectric figure of merit.""" return 2 * log_seebeck + log_temperature - log_rho - log_kappa
def range_geometric_row(number, d, r=1.1): """Returns a list of numbers with a certain relation to each other. The function divides one number into a list of d numbers [n0, n1, ...], such that their sum is number and the relation between the numbers is defined with n1 = n0 / r, n2 = n1 / r, n3 = n2 / r...
def operation_dict(ts_epoch, request_dict): """An operation as a dictionary.""" return { "model": request_dict, "model_type": "Request", "args": [request_dict["id"]], "kwargs": {"extra": "kwargs"}, "target_garden_name": "child", "source_garden_name": "parent", ...
def sq_km(value): """value is a float representing a surface using square kilometers as unit this tag simply format mille with space and leave only two digits in decimals""" if not isinstance(value, str): value = str(value) try: integer, decimal = value.split(".") except ValueError: ...
def _fill_common_details(host, port, message): """ fill ip, port and message for the connection. """ cert_details = {} cert_details['ssl_src_port'] = str(port) cert_details['error'] = message cert_details['ssl_src_host'] = str(host) return cert_details
def calculate_damage(program): """Calculate the damage done by program.""" strength, damage = 1, 0 for instruction in program: if instruction == 'C': strength *= 2 else: damage += strength return damage
def midpoint(a, b): """Calculate midpoint between two points.""" middle = [] for i in range(len(a)): middle.append(round((a[i]+b[i])/2)) return tuple(middle)
def plist_data_to_rbx_dict(plist_data: dict) -> dict: """ Converts data from a Roblox macOS .plist file into a dictionary. """ rbx_dict: dict = {} for raw_key, raw_value in plist_data.items(): split_key = raw_key.split(".") key_piece = rbx_dict for i, key_bit in enumerate(s...
def min_edit(s1, s2): """ Return the Levenshtein distance between two strings. """ if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for index2, char2 in enumerate(s2): newDistances = [index2 + 1] for index1, char1 in enumerate(s1): if char1...
def _changes(path): """ >>> _changes([2, 3, 0, 5]) [2, 1, -3, 5] >>> _changes([2]) [2] """ res = [path[0]] res += [p - p_prev for p, p_prev in zip(path[1:], path)] return res
def find_outer_most_last_parenthesis(line): """ Find outer-most last parenthesis of a line statement Used to identify the argument list in a function call :param line: a string representing a statement :return: a string representing this parenthesis with its content """ # Find last closing p...
def filter_future_act(acts, future_frame): """Get future activity ids. future activity from the data is all the future activity, here we filter only the activity in pred_len, also add the current activity that is still not finished Args: acts: a tuple of (current_actid_list, current_dist_list, ...
def adjusted_rand_index_pair_counts(a, b, c, d): """ Compute the adjusted Rand index from pair counts; helper function. Arguments: a: number of pairs of elements that are clustered in both partitions b: number of pairs of elements that are clustered in first but not second partition c: number o...
def fdr(pvals, a=0.05, n=None): """ Implementation of the Benjamini-Hochberg procedure. Takes a list of p-values and returns a list of the indices of those p-values that pass. Does not adjust p-values. See http://sas-and-r.blogspot.sg/2012/05/example-931-exploring-multiple-testing.html for ...
def remove_all_linebreaks(comment): """Remove trailing linebreak.""" return comment.replace("\n", "")
def add_last_timestamp(posts): """ add last updated liveblog timestamp """ # Currently we are leaning towards grabbing # the last published post timestamp timestamp = None if posts: timestamp = posts[0]['timestamp'] return timestamp
def __pyexpander_helper(*args, **kwargs): """a helper function needed at runtime. This evaluates named arguments. """ if len(args)==1: fn= args[0] elif len(args)>1: raise ValueError("only one unnamed argument is allowed") else: fn= None return(fn, kwargs)
def is_palindrome(n): """function helper for fourth Euler problem.""" rn = 0 on = n while n != 0: remainder = int(n % 10) rn = (rn * 10) + remainder n = int(n / 10) return on == rn
def get_parameter_label(parameter): """ Get a number in a unified format as label for the hdf5 file. """ return "{:.5f}".format(parameter)
def integer_to_octet_string_primitive(length: int, integer: int) -> bytes: """Convert a nonnegative integer to an octet string.""" # https://tools.ietf.org/html/rfc8017#section-4.1 if integer >= 256 ** length: raise ValueError(f"{integer} >= 256 ** {length}") index = 0 digits = [0] * length ...
def clean_item(item, artist, languages): """ Leave only needed fields from the respsonse :param item: raw json item :param artist: dict artist info :param languages: str language :return: dict """ return { "id": item["id"], "danceStyle": item["fields"]["Name"], "d...
def p2f(p): """Convert a path (including volume name) into a filename) """ i = p.find(":") assert i!=(-1), \ "Unexpected path format: %s, expecting volume name" % p return p[i+1:]
def canonical_base_url(base_path): """ Make given "basePath" a canonical base URL which can be prepended to paths starting with "/". """ return base_path.rstrip('/')
def parse_local_mounts(xs): """process block device info returned by device-scanner to produce a legacy version of local mounts """ return [(d["source"], d["target"], d["fs_type"]) for d in xs]
def h(level: int, text: str) -> str: """Wrap text into an HTML `h` tag.""" return f"<h{str(level)}>{text}</h{level}>"
def clean_float(v): """Remove commas from a float""" if v is None or not str(v).strip(): return None return float(str(v).replace(',', '').replace(' ',''))
def replace_simple_tags(string, from_tag="italic", to_tag="i", to_open_tag=None): """ Replace tags such as <italic> to <i> This does not validate markup """ if to_open_tag: string = string.replace("<" + from_tag + ">", to_open_tag) elif to_tag: string = string.replace("<" + from_...
def waveindex(value): """converts a wavenumber to index. Assuming there are 6000 cm^-1 and 8 points/cm^-1. """ index = int((6000-value)*8) return index
def rotate_list(in_list, n): """ Rotates the list. Positive numbers rotate left. Negative numbers rotate right. """ return in_list[n:] + in_list[:n]
def impedance(vp,rho): """ This function calculates an impedance value """ ai = vp*rho return ai
def is_list_of_dict(l): """ Checks if a list is entirely composed of dictionaries l ([]): List of any type returns (bool): True if l is entirely composed of dicts """ return all(type(x) == dict for x in l)
def sort_and_count_inversions(aList): """Return an inversion count and sorted list""" inversionCount = 0 sortedList = [] n = len(aList) # Check base case if n <= 1: # If the list has 1 or 0 elements, there are no inversions # and nothing to sort return 0, aList #...
def group_normalized_count(arr): """ aggregation: inverse of array length """ return 1.0/float(len(arr))
def city_ids(request): """Return a list of OpenWeatherMap API city ID.""" return (6434841, 2992790,)
def gravity_to_deg_plato(sg): """Convert gravity to degrees Plato. Parameters ---------- sg : float Original gravity, like 1.053 Returns ------- deg_plato : float Degrees Plato, like 13.5 """ return 250. * (sg - 1.)
def lookup_clutter_geotype(clutter_lookup, population_density): """ Return geotype based on population density Parameters ---------- clutter_lookup : list A list of tuples sorted by population_density_upper_bound ascending (population_density_upper_bound, geotype). population_de...
def add_description(citation, location): """Create metadata for additional descriptions, currently one for local location and one for preferred citation Parameters ---------- citation : str The preferred citation location : str Information on hpe to access data locally R...
def build_id(*elements, delimiter='.'): """ :param elements: :param str delimiter: :return: Strings joined by delimiter "." :rtype: str """ return delimiter.join(map(str, elements))
def get_registration_response_key(question): """ For mapping schemas to schema blocks: Answer ids will map to the user's response """ return question.get('qid', '') or question.get('id', '')
def combine(cr1, cr2): """ Combine a Curation metadata and a Canvas metadata based Curation search result. """ if cr1['curationHit']: has_cur = cr1 has_can = cr2 else: has_cur = cr2 has_can = cr1 has_cur['canvasHit'] = has_can['canvasHit'] return has_cur
def _format_items_to_db(item_list: list) -> str: """ Returns a database-ready string containing all the items """ db_items = "" for item in item_list: db_items += item.name + ";" # remove the last ; return db_items[: len(db_items) - 1]
def _handle_kind(raw): """Get kind.""" if 'eeg' in raw and ('ecog' in raw or 'seeg' in raw): raise ValueError('Both EEG and iEEG channels found in data.' 'There is currently no specification on how' 'to handle this data. Please proceed manually.') el...
def _GetPackageUri(package_name): """Returns the URI for the specified package name.""" return 'fuchsia-pkg://fuchsia.com/%s' % (package_name)
def title(snake_case: str): """Format snake case string as title.""" return snake_case.replace("_", " ").strip().title()
def create_envvar_file(env_file_path, envvars): """ Writes envvar file using env var dict :param env_file_path: str, path to file to write to :param envvars: dict, env vars :return: """ with open(env_file_path, "w+") as f: for key, value in envvars.items(): f.write("{}={}...
def weighting_syntactic_role(entity_role): """ Return weight given an entity grammatical role. +-----------+--------+ | EGrid Tag | Weight | +===========+========+ | S | 3 | +-----------+--------+ | O | 2 | +-----------+--------+ | X | 1 | ...
def format_process_state(process_state): """ Return a string formatted representation of the given process state :param process_state: the process state :return: string representation of process state """ return '{}'.format(process_state.capitalize() if process_state else None)
def absolute_path(dependency, current_path): """ Refactors `self::` and `super::` uses to absolute paths. :param dependency: :param current_path: :return: """ path_elements = dependency.split('::') if path_elements[0] == 'self': path_elements[0] = current_path elif path_elem...
def strescape(txt): """ Convert bytes or text to a c-style escaped string. """ if type(txt) == bytes: txt = txt.decode("cp1251") txt = txt.replace("\\", "\\\\") txt = txt.replace("\n", "\\n") txt = txt.replace("\r", "\\r") txt = txt.replace("\t", "\\t") txt = txt.replace('"',...
def _fix_basebox_url(url): """ Kinda fix a basebox URL """ if not url.startswith('http'): url = 'http://%s' % url if not url.endswith('/meta'): url += '/meta' return url
def build_insert(table, to_insert): """ Build an insert request. Parameters ---------- table : str Table where query will be directed. to_insert: iterable The list of columns where the values will be inserted. Returns ------- str Built query string. """...
def check_mantarray_serial_number(serial_number: str) -> str: """Check that a Mantarray Serial Number is valid.""" if len(serial_number) > 9: return "Serial Number exceeds max length" if len(serial_number) < 9: return "Serial Number does not reach min length" if serial_number[:2] != "M0"...
def get_damptime(conf) : """Parse pressure damp from configuration file Args: conf: Configuration data. Returns: dampt1: Pressure damp in processing. dampt2: Pressure damp in post-processing. """ try : damptime=float(conf['R...
def build_training_response(mongodb_result, hug_timer, remaining_count): """ For reducing the duplicate lines in the 'get_single_training_movie' function. """ return {'imdbID': mongodb_result['imdbID'], 'plot': mongodb_result['plot'], 'year': mongodb_result['year'], 'poster_url': mongodb_result['poster'], ...
def trapezoid_area(base_minor, base_major, height): """Returns the area of a trapezoid""" return height*((base_minor + base_major)/2)
def reduceWith(reducer, seed, iterable): """ reduceWith takes reducer as first argument, computes a reduction over iterable. Think foldl from Haskell. reducer is (b -> a -> b) Seed is b iterable is [a] reduceWith is (b -> a -> b) -> b -> [a] -> b """ accumulation = seed for value...
def calc_AIC_base10_checksum(code): """Check if a string checksum char in the base10 representation is correct. Parameters ---------- AIC : str The string containing the code used to generate the checksum Returns ------- str The checksum value. """ xn = [2*i...
def get_bad_query_summary(queries_above_threshold, total): """generates the bad query summary""" total_suspect = len(queries_above_threshold) percent = 0.0 if total_suspect > 0: percent = (float(total_suspect) / float(total)) * float(100.0) return "\nsuspect queries totals: %i/%i - %.2f%%\n"...
def remove_key_from_numpy_docstring_section(numpy_docstring_section, key): """Function to remove a specific key from a section of a numpy docstring. For example when combining docstrings with ``combine_split_mixin_docs`` both docstrings may have a particular attribute listed so it is neccessary to remo...
def persistence(n): """ Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit. :param n: an integer value. :return: the numbers of times the dig...
def find_all_available_seats(seats): """Find and return seat numbers that are unassigned. :param seats: dict - seating chart. :return: list - list of seat numbers available for reserving.. """ available = [] for seat_num, value in seats.items(): if value is None: available....
def _SortSimilarPatterns(similar_patterns): """Sorts a list of SimilarPatterns, leaving the highest score first.""" return sorted(similar_patterns, key=lambda x: x.score, reverse=True)
def encode_shift(s: str): """ returns encoded string by shifting every character by 5 in the alphabet. """ return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s])
def averageScore(userScoreD): """ userScoreD is the dictionary that contains user scores. Returns the average user's score on a single item """ sum = 0 len = 0 # go over scores in {userID:score,...} dictionary for score in userScoreD.values(): sum += score ...
def align_down(alignment, x): """Rounds x down to nearest multiple of the alignment.""" a = alignment return (x // a) * a
def despace(line): """ Removes single spaces from column names in string. e.g., "CONTAINER ID NAME" -> "CONTAINERID NAME" This is done so that pandas can read space-delimited files without separating headers with names containing spaces. """ parts = line.split(' ') parts = [p ...
def is_first_line(line): """ Returns true if line is the first line of a new file """ return line.split("|")[0].strip() == "1"
def card_matches(card, hand): """Checks if the colour/value matches the card in the players hand""" wilds = ["wild", "wild+4"] matches = False for player_card in hand: if matches: break elif player_card[0] in wilds: matches = True elif card[0] in wilds and...
def get_fem_word(masc_word, words): """ :param masc_word: masculine word to convert :param words: list of English-Femining-Masculine word triples :return: feminine inflection of masculine word """ for _, fem_word, word in words: if masc_word == word: return fem_word raise...
def split_at(string, sep, pos): """ Return string splitted at the desired separator. Args: string (str): The supplied string that will be splitted. sep (str): The desired separator to use for the split. pos (int): The desired occurence of the defined separator within the...
def vue(value: str) -> str: """Encierra el valor en doble llaves 'value' -> '{{ value }}'.""" return "{{ %s }}" % value
def facilityidstringtolist(facilityidstring): """ This method receives a string with the facility id's and converts it to a list with 1 facility id at each index. :param facilityidstring: string with all the facility id's :return: a list containing the facility id's as strings. """ facilityidlis...
def correct_other_vs_misc(rna_type, _): """ Given 'misc_RNA' and 'other' we prefer 'other' as it is more specific. This will only select 'other' if 'misc_RNA' and other are the only two current rna_types. """ if rna_type == set(['other', 'misc_RNA']): return set(['other']) return rn...
def num_splits(s, d): """Return the number of ways in which s can be partitioned into two sublists that have sums within d of each other. >>> num_splits([1, 5, 4], 0) # splits to [1, 4] and [5] 1 >>> num_splits([6, 1, 3], 1) # no split possible 0 >>> num_splits([-2, 1, 3], 2) # [-2, 3], [...
def cond(predicate, consequence, alternative=None): """ Function replacement for if-else to use in expressions. >>> x = 2 >>> cond(x % 2 == 0, "even", "odd") 'even' >>> cond(x % 2 == 0, "even", "odd") + '_row' 'even_row' """ if predicate: return c...
def SelectColumn(lig_dict, colname): """ Prune the dictionary, only attribute in colname will be left. :param lig_dict: a tree like dictionary :param colname: what attribute you want to keep. :return: a new dictionary """ lig_new = dict() for k in lig_dict: lig_new[k] = {sk:v fo...