content
stringlengths
42
6.51k
def hex_to_address(val): """Converts hex string to a clean Ethereum address. Accepts padded or unpadded values. Returns a 0x formatted address (string). """ return "0x{}".format(val[-40:])
def bind_method(value, instance): """Return a bound method if value is callable, or value otherwise""" if callable(value): def method(*args): return value(instance, *args) return method else: return value
def extract_grid(parameters): """Extract grid space from manually defined search parameters""" grid = {} for c_name, c_type, c_vals in parameters: if c_type == "choice": grid[c_name] = c_vals elif c_type == "fixed": grid[c_name] = [c_vals] else: ra...
def numMatches(query, collection): """returns the number of elements of collection that equal query""" return len([s for s in collection if s == query])
def divide(slc, maxLen): """ Divides a slice into sub-slices based on a maximum length (for each sub-slice). For example: `divide(slice(0,10,2), 2) == [slice(0,4,2), slice(4,8,2), slice(8,10,2)]` Parameters ---------- slc : slice The slice to divide maxLen : int Th...
def vector2d_to_facing(vector): """ Convert a string facing to a vector2d. Parameter --------- vector: vector2d to convert in facing (tuple(int, int)). Return ------ facing: facing <up|down|left|right|up-left|up-right|down-left|down-right>(str). Version ------- Specificati...
def get_nested_keys(obj, key_list): """ Expects dict object and list of keys in respective order, returns tuple >>> get_nested_keys({ 'a': { 'b': { 'c': 1 } }, 'd': 2 }, ['a', 'b', 'c']) ('c', 1) """ if len(key_list) == 1: return (key_list[0], obj[key_list[0]],) elif len(key_list) > 1: return get_nested_key...
def escape_special_characters(s): """Add a backslash before characters that have special meanings in regular expressions. Python does not handle backslashes in regular expressions or substitution text so they must be escaped before processing.""" special_chars = r'\\' new_string = '' for c...
def copy(string, buf, p, p_copy): """Copies the buffer, appends it to both string and buffer, multiplies in prob of copying. Arguments: string : string list. The string you're actually generating buf : string list. The buffer you might copy p : float. The current probability of the string ...
def counter(matrix): """ Counts the number of "islands" or clusters in a matrix. Assumes that the clusters are separated. """ rows = len(matrix) columns = len(matrix[0]) count = 0 for i in range(rows): for j in range(columns): if matrix[i][j] != 0: ...
def generate_report(formulae_occurances, malicious_cells): """ arguments: (1) output from detect_formulae(), (2) output from detect_malicious_cells() returns: if needed, a multi-line-string report, otherwise None """ if len(formulae_occurances) > 0: report = """There were {} formulae pattern...
def format_signoff_user(signoff): """ Format a single user signoff dictionary. Return "<username>" if signoff is valid, and "<username> (revoked)" if the signoff is revoked. """ if signoff["revoked"]: return signoff["user"] + " (revoked)" else: return signoff["user"]
def human_readable_size(num, suffix="B"): """ FROM http://stackoverflow.com/a/1094933/1958900 """ for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, "Yi", suffix)
def make_review_page_url(productId, page=1, reviews_per_page=5): """Make review pagination URL from page and productID""" return ("https://www.decathlon.it/it/ProductAvis_loadPaginationPage?" "product_id={0}&viewSize={1}&viewIndex={2}&" "currentEnvironment=PROD&componentId=ComponentProdu...
def humanbytes(B): """Return the given bytes as a human friendly KB, MB, GB, or TB string""" B = float(B) KB = float(1024) MB = float(KB ** 2) # 1,048,576 GB = float(KB ** 3) # 1,073,741,824 TB = float(KB ** 4) # 1,099,511,627,776 if B < KB: return '{0} {1}'.format(B,'Bytes' if 0...
def getNumericVersion(version_str): """Returns an integer representation of the given version string. The integers generated in this way will match mari.AppVersion.number() in scale. """ if version_str is None: return 0 version_str = version_str.lower() try: maj_str, rest = ...
def is_power_of_two_or_zero(x): """ Determine if an input is zero or a power of two. Alternative, determine if an input has at most 1 bit set. """ return (x & (~x + 1)) == x
def transit_x_axis_intercept(px: float, py: float, ox: float, oy: float) -> float: """Given an object at position px, py and an observer as ox, oy this returns the value on the x axis of the transit line.""" x = px + py * (ox - px) / (py - oy) return x
def get_key_from_line(line): """ Tries to extract the key from the line :param line: unicode string :return: unicode string: the key or None """ if line.find("#") != 0 or line.find("!") != 0: index_key_end = line.find("=") while (index_key_end > 0) and (line[index_key_end - 1] =...
def maxProfit(prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 max_profit = 0 buying_price = prices[0] for i in range(1, len(prices)): if (prices[i]-buying_price > 0): max_profit = max(max_profit, prices[i]-buy...
def ema(L, alpha=None): """ here we use 'exponential moving average' to predict the next time period data value # EMA Formula: X(0),X(1),X(2),...,X(t-1) : data-sets total with "t" time-period-points EMA(1) = X(0) // initial point -> 1 terms EMA(2) = EMA(1) + alpha*(X...
def copy_files(infiles, outfiles): """ """ inputs = infiles outputs = outfiles options = { 'cores': 1, 'memory': '4g', 'account': 'NChain', 'walltime': '01:00:00' } spec = '' for inf, outf in zip(infiles, outfiles): spec += "cp {} {}\n".format(inf,out...
def get_document_segmentation_details_url(document_id: int, project_id, action='segmentation') -> str: """ Generate URL to get the segmentation results of a document. :param document_id: ID of the document as integer :param project_id: ID of the project :param action: Action from where to get the r...
def read_param(params, key, default): """Read and return a parameter from a dict. If the key `key` is absent from the dict `params`, return the default value `default` instead. Parameters ---------- params : dict A dict containing parameters. key : str Name of the parameter...
def prependPackageToClassnames(urls, packageName): """Take web.py formatted url/endpoint tuples and prepend a packageName to each of the endpoint classnames, e.g. ('/Test/(.*)', 'test') becomes ('/Test/(.*)', 'Test.test') >>> prependPackageToClassnames(('/Test/(.*)', 'test'), 'PACKAGE') ('/Test/(.*)', 'PACKAGE....
def _FindNeighbor(invalid_run_point, all_builds): """Looks for a neighbor to replace or stop the analysis. Args: invalid_run_point (int): The build number with invalid artifact. all_builds (list): A list of build numbers that have been checked. Returns: New build to check. """ return (invalid_run_po...
def section_start(section, staff, **kwargs): """Handles the "section-start" fragment""" kwargs["section"] = section kwargs["staff"] = staff return kwargs
def gen_v_stmt(q1n, q2n): """ return a string of verify statement. """ return "verify {} {};\n".format(q1n, q2n)
def xor_same_length(input_bytes_1: bytes, input_bytes_2: bytes): """Takes in a two byte strings. Outputs the xor of those two strings""" list_of_chars = [(a ^ b) for (a, b) in zip(input_bytes_1, input_bytes_2)] return bytes(list_of_chars)
def MAX_CMP(x, y): """Return max comparison result.""" if not isinstance(x, (int, float)) or not isinstance(y, (int, float)): return 0 return x - y
def key_description(character): """generate a readable description for a key""" ascii_code = ord(character) if ascii_code < 32: return 'Ctrl+%c' % (ord('@') + ascii_code) else: return repr(character)
def islazy(f): """Internal. Return whether the function f is marked as lazy. When a function is marked as lazy, its arguments won't be forced by ``lazycall``. This is the only effect the mark has. """ # special-case "_let" for lazify/curry combo when let[] expressions are present return hasattr...
def _find_full_periods(events, quantity, capacity): """Find the full periods.""" full_periods = [] used = 0 full_start = None for event_date in sorted(events): used += events[event_date]['quantity'] if not full_start and used + quantity > capacity: full_start = event_date...
def get_block_name(num_block, type=0, weight=True, layer=0): """ Arguments --------- num_block -> "block_index" type -> "0: norm_layer1, 1: multi_head_attn, 2:norm_layer2, 3:mlp_block" weight -> "True for weight and False for bias" layer -> "0: qkv for attn and fc1 for mlp" "1: proj for attn...
def readable_bool(b): """Takes a boolean variable and returns "yes" for true and "no" for false as a string object. :param b: boolean variable to use """ if b: return "yes" else: return "no"
def net_gain(volume: float, initial_price: float, final_price: float) -> str: """Devuelve la ganacia de la inversion Argumentos: volume -- cantidad de items comprados initial_price -- precio unitario del item al momento de la compra (en GRO) final_price -- precio unitario del item al momento de la ...
def neighbor_idcs(x, y): """ Input x,y coordinates and return all the neighbor indices. """ xidcs = [x-1, x, x+1, x-1, x+1, x-1, x, x+1] yidcs = [y-1, y-1, y-1, y, y, y+1, y+1, y+1] return xidcs, yidcs
def error_type(err: Exception) -> str: """ Returns the type of the exception as a string. """ return type(err).__name__
def get_choice_label(label, data_dictionary, language=None): """ Return the label matching selected language or simply just the label. """ if isinstance(label, dict): languages = [i for i in label.keys()] _language = language if language in languages else \ data_dictionary.ge...
def get_url_id(url): """ https://www.zhihu.com/question/xxxxxx/xwf3qwrvq :param url: :return: xxxxxxx """ x = url.split('?')[0] s = x.replace('//', 'a') s = s.split('/') if len(s) < 3: return None return s[2]
def get_list_url(list_name): """Get url from requested list name. Parameters ---------- list_name : str Name of the requested list. Valid names are: *nea_list, risk_list, risk_list_special, close_approaches_upcoming, close_approaches_recent, priority_list, priority_list_faint, ...
def openai(base_lr, num_processed_images, num_epochs, num_warmup_epochs): """ Learning rate scheduling strategy from openai/glow :param base_lr: base learning rate :type base_lr: float :param num_processed_images: number of processed images :type num_processed_images: int :param num_epochs:...
def increment_version(current): """ Returns current version incremented by 1 minor version number """ minor = current.split('.')[-1] major = '.'.join(current.split('.')[:-1]) inc_minor = int(minor) + 1 return major + '.' + str(inc_minor)
def get_rank_value(rank): """Given rank in integer, return the 2 digits string representation 14 -> "14" 2 -> "02" """ if rank < 10: return "0" + str(rank) else: return str(rank)
def T_Tstar(M, gamma): """Static temperature ratio for flow with heat addition (eq. 3.86) :param <float> M: Initial Mach # :param <float> gamma: Specific heat ratio :return <float> Static temperature ratio T/Tstar """ return M ** 2 * ((1.0 + gamma) / (1.0 + gamma * M ** 2)) ** 2
def check_file(file, key_words, black_list): """ Check the file against a black list as well as check if it has keywords in it. Parameters ---------- file : string filename to check key_words : list list of strings required to be in file name black_list : list li...
def rflink_to_brightness(dim_level: int) -> int: """Convert RFLink dim level (0-15) to 0-255 brightness.""" return int(dim_level * 17)
def decimal_to_ternary(d, t_len=3): """ Convert a decimal to a ternary key. """ t = [0] * t_len for p in range(t_len, 0, -1): # print(d, p, 3**(p-1), d // (3**(p-1)) ) tp = d // 3 ** (p - 1) t[p - 1] = tp d -= tp * 3 ** (p - 1) return t
def _TestRangeForShard(total_shards, shard_index, num_tests): """Returns a 2-tuple containing the start (inclusive) and ending (exclusive) indices of the tests that should be run, given that |num_tests| tests are split across |total_shards| shards, and that |shard_index| is currently being run. """ assert n...
def replace(data, replacements): """ Given a list of 2-tuples (old, new), performs all replacements on the data and returns the result. """ for old, new in replacements: data = data.replace(old, new) return data
def padovan(number: int) -> int: """ Examples: >>> assert padovan(2) == 1 >>> assert padovan(5) == 3 """ result = [0, 1, 1] for c in range(2, number): result.append(result[0] + result[1]) del result[0] return result[0] + result[1]
def mass_surface_balsa_monokote_cf( chord, span, mean_t_over_c=0.08 ): """ Estimates the mass of a lifting surface constructed with balsa-monokote-carbon-fiber construction techniques. Warning: Not well validated; spar sizing is a guessed scaling and not based on structural analysis....
def model(x, nu, a): """ Model for fitting Figure 3. Args: x (numpy array): x coordinates nu (float): the exponent a (float): the constant of proportionality Returns: yy (numpy array): the y values for the model y = ax^{nu} """ yy = a * x ** nu return yy
def is_channel(string): """Check if a string is a channel name. Returns true if the argument is a channel name, otherwise false. """ return string and string[0] in "#&+!"
def tag_value(name_tag): """ docker-py provides "RepoTags", which are strings of format "<image name>:<image tag>" We want just the part after the colon. """ return name_tag.rsplit(":", 1)[1]
def DictToArgs(Dict): """ Dictionary to Args Give a dictionary of keys and values to convert it to a url applyable string {'a': 'val', 'b': 'val2'} >> ?a=val&b=val2 """ args = [] for item in Dict: args.append(item + "=" + str(Dict[item])) args = "&".join(args) return "?...
def steps_taken(offsets): """Calculate the steps needed to traverse an offset maze.""" # Put the offsets in a list value_list = offsets.split('\n') # Starting at [0] follow the offsets, adding one to each when used list_position = 0 steps = 0 while list_position < len(value_list): ...
def _recovery(state_old, state_new): """ Parameters ---------- state_old : dict or pd.Series Dictionary or pd.Series with the keys "s", "i", and "r". state_new : dict or pd.Series Same type requirements as for the `state_old` argument in this function apply. Returns ...
def middle_drop(progress): """ Returns a linear value with a drop near the middle to a constant value for the Scheduler :param progress: (float) Current progress status (in [0, 1]) :return: (float) 1 - progress if (1 - progress) >= 0.75 else 0.075 """ eps = 0.75 if 1 - progress < eps: ...
def zero1(mat): """ O(M * N) run-time / O(N) space solution Args: mat ([type]): [description] """ def zero_column(mat, col): for row in range(len(mat)): mat[row][col] = 0 def zero_row(mat, row): for col in range(len(mat[0])): mat[row][c...
def _as_text(s): """Converts a byte/string into string.""" if isinstance(s, bytes): return s.decode('utf-8') return s
def _GetExceptionName(error): """Gets a friendly exception name for the given error. Args: error: An exception class. Returns: str, The name of the exception to log. """ if error: try: return '{0}.{1}'.format(error.__module__, error.__name__) # pylint:disable=bare-except, Never want to...
def i2osp(x: int, xlen: int) -> bytes: """ Convert a nonnegative integer `x` to an octet string of a specified length `xlen`. https://tools.ietf.org/html/rfc8017#section-4.1 """ return x.to_bytes(xlen, byteorder='big', signed=False)
def get_images_for_offer(item, *args, **kwargs): """ Parse images from offer :param item: Tag html found by finder in html markup :return: List of image urls :rtype: list """ images_links = [] if item: images = item.find_all('img') for img in images: images_links...
def func_name_is_class_init(name): """Return True if |name| is that of a class' __init__ method.""" # Python 3's MAKE_FUNCTION byte code takes an explicit fully qualified # function name as an argument and that is used for the function name. # On the other hand, Python 2's MAKE_FUNCTION does not take any name ...
def get_qlabel(qckeyword, calcindex): """ Returns a string that can be used as a label for a given quantum chemistry calculation with qckeyword specified by the user and calculation index. The string is based on the dependencies of the corresponding calculation. """ calcs = qckeyword.split('...
def _get_bc_count(sample_name, bc_count, sample_run): """Retrieve barcode count for a sample :param sample_name: sample name :param bc_count: parsed option passed to application :param sample_run: sample run object :returns: barcode count or None""" if isinstance(bc_count, dict): if sa...
def invertM(coorSM, maxM): """ Invert M axis. :param coorSM: coordinate of vector for M inverted axes. :param maxS: value representing end of estatic axis. :param maxM: value representing end of mobile axis. :return: SM coordinate on S axis and inverted M axis. """ return int(coorSM - m...
def remove_underscores(value): """ Removes the underscores from a given string """ return value.replace("_", " ").title()
def split_array(arr, n): """ Split an input array into multiple sub-arrays of maximum length n :return: Array of arrays with maximum length n >>> split_array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 13) [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [14]] """ return [arr[i:i+n] for...
def identify_format(resource): """ " Takes incoming "resource" data from a POST to the indexer and identifies the format of that data. """ if resource.get("paragraph"): return "ocr" elif resource.get("document"): return "capturemodel" return
def get_rows(results): """Return the rows object from a Google Analytics API request. :param results: Google Analytics API results set :return: Python dictionary containing rows data """ if results['rows']: return results['rows']
def is_num(string): """Return whether or not a string can be interpreted as an integer.""" try: int(string) except ValueError: return False return True
def validate_blacklist(password): """ It does not contain the strings ab, cd, pq, or xy """ for blacklisted in ['ab', 'cd', 'pq', 'xy']: if blacklisted in password: return False return True
def arqivoExiste(nome): """ :param nome: nome do arquivo gerado :return: se existe ou nao """ try: a = open(nome, 'rt') a.close() except FileNotFoundError: return False else: return True
def start_fingerprint_client(prefix, xid, wid, fingerprint_server): """Starts a fingerprint client. Args: prefix: String, the prefix of the server. xid: Integer, the experiment id. wid: Integer, the work unit id. fingerprint_server: Fingerprint server. In distributed setting, the client shoul...
def is_iterable(var): """Return True if the given is list or tuple.""" return (isinstance(var, (list, tuple)) or issubclass(var.__class__, (list, tuple)))
def filter_vals(obj, vals): """Filter a dictionary by values. Args: obj (dict): The dictionary to filter. Returns: obj (dict): The filtered dict. """ if obj is None or not isinstance(vals, list): return obj newdict = {} for k, v in list(obj.items()): if v in...
def run_dir_name(run_num): """ Returns the formatted directory name for a specific run number """ return "run{:03d}".format(run_num)
def transform_key(key): """ Changes keys of tabular output to the names used in the JSON output. Args: key (str): The key to change. Returns: str: The new key name. """ key = key.lower().strip() key_substition = {'uuid' : 'archive_uuid', 'cluster uuid...
def one_pattern(board, row): """Return one pattern from board""" return "".join([board[i][j] for (i, j) in row])
def oneline(value): """ Replace each line break with a single space """ return value.replace('\n', ' ')
def dic_sum_up_lengths(in_dic): """ Given a dictionary with strings or numbers, sum up the numbers / string lengths and return the total length. Currently works for integer numbers and strings. >>> in_dic = {'e1': 5, 'e2': 10} >>> dic_sum_up_lengths(in_dic) 15 >>> in_dic = {'e1': 'ACGT'...
def memoized_can_sum(numbers, target): """ Parameters ---------- numbers : list of integers target : int target sum Returns ------- bool Boolean representing whether subsets exist which are equal to each other >>> memoized_can_sum([1, 2, 3, 4], 5) True """...
def round_up(n: int, m: int) -> int: """Round the given number *n* up to the nearest multiple of *m*. :param int n: number to round :param int m: multiple to round to :return: n rounded up to a multiple of m. :rtype int: """ return (n + m - 1) & ~(m - 1)
def _merge_columns(grid, columns_to_merge): """A helper function that merges columns in a grid. grid: [[str]] columns_to_merge: [(col1, col2)] The columns must not overlap. Also, they must be increasing. So if we had something like: [(x,y), (w,z)], x<y<w<z must hold. IMPORT...
def ceil_div(x, y): """ same as int(ceil(float(x)/y)), so no need to import math lib """ return -(-x // y)
def is_instance_or_subclass(val, class_) -> bool: """Return True if ``val`` is either a subclass or instance of ``class_``.""" try: return issubclass(val, class_) except TypeError: return isinstance(val, class_)
def get_conv_shape_1axis(image_shape, kernel_shape, border_mode, subsample): """ This function compute the output shape of convolution operation. Parameters ---------- image_shape: int or None. Corresponds to the input image shape on a given axis. None if undefined....
def moving_average(ys, window=6): """ Calculates moving average window of the given list of values. Args: ys (list[float]): list of values window (int): size of the window Returns: values (list[float]): list of values as moving average from `ys`. Same size as `ys`. ...
def correlate_dicts(dicts, key): """Correlate several dicts under one superdict. If you have several dicts each with a 'name' key, this puts them in a container dict keyed by name. Example:: >>> d1 = {"name": "Fred", "age": 41} >>> d2 = {"name": "Barney", "age": 31} >>> flint...
def operand_size_to_str(size: int) -> str: """ Gets the assembly operand type for a given size in bytes, in Intel syntax. """ if size == 1: return "byte" if size == 2: return "word" if size == 4: return "dword" if size == 8: return "qword" if size == 16: ...
def fix_negatives(num): """ Some scopes represent negative numbers as being between 128-256, this makes shifts those to the correct negative scale. :param num: an integer :return: the same number, shifted negative as necessary. """ if num > 128: return num - 255 else: re...
def adjacentMultiply(n,r): """Takes in a really large number, n, and looks for the r-th adjacent digits with the largest product""" maxProd = 1 nStr = str(n) nStrLen = len(nStr) for chunkIdx in range(nStrLen - r + 1): subStr= nStr[chunkIdx:chunkIdx+r] subProd=1 for di...
def replicated_data(index): """Whether data[index] is a replicated data item""" return index % 2 == 0
def merge_cms(cm1, cm2): """ Merge two confusion matrices. Parameters ---------- cm1 : dict Confusion matrix which has integer keys 0, ..., nb_classes - 1; an entry cm1[i][j] is the count how often class i was classified as class j. cm2 : dict Another confusion m...
def translate_bbox(bbox, translation): """ Translate given bbox by the amount in translation. Parameters ---------- bbox: tuple tuple of integers defining coordinates of the form (x1, y1, x2, y2, x3, y3, x4, y4). translation: tuple tuple of integer...
def Declares(node): """Variable scope in lambda function If variables Examples: >>> print(matlab2cpp.qscript("x = 4; f = @() x+2")) x = 4 ; f = [x] () {x+2 ; } ; """ # handle in Lambda return ""
def addPaddingToBase64String(base64String: str) -> str: """ Return a padded version of a base64String that is not long enough to be decoded by base64.b64decode() :param base64String: The base64String that is not long enough to be decoded by base64.b64decode() :type base64String: str :return: base64...
def format_number(num: float) -> str: """ Format strings at limited precision :param num: anything that can print as a float. :return: str I've read articles that recommend no more than four digits before and two digits after the decimal point to ensure good svg rendering. I'm being generous a...