content
stringlengths
42
6.51k
def mse_node(w_samples, y_sum, y_sq_sum): """Computes the variance of the labels in the node Parameters ---------- w_samples : float Weighted number of samples in the node y_sum : float Weighted sum of the label in the node y_sq_sum : float Weighted sum of the squared ...
def read_file(file_name, mode='r'): """ read file content """ try: with open(file_name, mode) as f: content = f.read() except Exception: return None return content
def singlyfy_parameters(parameters): """ Makes a cgi-parsed parameter dictionary into a dict where the values that are just a list of a single value, are converted to just that single value. """ for key, value in parameters.items(): if isinstance(value, (list, tuple)) and len(value) == 1: ...
def char_formatter(line): """ Returns the char for the special offers """ return ''.join([ch for ch in line if not ch.isdigit()])
def collate_metrics(keys): """Collect metrics from the first row of the table. Args: keys (List): Elements in the first row of the table. Returns: dict: A dict of metrics. """ used_metrics = dict() for idx, key in enumerate(keys): if key in ['Method', 'Download']: ...
def is_prime(n): """Check if n is prime or not.""" if (n < 2): return False for i in range(2, n + 1): if (i * i <= n and n % i == 0): return False return True
def average_precision(gt, pred,maxnum=-1): """ Computes the average precision. This function computes the average prescision at k between two lists of items. Parameters ---------- gt: set A set of ground-truth elements (order doesn't matter) pred: list A list of predicted elements (orde...
def patron_ref_builder(loan_pid, loan): """Return the $ref for given loan_pid.""" return {"ref": "{}".format(loan_pid)}
def format_callback_to_string(callback, args=None, kwargs=None): """ Convert a callback, its arguments and keyword arguments to a string suitable for logging purposes :param ~collections.abc.Callable,str callback: The callback function :param list,tuple args: The callback arguments ...
def GetSettingTemplate(setting): """Create the template that will resolve to a setting from xcom. Args: setting: (string) The name of the setting. Returns: A templated string that resolves to a setting from xcom. """ return ('{{ task_instance.xcom_pull(task_ids="generate_workflow_args"' ')....
def binary_search_recursive(array: list, target: int) -> int: """ binary search using recursion """ if len(array) == 0: return -1 mid = len(array) // 2 if array[mid] == target: return mid elif array[mid] < target: return binary_search_recursive(array[mid + 1:], targe...
def is_valid_ip_prefix(prefix, bits): """Returns True if *prefix* is a valid IPv4 or IPv6 address prefix. *prefix* should be a number between 0 to *bits* length. """ try: # Prefix should be a number prefix = int(prefix) except ValueError: return False # Prefi...
def SecureStringsEqual( a, b ): """Returns the equivalent of 'a == b', but avoids content based short circuiting to reduce the vulnerability to timing attacks.""" # Consistent timing matters more here than data type flexibility if not ( isinstance( a, str ) and isinstance( b, str ) ): raise TypeError( "inpu...
def get_ethnicity(x): """ returns the int value for the ordinal value ethnicity """ if x == 'White': return 1 elif x == 'Black': return 2 elif x == 'Native American': return 3 elif x == 'Asian': return 4 else: return 0
def get_station(seedid): """Station name from seed id""" st = seedid.rsplit('.', 2)[0] if st.startswith('.'): st = st[1:] return st
def _isFunction(v): """ A utility function to determine if the specified value is a function. """ if v==None: return False return hasattr(v, "__call__")
def get_scalar(default_value, init_value = 0.0): """ Return scalar with a given default/fallback value. """ return_value = init_value if default_value is None: return return_value return_value = default_value return return_value
def merge_dicts(*source_dicts): """Create a new dictionary and merge sources into it.""" target = {} for source in source_dicts: target.update(source) return target
def difference(n): """ This program will return differnce between square of sum and sum of square. """ sumOfSquare = 0 squareOfSum = 0 for i in range(n+1): squareOfSum += i sumOfSquare += i ** 2 return squareOfSum ** 2 - sumOfSquare
def write_at_index(array, index, value): """Creates a copy of an array with the value at ``index`` set to ``value``. The array is extended if needed. Parameters: array (tuple): The input array index (int): The index in the array to write to value (value): The value to write Ret...
def mergesort(lst): """Perform merge sort algorithm.""" def divide(lst): """Divide.""" if len(lst) <= 1: return lst middle = len(lst) // 2 left = lst[:middle] right = lst[middle:] left = divide(left) right = divide(right) return merg...
def get_str_bytes_length(value: str) -> int: """ - source: https://stackoverflow.com/a/30686735/8445442 """ return len(value.encode("utf-8"))
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category...
def is_cjmp(block): """Verify whether the block contains conditional jump. Args: block (list): a list of instructions (dict) belonging to one block Returns: bool: does the code block contain conditional jump? """ return (len(block[-1]["successors"]) == 2 and block[-1]["...
def openappend(file): """Open as append if exists, write if not.""" try: output = open(file, 'a') except Exception: try: output = open(file, 'w') except Exception: return 'error' return output
def findInter(next_event, event_atime, idx, end): """ Function: findInter Description: The helper iterator function to find the intersection Input: next_event - available time based on the next event event_atime - a list of available time based on events on date i...
def _format_price_str(price_string): """ Takes a string on the format '17 000:-...' and returns it on the format '17000'. """ price_string = price_string.split(':')[0] return price_string.replace(" ", "")
def check_error(error_code): """Converts the UCLCHEM integer result flag to a simple messaging explaining what went wrong" Args: error_code (int): Error code returned by UCLCHEM models, the first element of the results list. Returns: str: Error message """ errors={ -1:"...
def get_gcd(x, y): """Calculate the greatest common divisor of two numbers.""" if y > x: x, y = y, x r = x % y if r == 0: return y else: result = get_gcd(y, r) return result
def _norm(x, max_v, min_v): """ we assume max_v > 0 & max_v > min_v """ return (x-min_v)/(max_v-min_v)
def inverse_linked_list(list_to_inverse, next_node_property_name="next"): """ A linked list inversor. No new nodes are created. @param list_to_inverse: The linked list to inverse. @param next_node_property_name: The name of property pointing to the next node. @return: The head of the inversed l...
def handle_exception(error: Exception): """When an unhandled exception is raised.""" message = "Error: " + getattr(error, 'message', str(error)) return {'message': message}, getattr(error, 'code', 500)
def input_parameter_name(name, var_pos): """Generate parameter name for using as template input parameter names in Argo YAML. For example, the parameter name "message" in the container template print-message in https://github.com/argoproj/argo/tree/master/examples#output-parameters. """ return ...
def youngs_modulus(youngs_modulus): """ Defines the material properties for a linear-elastic hydrogel (such as Matrigel) hydrogel with a poission ratio of 0.25 (see [Steinwachs,2015], in this case Youngsmodulus equals K_0/6). Args: youngs_modulus(float) : Young's modulus of the material in Pasc...
def condensate_abovedew(Bg, Bgi, Gp, Gpi): """ Calculate the parameters for material balance plot of gas-condensate reservoirs above dewpoint pressure Input: array: Bg, Gp float: initial Bg, initial Gp Output: F (array), Eg (array) """ Eg = Bg - Bgi F = Bg * (Gp - Gpi) ret...
def capture(func): """Return the printed output of func(). ``func`` should be a function without arguments that produces output with print statements. >>> from sympy.utilities.iterables import capture >>> from sympy import pprint >>> from sympy.abc import x >>> def foo(): ... print...
def basic_pyxll_function_1(x, y, z): """returns (x * y) ** z """ return (x * y) ** z
def contains_sublist(list, sublist): """Return whether the given list contains the given sublist.""" def heads_match(list, sublist): if sublist == (): return True elif list == (): return False else: head, tail = list subhead, subtail = subl...
def filter_opt(opt): """Remove ``None`` values from a dictionary.""" return [k for k, v in opt.items() if v]
def common_get(list_header): """ :param list_header: list of training & testing headers :return: common header """ golden_fea = ["F116", "F115", "F117", "F120", "F123", "F110", "F105", "F68", "F101", "F104", "F65", "F22", " F94", "F71", "F72", "F25", "F3-", "F15", "F126", "F41", "...
def anagram_solution_4(words): """ Count and Compare Complexity O(n) Although the last solution was able to run in linear time, it could only do so by using additional storage to keep the two lists of character counts. In other words, this algorithm sacrificed space in order to gain ...
def split_and_join(line: str) -> str: """ >>> split_and_join('this is a string') 'this-is-a-string' """ return "-".join(line.split())
def expand_dict(init_dict): """ Expand dict keys to full names :param init_dict: Initial dict :type: dict :return: Dictionary with fully expanded key names :rtype: dict """ # Match dict for print output in human readable format m = {'h': 'health', 's': 'status', 'ow': 'owner', 'owp...
def ipv4_address_validator(addr): """ Regex to validate an ipv4 address. Checks if each octet is in range 0-255. Returns True/False """ import re pattern = re.compile( r"^([1]?\d?\d|2[0-4]\d|25[0-5])\.([1]?\d?\d|2[0-4]\d|25[0-5])\.([1]?\d?\d|2[0-4]\d|25[0-5])\.([1]?\d?\d|2[0-4]\d|25...
def find_odd_pair_product(someList=None): """ Find pair of integers in list whose product is odd, and returns a list of tuples, where a tuple is made up of both integers whose product is odd. :param someList: List to find pairs within. :return: List of pair-tuples. """ listPair = [] ...
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc reference: http://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 10...
def sign(number): """Returns the sign of a given number.""" if number != 0: return number / abs(number) else: return 0
def get_duplicates(setlist): """ Takes a list of sets, and returns a set of items that are found in more than one set in the list """ duplicates = set() for i, myset in enumerate(setlist): othersets = set().union(*setlist[i+1:]) duplicates.update(myset & othersets) return dup...
def reference_swap(my_dict: dict) -> dict: """ swap keys with values, note values must be immutable """ return {v: k for k, v in my_dict.items()}
def single_v_L(v_L0, L): """ Calculates velocity of a single-phase flow at the given position L along the wellbore. See the first equation of the system. Args: v_L0 (float) - boundary condition for velocity. Can assume any positive value. Returns: ...
def static_url(context, static_file_path): """Filter for generating urls for static files. NOTE: you'll need to set app['static_root_url'] to be used as the root for the urls returned. Usage: {{ 'styles.css'|static }} might become "/static/styles.css" or "http://mycdn.example.com...
def add_sign(number): """Return signed string: x -> '+x' -x -> '-x' 0 -> '0' """ if number > 0: return f'+{number}' else: return str(number)
def normalise(matrix): """Normalises the agents' cumulative utilities. Parameters ---------- matrix : list of list of int The cumulative utilities obtained by the agents throughout. Returns ------- list of list of int The normalised cumulative utilities (i.e., utility share...
def flatten_lists(lists: list) -> list: """Removes nested lists""" result = list() for _list in lists: _list = list(_list) if _list != []: result += _list else: continue return result
def sieve_eratosthenes(range_to): """ A Very efficient way to generate all prime numbers upto a number. Space complexity: O(n) Time complexity: O(n * log(logn)) n = the number upto which prime numbers are to be generated. """ range_to=int(range_to) # creating a boolean list first pri...
def timeElapsed(seconds, opts=None): """Time Elapsed Returns seconds in a human readable format with several options to show/hide hours/minutes/seconds Arguments: seconds (uint): The seconds to convert to ((HH:)mm:)ss opts (dict): Optional flags: show_minutes: default True show_seconds: default Tr...
def readDirective(s): """Reads a directive line from forcefield, itp, or rtp file.""" # Remove comments, then split normally sline = s.split(';')[0].split() if len(sline) == 3 and sline[0] == '[' and sline[2] == ']': return sline[1] else: return ''
def summation(num): """Return sum of 0 to num.""" x = [i for i in range(num + 1)] return sum(x)
def resource_config_is_unchanged_except_for_tags(original_config, new_config, except_tags=[]): """ Recursively compare if original_config is the same as new_config except for the except_tags """ if type(original_config) is str: if original_config...
def get_option_list(string, all_value='all'): """ Method to switch the string of value separated by a comma into a list. If the value is 'all', keep all. :param string: string to change :param all_value: value to return if all used :return: None if not set, all if all, list of value otherwise ...
def to_words(node): """Generates a word list from all paths starting from an internal node.""" if not node: return [''] return [(node[0] + word) for child in node[1] for word in to_words(child)]
def get_delete_op(op_name): """ Determine if we are dealing with a deletion operation. Normally we just do the logic in the last return. However, we may want special behavior for some types. :param op_name: ctx.operation.name.split('.')[-1]. :return: bool """ return 'delete' == op_name
def ix(dot,orb,spin): """ Converts indices to a single index Parameters ---------- dot : int Dot number orb : int Orbital number (0 for p- and 1 for p+) spin : int 0 for spin down, 1 for spin up. Returns ------- int """ return 4*dot+2*orb+spin
def url_filter(url_list: list) -> list: """Filters out URLs that are to be queried, skipping URLs that responded with 204 HTTP code. Args: url_list: List of URL with metadata dict object. Returns: List of URL with metadata dict object that need to be queried. ""...
def auth_str_equal(provided, known): """Constant-time string comparison. :params provided: the first string :params known: the second string :returns: True if the strings are equal. This function takes two strings and compares them. It is intended to be used when doing a comparison for authe...
def add(x, y, z=0): """Add two (or three) objects""" return x + y + z
def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_...
def weighted_sum(predictions, weight=None): """Returns a weighted sum of the predictions """ return sum([prediction["prediction"] * prediction[weight] for prediction in predictions])
def real_diff(diff): """ :param diff: The diff to check. :type diff: str :return: True if diff is real (starts with ' ') :rtype: bool """ return not diff.startswith(' ')
def super_digit(n: int) -> int: """Return the result of summing of a number's digits until 1 digit remains.""" ds = n % 9 if ds: return ds return 9
def make_general_csv_rows(general_csv_dict): """ Method for make list of metrics from general metrics dict. Rows using in general metrics writer :param general_csv_dict: dict with all metrics :type general_csv_dict: dict :return: all metrics as rows :rtype: list """ rows = [] f...
def hash(h, key): """Function leaves considerable overhead in the grid_detail views. each element of the list results in two calls to this hash function. Code there, and possible here, should be refactored. """ return h.get(key, {})
def up(user_version: int) -> str: """Return minimal up script SQL for testing.""" return f""" BEGIN TRANSACTION; PRAGMA user_version = {user_version}; CREATE TABLE Test (key PRIMARY KEY); COMMIT; """
def vertinds_faceinds(vertex_inds, faces): """ Return indices of faces containing any of `vertex_inds` Parameters ---------- vertex_inds : sequence length N. Indices of vertices faces : (F, 3) array-like Faces given by indices of vertices for each of ``F`` faces Returns ----...
def extract_label(label): """Get the layer number, name and shape from a string. Parameters ---------- label: str Specifies both the layer type, index and shape, e.g. ``'03Conv2D_3x32x32'``. Returns ------- : tuple[int, str, tuple] - layer_num: The index of the la...
def binary_fn(gold, pred): """ if there is any member of gold that overlaps with no member of pred, return 1 else return 0 """ fns = 0 for p in gold: fn = True for word in p: for span in pred: if word in span: fn = False ...
def I(x, A, s, L): """I(x) is the initial condition, meaning t=0 x is a variable in space A is the amplitude s is the intersection L is the length To form a "triangle-shaped" initial condition we return the value I(x) of the 1st linear function in the eq...
def Windowize(windowSize, individual): """Reduce individual size by summing the number of mutations in a window and replacing all values with that sum.""" reducedIndividual = [0] j = 0 for i in range(len(individual)): reducedIndividual[j] += individual[i] if((i+1)%windowSi...
def escape_html(s, quote = True): """escape HTML""" s = s.replace("&", "&amp;").replace("<", "&lt;") \ .replace(">", "&gt;") if quote: s = s.replace('"', "&quot;").replace("'", "&apos;") return s
def rank_results(results): """Ranks the results of the hyperparam search, prints the ranks and returns them. Args: results (list): list of model configs and their scores. Returns: list: the results list reordered by performance. """ ranking = sorted(results, key=lambda k: k["score"...
def sort_latency_keys(latency): """The FIO latency data has latency buckets and those are sorted ascending. The milisecond data has a >=2000 bucket which cannot be sorted in a 'normal' way, so it is just stuck on top. This function resturns a list of sorted keys. """ placeholder = "" tmp = [] ...
def capenergy(C,v): """ capenergy Function A simple function to calculate the stored voltage (in Joules) in a capacitor with a charged voltage. Parameters ---------- C: float Capacitance in Farads. v: float Voltage across capaci...
def maximumGap(arr): """ :type arr: List[int] :rtype: int """ if len(arr) < 2: return 0 min_v, max_v = min(arr), max(arr) if max_v - min_v < 2: return max_v - min_v min_gap = max(1, (max_v - min_v) // (len(arr))) # The minimum possible gap sentinel_min, sentinel_ma...
def circ_supply(height: int, nano: bool = False) -> int: """ Circulating supply at given height, in ERG (or nanoERG). """ # Emission settings initial_rate = 75 fixed_rate_blocks = 525600 - 1 epoch_length = 64800 step = 3 # At current height completed_epochs = max(0, h...
def nsplit(seq, n=2): """Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will strings into individual characters. Examples: >>> nsplit('aabbcc') [('a', 'a'), ('b', 'b'), ('c', 'c')] >>> nsplit('aabbcc',n=...
def is_diagonal(A): """Tells whether a matrix is a diagonal matrix or not. Args ---- A (compulsory) A matrix. Returns ------- bool True if the matrix is a diagonal matrix, False otherwise. """ for i in range(len(A)): for j in range(len(A[0])): ...
def parse_visitor_score(d): """ Used to parse score of visiting team. """ string_value = d.get("uitslag", " 0- 0") (_, v) = string_value.replace(" ", "").split("-") return int(v)
def strip_namespace(tag_name): """ Strip all namespaces or namespace prefixes if present in an XML tag name . For example: >>> tag_name = '{http://maven.apache.org/POM/4.0.0}geronimo.osgi.export.pkg' >>> expected = 'geronimo.osgi.export.pkg' >>> assert expected == strip_namespace(tag_name) ...
def school2nation(id_num): """ Takes school id, returns nation id of the school. """ if id_num < 97100000: return id_num // 100000 * 10000 if id_num < 97200000: return 7240000 if id_num < 97400000: return 8400000 return 320100
def einstein_a(freq,line_str,g_up): """ Einstein A from line_str (S_g mu_g^2), freq (MHz) and g_up, as per eq. 6 in www.astro.uni-koeln.de/site/vorhersagen/catalog/main_catalog.shtml """ return 1.16395e-20 * freq**3 * line_str / g_up
def tap(value, interceptor): """Invokes `interceptor` with the `value` as the first argument and then returns `value`. The purpose of this method is to "tap into" a method chain in order to perform operations on intermediate results within the chain. Args: value (mixed): Current value of chain ...
def get_weight_shapes3(num_inputs, layer_sizes, num_outputs, m_trainable_arr, b_trainable_arr): """ see calc_num_weights3 for relevant of suffix """ weight_shapes = [] input_size = num_inputs for i, layer in enumerate(layer_sizes): if m_trainable_arr[i]: weight_shapes.append((input_size, layer)) if b_trai...
def slash_count(l): """Check the slash count""" l= str(l) if l.count('/')<5: return 0 elif l.count('/')>=5 and l.count('/')<=7: return 2 else: return 1
def is_number(s): """Is this the right way for checking a number. Maybe there is a better pythonic way :-)""" try: int(s) return True except TypeError: pass except ValueError: pass return False
def loess_abstract(estimator, threshold, param, length, migration_time, utilization): """ The abstract Loess algorithm. :param estimator: A parameter estimation function. :type estimator: function :param threshold: The CPU utilization threshold. :type threshold: float :param param: The safe...
def firmware_version_at_least(fw_version, major, minor): """ Returns True if the firmware version is equal to or above the provided major and minor values. """ if fw_version['major'] > major: return True if fw_version['major'] == major and fw_version['minor'] >= minor: return Tru...
def int_or_none(string): """Return the string as Integer or return None.""" try: return int(string) except: return None
def getColumnTitle(min='-inf', max='+inf'): """ Human readable column titles """ if str(min) == '-inf' and str(max) == '+inf': return 'Total' elif str(min) == '-inf': return 'Up to ' + '{0:,}'.format(max) elif str(max) == '+inf': return 'From ' + '{0:,}'.format(min) ...
def is_interactive(): """Detects if package is running interactively https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook Returns: bool: True if session is interactive """ import __main__ as main return not hasattr(main, '__file__')
def _get_seeds_to_create_not_interpolate_indicator(dense_keys, options): """Get seeds for each dense index to mask not interpolated states.""" seeds = { dense_key: next(options["solution_seed_iteration"]) for dense_key in dense_keys } return seeds