content
stringlengths
42
6.51k
def function_lexer(string): """A brute force lexer for funcions of the SensorThings API. Returns a list of the function and parameters""" parsedlist = [] parsedstring = '' leftbcounter = 0 rightbcounter = 0 for i, a in enumerate(string): if a == '(': leftbcounter += 1 ...
def make_mongo_url(user, pwd, url, db): """ makes the mongo url string :param user: user :param pwd: password :param url: url :param db: db :return: mongo url string """ return "mongodb://" + user + ":" + pwd + "@" + url + "/" + db
def all_nums(table): """ Returns True if table contains only numbers (False otherwise) Example: all_nums([[1,2],[3,4]]) is True all_nums([[1,2],[3,'a']]) is False Parameter table: The candidate table to modify Preconditions: table is a rectangular 2d List """ result = True # Ac...
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to underscores. """ value = value.strip().lower() value = value.replace(',', '') value = value.replace(' ', '_') return value
def google_api_query(query_dict: dict) -> str: """Join given query args into one string. Return query string in format required by googlapis: https://developers.google.com/books/docs/v1/using#WorkingVolumes """ if not query_dict: return "" def allowed_google_item(): if item[1] ...
def format32BitHexStr(hexStr): """ format the given string which represents a valid 32-bit hexadecimal number. prefix "0x" will be added and will replace any valid prefix. alphabetic letter will be formatted into upper case. "0" will be used to fill the hexadecimal number if this number is represent...
def get_url_at_page_number(url: str, counter: int) -> str: """Retrieves the link to the next result page of a query.""" # All result pages will start out like this root_url = "https://www.hearthstonetopdecks.com/cards/" # Fhe first page of the query is followed by a string # describing your q...
def makevar(name): """Make a variable name""" return "var" + str(name)
def maprange(x, input: complex, output: complex): """Scales bound of `x` as of `input` and converts to another bound as of `output`. `input` and `output` are complex numbers whose `real` denotes minimum and `imag` denotes maximum value.""" a = input.real; b = input.imag c = output.real; d = outpu...
def price_text(price): """Give price text to be rendered in HTML""" if price == 0: return "Gratis" return price
def Segments(n): """ n has to be greater than 3 """ # divide Segment into 2 sub Segments if n % 2 == 0: n_1 = n / 2 n_2 = n / 2 else: n_1 = (n + 1) / 2 n_2 = n - n_1 # determine the checking point index of the two sub Segments if n_1 % 2 == 0: n_1_checking_point = n_1 / 2 else: ...
def sample_data_path(name): """return the static path to a CatEyes sample dataset. Parameters ---------- name : str The example file to load. Possible names are: 'example_data', 'example_events' and 'test_data_full'. Returns ------- data_path : str The absolu...
def _classify(srna_type, attr, samples): """ Parse the line and return one line for each category and sample. """ # iso_5p, iso_3p, iso_add ... # FILTER :: exact/isomiR_type lines = [] counts = dict(zip(samples, attr['Expression'].split(","))) for s in counts: if int(counts[s...
def champZ(commande): """ Commande CC pour ajouter un Scalar Field pour la composante Z """ commande+=" -coord_to_SF Z" #subprocess.call(commande) return commande
def date_to_int(d): """ Represents a date object as an integer, or 0 if None. """ if d is None: return 0 return int(d.strftime('%Y%m%d'))
def Clamp(val, min, max): """ Clamps a given value to be between max and min parameters. Converts value to float. :param val: (float, int) Value to clamp :param min: (float, int) Minimal value :param max: (float, int) Maximal value :returns: float """ val = float(val) min = float(min) max = float(max) if v...
def get_radii(coords): """ Radii of x,y,z arrays in array. Distance from (0,0,0). """ return [(x**2+y**2+z**2)**.5 for x,y,z in coords]
def calculate_real_len(args): """ Calculate the real length of supplied arguments :param args: args :return: real length """ i = 0 for arg in args: if arg is not None: i += 1 return i
def indices_containing_substring(list_str, substring): """For a given list of strings finds the indices containing the substring. Parameters ---------- list_str: list of strings substring: substring Returns ------- index: containing the substring or -1 """ indices = [] f...
def normalize(hex_code): """Convert hex code to six digit lowercase notation. """ hex_digits = hex_code.lstrip('#') if len(hex_digits) == 3: hex_digits = ''.join(2 * c for c in hex_digits) return '#{}'.format(hex_digits.lower())
def count_chars(s: str) -> dict: """Checking the chars number in a str example :param s: {str} :return: {dict} """ count_dict = {} for c in s: if c in count_dict: count_dict[c] += 1 else: count_dict[c] = 1 return count_dict
def match_pattern( resource: bytes, pattern: bytes, mask: bytes, ignored: bytes): """ Implementation of algorithm in: https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern True if pattern matches the resource. False otherwise. """ if len(pattern) != len...
def format_bit(b): """ Converts a bit to a string. >>> format_bit(0) '0' >>> format_bit(one) '1' """ return '0' if b == 0 else '1'
def get_argument_score(user1, user2): """ Considers two twitter users and calculates some proxy of 'probability of argument' between them. Score is either in [0, 1] or {0, 1} (undecided) """ # this is likely going to be a binary classifier # or logistic regression model # # req...
def is_false(str_value): """ :param str_value: String to evaluate. :returns: True if string represents TGN attribute False value else return True. """ return str_value.lower() in ('false', 'no', '0', 'null', 'none', '::ixnet::obj-null')
def get_key(val, search_dict): """ Gets dict key from supplied value. val: Value to search search_dict : Dictionary to search value for """ for key, value in search_dict.items(): if val in value: return key
def interpolate_num(a, b, fraction): """Linear interpolation for numeric types. Parameters ---------- a : numeric type initial value b : numeric type final value fraction : float fraction to interpolate to between a and b. Returns ---------- : numeric ty...
def insertion_sort(arr): """ insertion sort using swap Time: O(n^2) Space: O(1) """ for i in range(1, len(arr)): j = i while j > 0 and arr[j - 1] > arr[j]: arr[j - 1], arr[j] = arr[j], arr[j - 1] j -= 1 return arr
def get_number(s): """ Check that s is number In this plugin, heatmaps are created only for columns that contain numbers. This function checks to make sure an input value is able to be converted into a number. This function originally appeared in the image asembler plugin: https://github.c...
def recursive_get(d, attr, default=None, sep='.'): """ Recursive getter with default dot separation :param d: :param attr: :param default: :param sep: :return: """ if not isinstance(attr, str): return default if not isinstance(d, dict) or not dict: return default ...
def overlap(_x: list, _y: list) -> float: """overlap coefficient (Unuse) Szymkiewicz-Simpson coefficient) https://en.wikipedia.org/wiki/Overlap_coefficient """ set_x = frozenset(_x) set_y = frozenset(_y) return len(set_x & set_y) / float(min(map(len, (set_x, set_y))))
def count_bitmap(b, n): """ Counts the number of bitmaps occupied """ return 0 if n==0 else (1 if b&1==1 else 0) + count_bitmap(b>>1, n-1)
def preprocess_DFun_args(dfun): """Preprocess function arguments in function declaration `dfun`""" assert "DFun_args" in dfun dfun["DFun_args"] = [ {"tag": "DFun_arg", "DFun_arg_name": name, "DFun_arg_type": t} for name, t in dfun["DFun_args"] ] return dfun
def generate_access(metadata): """Generates access metadata section. https://oarepo.github.io/publications-api/schemas/publication-dataset-v1.0.0.html#allOf_i0_allOf_i1_access """ return { 'record': 'restricted', 'files': 'restricted', 'owned_by': [] }
def convert_label_for_pixellink(old_class): """Convert input class name to new for PixelLink Args: old_class: label to be converted Return converted label name """ # IMAGE_TYPE_TEXT_DETECTION = ['TopTitleText','TopTitleWord', 'LeftTitleText','LeftTitleWord', 'Text', 'Word'] ...
def calcInputUnits(c): """gets input units for a response, checking InstrumentSensitivity, InstrumentPolynomial and the first Stage""" units = None if hasattr(c, 'Response'): resp = c.Response if hasattr(resp, 'InstrumentPolynomial'): units = resp.InstrumentPolynomial.InputUn...
def _batch_updates(updates): """Takes a list of updates of form [(token, row)] and sets the token to None for all rows where the next row has the same token. This is used to implement batching. For example: [(1, _), (1, _), (2, _), (3, _), (3, _)] becomes: [(None, _), (1, _), (2,...
def get_version(version_info): """Return a PEP-386 compliant version number from version_info.""" assert len(version_info) == 5 assert version_info[3] in ('alpha', 'beta', 'rc', 'final') parts = 2 if version_info[2] == 0 else 3 main = '.'.join([str(part) for part in version_info[:parts]]) sub ...
def term_A(P0, e0): """Term A in the main equation. P0 is the atmospheric pressure at the site (in hPa). e0 is the water vapor pressure at the site (in hPa)""" return 0.002357 * P0 + 0.000141 * e0
def get_projects_by_4(p): """ The frontend displays a list of projects in 4 columns. This function splits the list of the projects visible by the user in chunks of size 4 and returns it.""" # Split the list of visible projects by chunks of size 4 projects = sorted([e['id'] for e in p['projects']]) ...
def is_pull_request(issue): """Return True if the given issue is a pull request.""" return 'pull_request_url' in issue
def extract_label_signature(autodoc_line): """Extract the object name and signature of the object being document. For example:: >>> extract_label_signature(':: foo(a, b)') 'foo', 'foo(a, b)' >>> extract_label_signature(':: foo') 'foo', None """ _, what = autodoc_line.sp...
def validate_probability(p: float, p_str: str) -> float: """Validates that a probability is between 0 and 1 inclusively. Args: p: The value to validate. p_str: What to call the probability in error messages. Returns: The probability p if the probability if valid. Raises: ...
def check_bounds_overlap(bounds_1, bounds_2): """ Calculate the ratio of overlap """ left_1, top_1, right_1, bottom_1 = bounds_1[0], bounds_1[1], bounds_1[2], bounds_1[3] left_2, top_2, right_2, bottom_2 = bounds_2[0], bounds_2[1], bounds_2[2], bounds_2[3] width_1 = right_1 - left_1 height_1...
def intseq(words, w2i, unk='.unk'): """ Convert a word sequence to an integer sequence based on the given codebook. :param words: :param w2i: :param unk: :return: """ res = [None] * len(words) for j, word in enumerate(words): if word in w2i: res[j] = w2i[w...
def extract_github_owner_and_repo(github_page): """ Extract only owner and repo name from GitHub page https://www.github.com/psf/requests -> psf/requests Args: github_page - a reference, e.g. a URL, to a GitHub repo Returns: str: owner and repo joined by a '/' """ if githu...
def strip_list(xs, e): """Get rid of all rightmost 'e' in the given list.""" p = len(xs) - 1 while p >= 0 and xs[p] == e: p -= 1 return xs[:p+1]
def hex_to_byte(hex_str): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. :param hex_str: hex string msg with UUID. :return: byte string msg with UUID. """ # The list comprehension implementation is fractionally slower in this ...
def mySqrt(x): """ :type x: int :rtype: int """ if x <= 0: return x x0=x hk=0 while 1: hk=(pow(x0,2)-x)/(2*x0) x0 -= hk if hk < 0.1: break return int(x0)
def _strip_quote(value): """ Removing the quotes around the edges """ if value.startswith('"') and value.endswith('"'): value = value[1:-1] elif value.startswith("'") and value.endswith("'"): value = value[1:-1] return value
def has_three_or_more_vowels(string): """Check if string has three or more vowels.""" return sum(string.count(vowel) for vowel in 'aeiou') >= 3
def from_letter_base(letters): """Tranforms a letter base number into an integer.""" n = 0 for i, letter in enumerate(letters): n += (ord(letter) - 64) * pow(26, len(letters) - (i + 1)) return n - 1
def ordset(xs): """ a generator for elements of xs with duplicates removed """ return tuple(dict(zip(xs, xs)))
def time_delta(t1: int, t2: int) -> float: """ :param t1: first timestamp :param t2: second timestamp :return: time delta """ return (t2 - t1) / 3600000
def filter_jump_paths(simple_paths): """ Filter jump simple path or simple cycle(as a special case of simple path). Args: simple_paths (list): a list of simple paths, where each path is a list. Return: List: a list of filtered simple paths. """ filter_scs = [] for...
def intersector(x, y): """ Intersection between two tuples of counters [c_1, c_3, ..., c_d] [c'_1, c'_3, ..., c'_d]. Corresponds to the minimum between each c_i, c'_i. :param x: :type x: :param y: :type y: :return: :rtype: """ size = len(x) res = [] for i in range(0,...
def applyF_filterG(L, f, g): """ Assumes L is a list of integers Assume functions f and g are defined for you. f takes in an integer, applies a function, returns another integer g takes in an integer, applies a Boolean function, returns either True or False Mutates L such that, for ea...
def col_to_num(col_str): """ Convert base26 column string to number. """ expn = 0 col_num = 0 for char in reversed(col_str): col_num += (ord(char) - ord('A') + 1) * (26 ** expn) expn += 1 return col_num
def store_by_slc_id(obj_list): """returns a dict where acquisitions are stored by their slc id""" result_dict = {} for obj in obj_list: slc_id = obj.get('_source', {}).get('metadata', {}).get('title', False) if slc_id: result_dict[slc_id] = obj return result_dict
def minmax(s): """Return the minimum and maximum elements of a sequence. Hint: start with defining two variables at the beginning. >>> minmax([1, 2, -3]) (-3, 2) >>> minmax([2]) (2, 2) >>> minmax([]) (None, None) """ if s: max = s[0] min = s[0] for...
def replace_if_none(to_be_checked, replacement_string): """Return a replacement is to be checked is empty (None or empty string)""" if to_be_checked: return to_be_checked return replacement_string
def check_horizontal_winner(board) -> bool: """checks for horizontal winner""" for row in board: if row[0] == row[1] == row[2] and row[0] is not None: return True return False
def get_most_freq_cui(cui_list, cui_freq): """ from a list of strings get the cui string that appears the most frequently. Note: if there is no frequency stored then this will crash. """ cui_highest_freq = None for cui in cui_list: if cui in cui_freq: # sets an initial c...
def add_extras(cosmo): """Sets neutrino number N_nu = 0, neutrino density omega_n_0 = 0.0, Helium mass fraction Y_He = 0.24. Also sets w = -1. """ extras = {'omega_n_0' : 0.0, 'N_nu': 0, 'Y_He': 0.24, 'w' : -1.0, 'baryonic_effects' : Fals...
def compression_ratio(obs_hamiltonian, final_solution): """Function that calculates the compression ratio of the procedure. Args: - obs_hamiltonian (list(list(str))): Groups of Pauli operators making up the Hamiltonian. - final_solution (list(list(str))): Your final selection of observables. ...
def joinPathSplit(pathSplit): """ Join the pathSplit with '/' """ return "/".join(pathSplit)
def format_span_id(span_id): """Format the span id according to b3 specification.""" return format(span_id, '016x')
def instance_or_id_to_snowflake(obj, type_, name): """ Validates the given `obj` whether it is instance of the given `type_`, or is a valid snowflake representation. Parameters ---------- obj : `int`, `str` or`type_` instance The object to validate. type_ : `type` of (`tuple` of `ty...
def remove_prefix(text, prefix): """ remove prefix from text """ if text.startswith(prefix): return text[len(prefix):] return text
def get_tag_name(number): """Convert a pinColor to a tag string""" if number == 0: return "Food" elif number == 1: return "Drink" elif number == 2: return "Coffee" elif number == 3: return r"Coffee\ Supplies" #dayone2 cli needs the space escaped elif num...
def calc_line(p1, p2): """ Calculates line from two points p1 and p2 by returning a, b, c from line formula ax + by = c :param p1: point 1, represented as x, y coordinates :param p2: point 2, represented as x, y coordinates :return: a, b, -c from line formula ax + by = c """ a = (p1[1] -...
def find_stats(_id, stats): """Find the latest activity stats for the SSG with `_id`. """ for ssg in stats: if ssg["id"] == _id: return ssg return None
def _transform_data(data, data_mapper=None): """Use mapper or transformer to convert raw data to engineered before explanation. :param data: The raw data to transform. :type data: numpy, pandas, dense, sparse data matrix :param data_mapper: A list of lists of generated feature indices for each raw feat...
def find_nth(str1, mystr, n): """ Finds a pattern in an input string and returns the starting index. """ start = str1.find(mystr) while start >= 0 and n > 1: start = str1.find(mystr, start+len(mystr)) n -=1 return start
def _config_split(value, delim, cast=None): """Splits the specified value using `delim` and optionally casting the resulting items. Args: value (str): config option to split. delim (str): string to split the option value on. cast (function): to apply to each item after the split ope...
def is_zero_len(value): """ is value of zero length (or has no len at all)""" return getattr(value ,'__len__', lambda : 0)() == 0
def mocked_search_execute(search_query: str, search_part: str, search_type: str, max_results: int): """ Currently only returns a response of video ID's based on max_results. Otherwise returns none. """ if search_type == 'video' and search_part == 'id': items = [{'id': {'videoId': str(i).zfil...
def parse_material(inp): """ Parse each material and create a map with it's name and the amount. """ material_map = {} for x in inp.split(", "): amount, name = x.split(" ") material_map[name] = int(amount) return material_map
def index(it, ind): """ Fancy indexing into an indexable iterable (tuple, list). Examples ======== >>> from sympy.unify.core import index >>> index([10, 20, 30], (1, 2, 0)) [20, 30, 10] """ return type(it)([it[i] for i in ind])
def gs_to_accel(data): """ Convert to m/s^2 :param data: :return: data in m/s^2 """ import numpy as np return np.array(data) * 9.8
def is_integer(value): """ check if value is an interger """ try: v = int(value) return True except ValueError: return False
def b2i(byte_string): """ big endian byte array to integer value """ return int.from_bytes(byte_string, byteorder="big", signed=False)
def infinite(smaj, smin, bpa): """ If the beam is not correctly fitted by AWimager, one or more parameters will be recorded as infinite. :param smaj: Semi-major axis (arbitrary units) :param smin: Semi-minor axis :param bpa: Postion angle """ return smaj == float('inf') or smin == float...
def is_file(line: str) -> bool: """Check if a return line is a song file.""" return line.startswith('file:')
def giniIndex(p_m1): """ G = sum_k { p_mk(1-p_mk } """ G = p_m1*(1-p_m1)*2 return G
def not_list_tuple(obj): """return False if obj is a list or a tuple""" return not isinstance(obj, (list, tuple))
def genome_2_cortical_list(flat_genome): """ Generates a list of cortical areas inside genome """ cortical_list = list() for key in flat_genome: cortical_id = key[9:15] if cortical_id not in cortical_list and key[7] == "c": cortical_list.append(cortical_id) return cor...
def _clean_listofcomponents_tuples(listofcomponents_tuples): """force 3 items in the tuple""" def to3tuple(item): """return a 3 item tuple""" if len(item) == 3: return item else: return (item[0], item[1], None) return [to3tuple(item) for item in listofcompon...
def _wordwrap(text, chars_per_line=80): """Split the lines of a text between whitespaces when a line length exceeds the specified number of characters. Newlines already present in text are kept. """ text_ = text.split('\n') text = [] for l in text_: if len(l) > chars_per_line: ...
def normalize(y_eval, mean_y, std_y): """ normalize outputs for GP """ return (y_eval - mean_y) / std_y
def sizes_by_key(sections, key): """ Takes a dict of sections (from load_sections) and returns a dict keyed by 'key' with aggregate output size information. Key can be either "archive" (for per-archive data) or "file" (for per-file data) in the result. """ result = {} for section in sections.va...
def get_sample_name(sample, delimiter='_', index=0): """ Return the sample name """ return sample.split(delimiter)[index]
def find_high_index1(arr, key): """Find the high index of the key in the array arr. Time: O(log n) Space: O(1) """ lo, hi = 0, len(arr) while lo < hi: mi = (lo + hi) // 2 if arr[mi] <= key: lo = mi + 1 elif arr[mi] > key: hi = mi if lo > 0 an...
def method_item(method, status, wsdl): """Function that sets the correct structure for method item""" return { 'serviceCode': method[4], 'serviceVersion': method[5], 'methodStatus': status, 'wsdl': wsdl }
def nearest_square(num): """Return the nearest perfect square that is less than or equal to num""" root =0 while (root +1) **2 <= num: root +=1 return root**2
def csv_append(csv_string, item): """ Appends an item to a comma-separated string. If the comma-separated string is empty/None, just returns item. """ if csv_string: return ",".join((csv_string, item)) else: return item
def deep_exclude(state: dict, exclude: list) -> dict: """[summary] Args: state (dict): A dict that represents the state of an instance. exclude (list): Attributes that will be marked as 'removed' Returns: dict: [description] """ tuples = [key for key in exclude if isinstanc...
def parse_string_format(time_string): """ Fixes some difficulties with different time formats """ format = "%Y-%m-%d %H:%M:%S" if '.' in time_string: format = "%Y-%m-%d %H:%M:%S.%f" if time_string[-6] == '+': format = format + "%z" return format
def spin_words(sentence): """Take a string and reverse all words 5+ characters.""" answer_array = [] split = sentence.split(" ") for word in split: if len(word) < 5: answer_array.append(word) else: answer_array.append(word[::-1]) return " ".join(answer_array)
def FindNearestElectrode(x, y, z, electrodes={}): """ finds the nearest electrode in the dictionary electrodes (x,y,z) is the coordinates of a proposed electrode :param x: x coordinate of electrode :param y: y coordinate of electrode :param z: x coordinate of electrode :param electrodes: dic...