content
stringlengths
42
6.51k
def int_to_string( long_int, padto=None ): """ Convert integer long_int into a string of bytes, as per X9.62. If 'padto' defined, result is zero padded to this length. """ if long_int > 0: octet_string = "" while long_int > 0: long_int, r = divmod( long_int, 25...
def _abs2(x): """Absolute square of data""" return x.real*x.real + x.imag*x.imag
def virus_test(name): """Tests whether "virus" is in a species name or not. Written by Phil Wilmarth, OHSU, 2009. """ return ('virus' in name)
def get_fun_elem_from_fun_inter(interface_list, fun_elem_list): """Get output_list = [[fun_elem_1, fun_elem_2, fun_inter]...] list from interface_list = [[producer, consumer, fun_inter]...] and put value to False if (first, second, interface) have been added to output_list (i.e. fun_elem_1/fun_elem_2 have b...
def get_tokens(line): """tokenize an Epanet line (i.e. split words; stopping when ; encountered)""" tokens=list() words=line.split() for word in words: if word[:1] == ';': break else: tokens.append(word) return tokens
def rename_qty2stdunit(unit): """ Clean OFF quantity unit to a standard unit name (g, kg, mg, gal, egg, portion, l...) Args: unit (str): OFF quantity unit Returns: std_unit (str): standard unit name """ clean_matrix = {None:[None,''], 'g':['g','gr','grammes','...
def obtain_all_devices(my_devices): """Dynamically create 'all' group.""" new_devices = {} for device_name, device_or_group in my_devices.items(): # Skip any groups if not isinstance(device_or_group, list): new_devices[device_name] = device_or_group return new_devices
def frequency_to_n(freq, grid=0.00625e12): """ converts frequency into the n value (ITU grid) """ return (int)((freq-193.1e12)/grid)
def _get_pairs(data): """Return data in pairs This uses a clever hack, based on the fact that zip will consume items from the same iterator, for each reference found in each row. Example:: >>> _get_pairs([1, 2, 3, 4]) [(1, 2), (3, 4)] """ return list(zip(*((iter(data),)*2...
def slice(n): """Return slice for rank n array""" return ", ".join(["1"] * n)
def get_lane_mean_x(lane): """Get mean x of the lane. :param lane: target lane :type lane: list :return: the mean value of x :rtype: float """ x_pos_list = [] for pt in lane: x_pos_list.append(pt.x) x_mean = 0 if len(x_pos_list) == 1: x_mean = x_pos_list[0] e...
def taux_boost(cote, boost_selon_cote=True, boost=1): """ Calcul du taux de boost pour promotion Betclic """ if not boost_selon_cote: return boost if cote < 2: return 0 if cote < 2.51: return 0.25 if cote < 3.51: return 0.5 return 1
def sgn(x): """ Return the sign of *x*. """ return 1 if x.real > 0 else -1 if x.real < 0 else 0
def unique_preserve_order(lst): """ Deduplicate lst without changing the order. Return a new list. The elements of lst are not required to be hashable. """ new_lst = [] for item in lst: if item not in new_lst: new_lst.append(item) return new_lst
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in earlier dicts. Modified from http://stackoverflow.com/a/26853961/554546 :param list[dict] dict_args: An iterable of dictionaries. :return: A dictionary merge...
def padding_4ch(s): """ Add zeros to form 4 continuous characters and add spaces every 4 characters :type s: str """ n = len(s) r = n % 4 if r != 0: k = 4 - r s = k * '0' + s else: s = s s = s[::-1] s = ' '.join(s[i:i + 4] for i in range(0, len(s), 4)) ...
def networkx_json_to_visjs(res): """Convert JSON output from networkx to visjs compatible version Params ------ res: JSON output from networkx of the graph """ colors = {1: 'green', 2: 'red', 3: 'rgba(255,168,7)'} if res: links = res['links'] new_links = [] for _link...
def join_host_strings(user, host, port=None): """Turn user/host/port strings into ``user@host:port`` combined string.""" port_string = '' if port: port_string = ":%s" % port return "%s@%s%s" % (user, host, port_string)
def normalize(size_sequence): """ :param size_sequence: list or tuple of [k1, k2, ... , kn] :return: a tuple of (k1/(k1 + k2 + ... + kn), k2/(k1 + k2 + ... + kn), ... , kn/(k1 + k2 + ... + kn),) """ total = sum(size_sequence) denominator = 1.0 / total result = [item * denominator for item in...
def RequestArgsGetHeader(args, kwargs, header, default=None): """Get a specific header given the args and kwargs of an Http Request call.""" if 'headers' in kwargs: return kwargs['headers'].get(header, default) elif len(args) > 3: return args[3].get(header, default) else: return default
def expand_shape(shape): """ Expands a flat shape to an expanded shape >>> expand_shape([2, 3]) [2, [3, 3]] >>> expand_shape([2, 3, 4]) [2, [3, 3], [[4, 4, 4], [4, 4, 4]]] """ expanded = [shape[0]] for i in range(1, len(shape)): next = [shape[i]] * shape[i-1] for j i...
def is_pid_valid(pid): """Checks whether a pid is a valid process ID of a currently running process.""" # adapted from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid import os, errno if pid <= 0: raise ValueError('Invalid PID.') try: os.kill...
def comment(commentstr=u''): """Insert comment.""" return u'<!-- ' + commentstr.replace(u'--',u'') + u' -->'
def check_if_seq(NN_config): """ Parameters ---------- NN_config : list Specifies the architecture of neural network. Returns ------- return_seq : bool Specifies if there are some GRU or LSTM layers in the NN_config (or its part). """ if "g" in NN_config or "l" in N...
def cast_string(f, s): """ Generic function that casts a string. :param f: (function) Any casting function. :param s: (str) String to cast. :return: The casted object """ try: return f(s) except ValueError as e: return None
def forms_processed_per_hour(total_forms_processed, total_time_in_seconds): """Calculate forms processed per hour. Divide total forms processed by the total time it took to process all the forms. :param total_forms_processed: Total number of forms processed. :param total_time_in_seconds: Total time...
def _wcversion_value(ver_string): """ Integer-mapped value of given dotted version string. :param str ver_string: Unicode version string, of form ``n.n.n``. :rtype: tuple(int) :returns: tuple of digit tuples, ``tuple(int, [...])``. """ retval = tuple(map(int, (ver_string.split('.')))) r...
def acos(c): """acos - Safe inverse cosine Input argument c is shrunk to admissible interval to avoid case where a small rounding error causes a math domain error. """ from math import acos if c > 1: c=1 if c < -1: c=-1 return acos(c)
def _format_time(seconds): """Formats seconds to readable time string. This function is used to display time in progress bar. """ if not seconds: return '--:--' seconds = int(seconds) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if hours: ...
def GetTokensInSubRange(tokens, start, end): """Get a subset of tokens within the range [start, end).""" tokens_in_range = [] for tok in tokens: tok_range = (tok.lineno, tok.column) if tok_range >= start and tok_range < end: tokens_in_range.append(tok) return tokens_in_range
def deduped_table(table): """ De-deplicate the codepoint entries in the from-disk table according to WHATWG specs. """ tmp_table_1 = [x for x in table] # Remove all except the _last_ entries for code points U+2550, U+255E, # U+2561, U+256A, U+5341, and U+5345. tmp_table_1.reverse() ...
def is_number(s): """return True if s is a number, or False otherwise""" try: float(s) return True except ValueError: return False
def generate_command(input_dir, output_dir, vocab_file, bert_config, init_checkpoint, layers, max_seq_length, batch_size): """ generete command :param input_dir: :param output_dir: :param vocab_file: :param bert_config: :param init_checkpoint: :param layers: :param max_seq_length: ...
def _get_nested(dict_, keys): """ Nested get method for dictionaries (and lists, tuples). """ try: for key in keys: dict_ = dict_[key] except (KeyError, IndexError, TypeError): return None return dict_
def uniformFunc( dispX, dispY, radius ): """ Density Estimation using uniform function -> square in 2D """ maskX = dispX <= radius maskY = dispY <= radius maskXY = maskX & maskY return maskXY/ float(radius *radius)
def prime(num): """" To check whether a number is prime """ num2 = num while num2 > 0: if num == num2: num2 -= 1 elif num2 == 1: num2 -= 1 elif num % num2 == 0: return False num2 -= 1 return T...
def to_sequence(index, text): """Returns a list of integer indicies of lemmas in `text` to the word2idx vocab in `index`. :param index: word2idx vocab. :param text: list of tokens / lemmas / words to be indexed :returns: list of indicies """ indexes = [index[word] for word in text if word...
def unique(seq): """ unique: Retorna valores unicos de uma lista Parametros ---------- seq: array de objetos lista de objetos Examples -------- # >> import file_utils # >>> file_utils.unique([1,1,2,3,3,4]) # lista de nu...
def _resolve(dikt, var): """ Resolve a complex key using dot notation to a value in a dict. Args: dikt: Dictionary of key-value pairs, where some values may be sub dictionaries, recursively. var: Key or string of dot-separated keys denoting path through dict Returns: The referenced value, or...
def sumSquare(number): """ This function will do the math required to calculate the difference in the stated problem. """ sumSq = 0 # Sum of the squares. sqOfSum = 0 # Square of the sum. for i in range(1, number+1): sumSq += i**2 # Get the sum of the squares. sqOfSum +=...
def precipitation_intensity(precip_intensity, unit): """ :param precip_intensity: float containing the currently precipIntensity :param unit: string of unit for precipitation rate ('in/h' or 'mm/h') :return: string of precipitation rate. Note: this is appended to and used in special event times """ ...
def remove_unnecessary(string): """Removes unnecessary symbols from a string and returns the string.""" string = string.replace('@?', '') string = string.replace('?@', '') return string
def fibonacciNumber(n): """ :return: n'th fibonacci Number """ if n == 0: return 0 elif n == 1: return 1 else: return fibonacciNumber(n - 1) + fibonacciNumber(n - 2)
def get_note_freq(note: int) -> float: """Return the frequency of a note value in Hz (C2=0).""" return 440 * 2 ** ((note - 33) / 12)
def tokenize_doc(json_data): """ IMPLEMENT ME! Tokenize a document and return its bag-of-words representation. doc - a string representing a document. returns a dictionary mapping each word to the number of times it appears in doc. """ words = {} for w in json_data['ingredients']: ...
def MinMod(pa,pb): """ Minmod averaging function """ s = (0.5 if pa>0.0 else -0.5) + (0.5 if pb>0.0 else -0.5) return min([abs(pa),abs(pb)])*s
def index_of_value(x, value): """ Takes the list x and returns a list of indices where it takes value """ indices = [i for i in range(len(x)) if x[i]==value] if indices == []: print("There is no item=={v} in the list".format(v=value)) else: return indices
def _endswith(prop_value, cmp_value, ignore_case=False): """ Helper function that take two arguments and checks if :param prop_value: endswith :param cmp_value: :param prop_value: Property value that you are checking. :type prop_value: :class:`str` :param cmp_value: Value that you are checking ...
def evaluations(ty, pv): """ evaluations(ty, pv) -> ACC Calculate accuracy using the true values (ty) and predicted values (pv). """ if len(ty) != len(pv): raise ValueError("len(ty) must equal to len(pv)") total_correct = total_error = 0 for v, y in zip(pv, ty): if y == v: ...
def get_scale(a_index, w_index): """ Returns the proper scale for the BBQ multliplication index Parameters ---------- a_index : Integer Current activation bit index w_index : Integer Current weight bit index """ scale = pow(2, (a_index + w_ind...
def find_path(matrix, task): """ Find a all available paths for a next step :param matrix: :param task: :return: """ result = [] goal = (len(matrix) - 1, len(matrix[-1]) - 1) while True: candidate = [] last_point = task[-1] if len(matrix) > last_point[0] + 1:...
def extract(x, *keys): """ Args: x (dict or list): dict or list of dicts Returns: (tuple): tuple with the elements of the dict or the dicts of the list """ if isinstance(x, dict): return tuple(x[k] for k in keys) elif isinstance(x, list): return tuple([xi[k] for ...
def make_cost_matrix(profit_matrix, inversion_function): """ Create a cost matrix from a profit matrix by calling 'inversion_function' to invert each value. The inversion function must take one numeric argument (of any type) and return another numeric argument which is presumed to be the cost invers...
def add_start_end(tokens, start_word="<START>", end_word="<END>"): """ Add start and end words for a caption string Args: tokens: original tokenized caption start_word: word to indicate start of a caption sentence end_word: word to indicate end of a caption sentence Returns: token_...
def pretty_machine_stamp(machst): """Return a human-readable hex string for a machine stamp.""" return " ".join("0x{:02x}".format(byte) for byte in machst)
def _try_compile(source, name): """Attempts to compile the given source, first as an expression and then as a statement if the first approach fails. Utility function to accept strings in functions that otherwise expect code objects """ try: c = compile(source, name, "eval") ...
def is_valid_wager_amount(wager, balance): """ To determine whether the balance is less than or equal to the wager If the wager is less than or equal to the balance Returns true Otherwise, Returns false Returns: The boolean value (boolean) """ if wager <= balance: r...
def _trim_doc(doc): """Trims the quotes from a quoted STRING token (eg. "'''text'''" -> "text") """ l = len(doc) i = 0 while i < l/2 and (doc[i] == "'" or doc[i] == '"'): i += 1 return doc[i:-i]
def getProcVer(version: str) -> str: """Process a version string. This is pretty opinionated. Args: version (str): the version Returns: str: the processed version """ if version.startswith("^"): major = int(version[1:].split(".")[0]) if major > 1990 or major == 0: # if cal ver or zero ver return f"<{...
def matrix_divided(matrix, div): """ Divides all the elements of a matrix by a divisor, result is rounded by two decimal places. Args: matrix: list of lists containing dividends div: divisor Raises: TypeError: matrix must be a matrix (list of lists) of integers...
def quote(s): """Ensure that any string S with white space is enclosed in quotes.""" if isinstance(s, str): if " " in s or len(s.split()) > 1: start, end = s[0], s[-1] if start != end or start not in ('"', "'"): q1s, q1d, q3s, q3d = "'", '"', 3 * "'", 3 * '"' ...
def cyclic_pattern(maxlen, n = 3): """Generate the De Bruijn Sequence (a cyclic pattern) up to `maxlen` characters and subsequences of length `n`. Modified from github.com/longld/peda/. """ charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" k = len(charset) a = [0] * k * n sequ...
def sequence(value): """Return tuple containing value if value is not a sequence. >>> sequence(1) (1,) >>> sequence([1]) [1] """ try: len(value) return value except TypeError: return (value,)
def transformed_name(key: str) -> str: """Generate the name of the transformed feature from original name.""" return f"{key}_xf"
def calc_minutes(hhmm): """Convert 'HH:MM' to minutes""" return int(hhmm[:2]) * 60 + int(hhmm[3:])
def map_wrapper(x): """[summary] Args: x ([type]): [description] Returns: [type]: [description] """ return x[0](*(x[1:]))
def _obj2dict(obj): """ Convert plain object to dictionary (for json dump) """ d = {} for attr in dir(obj): if not attr.startswith('__'): d[attr] = getattr(obj, attr) return d
def formatHex(data, delimiter = " ", group_size = 2): """ formatHex(data, delimiter = " ", group_size = 2): Returns a nice hex version of a string data - The string to turn into hex values delimiter - The delimter between hex values group_size - How many characters do we want in a group? """ if not isinstance(...
def _compute_scale(dimension, spread, special_scale): """See BFaS; p. 83. Parameters ---------- dimension: int Spatial dimensionality of state space model spread: float Spread of sigma points around mean (1; alpha) special_scale: float Spread of sigma points around mean ...
def fmatch(string, match): """Test the forward part of string matches another string or not. """ assert len(string) >= len(match) return string[:len(match)] == match
def extract_capa_units(string): """ Takes a string and returns a list of floats representing the string given. Temporary capacity unit model. Usage:: test_string = 'mAh/g' end_value = extract_value(test_string) print(end_value) # "Gram^(-1.0) Hour^(1.0) MilliAmpere^(1.0)" :para...
def clamp(value: float, minimum: float, maximum: float) -> float: """Clamp a floating point value within a min,max range""" return min(maximum, max(minimum, value))
def list_to_choices(l, sort=True): """Converts a list of strings to the proper PyInquirer 'choice' format Args: l (list): a list of str values sort (bool, optional): Defaults to True. Whether or not the choices should be sorted alphabetically. Returns: list: a l...
def avp_from_rhmax(svp_temperature_min, relative_humidity_max): """ Estimate actual vapour pressure (*e*a) from saturation vapour pressure at daily minimum temperature and maximum relative humidity Based on FAO equation 18 in Allen et al (1998). :param svp_temperature_min: Saturation vapour pressu...
def first(iterable): """Returns the first item of 'iterable' """ try: return next(iter(iterable)) except StopIteration: return None
def pad_dscrp(in_str, out_len=67, pad_char='-'): """Pad DESCRIP with dashes until required length is met. Parameters ---------- in_str : string String to pad. out_len : int, optional The required length. CDBS default is 67 char. pad_char : char, optional Char to pad wi...
def brighten_everything(output_dict, light_profile_mag, bands): """ Brighten everything in a light profile by a given number of mags. Args: output_dict (dict): flat dictionary being used to simulate images light_profile_mag (str): light profile id to be recolored + '-' + mags to brighten. E...
def calculatePoint(listName): """ Point system used to determine wether a card has moved up or down Args: cardName (STR): Name of the list that the card came from Returns: [type]: [description] """ if listName in ["Backlog", "To Do"]: return 1 elif listName in ["In...
def phi_function(n): """ generates a Collatz sequence given a starting number""" result = [n] while n > 1: if n % 2 == 0: n = n / 2 else: n = 3 * n + 1 result.append(n) return result # return len(result)
def sgd_updates(params, grads, stepsizes): """Return a list of (pairs) that can be used as updates in theano.function to implement stochastic gradient descent. :param params: variables to adjust in order to minimize some cost :type params: a list of variables (theano.function will require shared variab...
def text_or_default(element, selector, default=None): """Same as one_or_default, except it returns stripped text contents of the found element """ try: return element.select_one(selector).get_text().strip() except Exception as e: return default
def is_done(value): """ Helper function for deciding if value is sign of successfull update's procession. :param value: value to interpret :returns: True if value is None or equals to "DONE" otherwise False """ return value is None or value == "DONE"
def _remove_prefix(path): """Remove the web/ or build/ prefix of a pdfjs-file-path. Args: path: Path as string where the prefix should be stripped off. """ prefixes = {'web/', 'build/'} if any(path.startswith(prefix) for prefix in prefixes): return path.split('/', maxsplit=1)[1] ...
def x(n): """ Args: n: Returns: """ if n > 0: return n-1 return 0
def expand_dups(hdr_tuples): """ Given a list of header tuples, unpacks multiple null separated values for the same header name. """ out_tuples = list() for (n, v) in hdr_tuples: for val in v.split('\x00'): if len(val) > 0: out_tuples.append((n, val)) retu...
def count_equal_from_left(original: list, new: list) -> int: """ Count the number of equal elements starting from the element with index 0. """ for index, (e1, e2) in enumerate(zip(original, new)): if e1 != e2: return index return min(len(original), len(new))
def rivers_with_station(stations): """Given a list of stations, return a alphabetically sorted set of rivers with at least one monitoring station""" river_set = set() for station in stations: river_set.add(station.river) river_set = sorted(river_set) return river_set
def int_converter(value): """To deal with Courtney CTD codes""" return int(float(value.split(":")[-1].strip()))
def Data(url,data): """ Check url and data path """ if url.endswith('/') and data.startswith('/'): return url[:-1] + "?" + data[1:] if not url.endswith('/') and data.startswith('/'): return url + "?" + data[1:] if url.endswith('/') and not data.startswith('/'): return url[:-1] + "?" + data else: return url +...
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Backwards compatible function; Python 3.5+ equivalent of foo = {**x, **y, **z} """ result = {} for dictionary in dict_args: resu...
def get_tokens_list_from_column_list(column_name_list: list, delimiter: str = '!!') -> list: """Function that returns list of tokens present in the list of column names. Args: column_name_list: The list of column name strings. delimiter: delimiter seperating tok...
def compute_expected_salary(salary_from, salary_to, **kwargs): """Compute and return expected salary. Expected salary compute using the "from" & "to" salary fields of the vacancy. Giving "from" and "to," fields, calculate the expected salary as an average. Giving only "from", multiply by 1.2, else ...
def list_duplicates_of(seq, item): """ Predicts the indexes of duplicate elements inside a list args: -seq - List containing repeated elements -item - Repeated element returns: A list containing the index numbers of the duplicate elements inside the list, 'seq' """ start_at = -1 lo...
def binary_search(lo, hi, condition): """Binary search.""" # time complexity: O(log N) # space complexity: O(1) # dep: condition() # keep looping as long as the substring exists while lo <= hi: mid = (lo + hi) // 2 # the int division result = condition(mid) if ...
def solution(array): """ Finds the number of combinations (ai, aj), given: - ai == 0 - aj == 1 - j > i Time Complexity: O(n), as we go through the array only once (in reverse order) Space Complexity O(1), as we store three variables and create one iterator """ result = 0 count = 0 ...
def comp (a, b): """compare two arrays""" if len(a) != len(b): return False for e in zip(a, b): if e[0] != e[1]: return False return True
def parse_STATS_header(header): """ Extract the header from a binary STATS data file. This extracts the STATS binary file header information into variables with meaningful names. It also converts year and day_of_year to seconds at midnight since the epoch used by UNIX systems. @param header : string of...
def _create_partial_storm_id(previous_numeric_id): """Creates partial (primary or secondary) storm ID. :param previous_numeric_id: Integer ID for previous storm. :return: string_id: String ID for new storm. :return: numeric_id: Integer ID for new storm. """ numeric_id = previous_numeric_id + 1...
def read_file(filename): """ Read a file, and return its contents. """ program = None try: with open(filename, 'r') as f: program = f.read() return program except (IOError, OSError) as e: print("Unable to read file: {}".format(e)) return None
def capitalize(txt: str) -> str: """Trim, then turn only the first character into upper case. This function can be used as a colander preparer. """ if txt is None or ( not isinstance(txt, str) and repr(txt) == "<colander.null>" ): return txt txt = str(txt).strip() if txt == ...