content
stringlengths
42
6.51k
def bakhshali_sqrt(rough, n): """https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Bakhshali_method""" iterations = 10 for _ in range(iterations): a = (n - (rough ** 2)) / (2 * rough) b = rough + a rough = b - ((a ** 2) / (2 * b)) return rough
def factorial(num): """This is a recursive function that calls itself to find the factorial of given number""" if num == 1: return num else: # print("lofh") return num * factorial(num-1)
def resolve_args_and_kwargs(context, args, kwargs): """ Resolves arguments and keyword arguments parsed by ``parse_args_and_kwargs`` using the passed context instance See ``parse_args_and_kwargs`` for usage instructions. """ return ( [v.resolve(context) for v in args], {k: v.res...
def list_cubes(path='.'): """ List all the cubefiles (suffix ".cube" ) in a given path Parameters ---------- path : str The path of the directory that will contain the cube files """ import os cube_files = [] isdir = os.path.isdir(path) if isdir: for file in os....
def config_value(config, key): """ Return value of a key in config """ if key not in config: return None return config[key]
def compute_1d_offsets(off, n, target_dist): """Helper function to compute slices along one dimension. Args: off (int): The offset of the local data. n (int): The local number of elements. target_dist (list): A list of tuples, one per process, with the offset and number o...
def ci_extractor(document): """Only records positive features""" features = {} for token in document.split(): features["contains_ci(%s)" % token.upper()] = True return features
def same(path1, path2): """ Compares two paths to verify whether they're the same. :param path1: list of nodes. :param path2: list of nodes. :return: boolean. """ start1 = path2.index(path1[0]) checks = [ path1[:len(path1) - start1] == path2[start1:], path1[len(path1...
def get_row_sql(row): """Function to get SQL to create column from row in PROC CONTENTS.""" postgres_type = row['postgres_type'] if postgres_type == 'timestamp': postgres_type = 'text' return '"' + row['name'].lower() + '" ' + postgres_type
def linspace(start, stop, n): """ Generates evenly spaced values over an interval Parameters ---------- start : int Starting value stop : int End value n : int Number of values Returns ------- list Sequence of evenly spaced values """ if ...
def f(n: int) -> int: """ Extract the digit value you like from a natural number. :param n: the natural number :return: the digit (as int) """ s = str(n) return int(s[0])
def get_row_col_channel_indices_from_flattened_indices(indices: int, num_cols: int, num_channels: int): """Computes row, column and channel indices from flattened indices. NOTE: Repurposed from Google OD A...
def find_min(a_para_list): """ Take in a list and return its minimum value :param a_para_list: a list of a wanted parameter :return: a_min: a minimum value """ num_lt = [float(i) for i in a_para_list] # Arjun Mehta min_val = min(num_lt) return min_val
def decode(text): """Decode text using Run-Length Encoding algorithm""" res = '' for i in range(len(text)): if text[i].isdigit(): res += text[i+1] * int(text[i]) return res
def even(value): """ Rounds a number to an even number less than or equal to original Arguments --------- value: number to be rounded """ return 2*int(value//2)
def normalize(numbers, total=1.0): """Multiply each number by a constant such that the sum is 1.0 (or total). >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ k = total / sum(numbers) return [k * n for n in numbers]
def fuel_to_launch_mass(module_mass: int) -> int: """Calculate the fuel to launch a module of the given mass.""" return max(module_mass // 3 - 2, 0)
def mult(m1,m2): """Matrix multiplication""" res = [len(m2[0])*[0] for i in range(len(m1))] for i in range(len(m1)): for j in range(len(m2[0])): for k in range(len(m2)): res[i][j] += m1[i][k]*m2[k][j] return res
def rotate_lambda(Lambda,clockwise=True): """ Rotate the Lambda tensors for the canonical PEPS representation """ if Lambda is not None: # Get system size (of rotated lambda) Ny = len(Lambda[0]) Nx = len(Lambda[1][0]) # Lambda tensors along vertical bonds vert =...
def checker_multiple_newlines_at_end_of_file(physical_line, last_line=False, **args): """Multiple newlines at end of file.""" if not last_line: return if not physical_line.strip(): return 0, W205
def make_skills_string(position): """ Take a position dictionary and build the skills list. Ensure the list separator is not a comma if there is a comma in one of the skill items """ if not 'skills' in position.keys(): return '' # Seprator separator = ', ' # Default separator is comm...
def diff_sequences(left, right): """ Compare two sequences, return a dict containing differences """ return { 'length_match': len(left) == len(right), 'differing': set([ i for i, (l, r) in enumerate(zip(left, right)) if l != r ])}
def gen_rowkey( sport_id: int, league_id: int, match_id: int, market: str, seq: int, period: str, vendor: str, timestamp: int) -> str: """Generate a row key based on the following format with ``#`` as the seperator. <sport_id>#<league_id>#<mat...
def boolean(_printer, ast): """Prints a boolean value.""" return f'{"true" if ast["val"] else "false"}'
def mean_parallel_B(rm=0.0, dm=100.0): """ Accepts a rotation measure (in rad/m^2) and dispersion measure (in pc/cm^3) and returns the approximate mean value for the paralelle magnetic field compoent along the line of sight, in Gauss. Conversion to Tesla is: 1 T = 10^4 G """ b_los = 1.23 * (rm / dm) return...
def add_ssl_statement(bucket, policy): """Add SSL statement to policy.""" bucket_arn_obj = "arn:aws:s3:::" + bucket + "/*" ssl_statement = { "Effect": "Deny", "Principal": "*", "Action": "*", "Resource": bucket_arn_obj, "Condition": { "Bool": { ...
def smallest_prime_factor(x): """Returns the smallest prime number that is a divisor of x""" # Start checking with 2, then move up one by one n = 2 while n <= x: if x % n == 0: return n n+=1
def get_options(options_str): """ Receives a string of 1's and 0's corresponding to different user settings 1 = True, 0 = False options_list[0]: "Enable Footnotes" options_list[1]: "Force Reprocess" """ options_list = [True if char == "1" else False for char in options_str] options = ...
def float_round(val): """ Rounds a floating number Args: val: number to be rounded Returns: Rounded integer """ return round(float(val))
def cssname(value): """Replaces all spaces with a dash to be a valid id for a cssname""" return value.replace(' ', '-')
def round_to_mbsize(value, batch_size): """Round value to multiple of batch size, if required.""" if value % batch_size == 0: return value else: return value + batch_size - value % batch_size
def to_bool(v): """Converts the given argument to a boolean value""" return v is True or str(v).lower() in ['true', '1']
def build_tags_filter(tags): """Build tag filter based on dict of tags. Each entry in the match is either single tag or tag list. It if is a list, it is "or". """ filters = [] assert isinstance(tags, (list, dict)), 'tags must be either list or dict.' if isinstance(tags, list): tags...
def isnull(val): """ Equivalent to isnan for floats, but also numba compatible with integers """ return not (val <= 0 or val > 0)
def get_page_url(year, month): """Get the 'wallpapers of the month' page URL. Arguments: year {int} -- year month {int} -- month Returns: str -- URL string """ template = "https://www.smashingmagazine.com/{:04}/{:02}/desktop-wallpaper-calendars-{}-{:04}/" months = [ ...
def wikidata_url(wikibase): """ returns Wikidata URL from wikibase """ if wikibase: return 'https://www.wikidata.org/wiki/' + wikibase
def get_value(line): """ - line: Line with QASM code to inspect """ return line.split(":")[1].strip()
def format_bytes(count): """ Format bytes in human-readable format """ for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB']: if abs(count) < 1024.0: return f"{count:3.1f} {unit}" count /= 1024.0 return f"{count:.1f} YiB"
def transition_soil_carbon(area_final, carbon_final, depth_final, transition_rate, year, area_initial, carbon_initial, depth_initial): """This is the formula for calculating the transition of soil carbon .. math:: (af * cf * df) - \ \\frac{1}{(1 ...
def generate_constraint(category_id, user): """ generate the proper basic data structure to express a constraint based on the category string """ return {'year': category_id}
def is_threatening(x1: int, y1: int, x2: int, y2: int) -> bool: """ Check if the positions are threatening each other. Examples -------- >>> is_threatening(0, 1, 1, 0) True """ same_row = x1 == x2 same_col = y1 == y2 delta1 = min(x1, y1) major_coords1 = (x1 - delta1, y1 - d...
def take(l, indexes): """take(l, indexes) -> list of just the indexes from l""" items = [] for i in indexes: items.append(l[i]) return items
def stringToArgList(string): """Converts a single argument string into a list of arguments""" return string.split(" ")
def day_postfix(day): """Returns day's correct postfix (2nd, 3rd, 61st, etc).""" if day != 11 and day % 10 == 1: postfix = "st" elif day != 12 and day % 10 == 2: postfix = "nd" elif day != 13 and day % 10 == 3: postfix = "rd" else: postfix = "th" return postfix
def is_acceptable_multiplier(m): """A 61-bit integer is acceptable if it isn't 0 mod 2**61 - 1. """ return 1 < m < (2 ** 61 - 1)
def is_unique_chars(str): """returns True if every character in the string is unique""" s = [char for char in str] print(s, str) for x in set(s): if (s.count(x) > 1): print(x) return False return True
def _can_cast_to(value, cast_type): """Returns true if `value` can be casted to type `type`""" try: _ = cast_type(value) return True except ValueError: return False
def tobin(x): """ Serialize strings to UTF8 """ if isinstance(x, str): return bytes(x, 'utf-8') else: return x
def read_sensor_package(bytes_serial): """ Read a sensor from serial bytes. Expected format is 5 bytes: 1, 2 : Package start 0x59 for YY 3 : unsigned integer for sensor index 4, 5 : unsigned integer for reading :return: sensor_index, reading """ if bytes_serial[0] ==...
def predict_species_impala(context, sepal_width, petal_length, petal_width): """ Predictor for species from model/52952081035d07727e01d836 Predictive model by BigML - Machine Learning Made Easy """ # 0 == Iris-virginica # 1 == Iris-versicolor # 2 == Iris-setosa if (petal_width > 0.8): ...
def pull_instance_id(arn): """ pulls the ecs instance id from the full arn """ return arn.split('container-instance/', 1)[-1]
def u_func(z, theta): """ Agents utility of asset: Args: z (input array): input to utility function. theta (float): the degree of relative risk aversion (theta = -2). Returns: u (float): utility for given i...
def prepare_shortlistedFirms(shortlistedFirms): """ Make list with keys key = {identifier_id}_{identifier_scheme}_{lot_id} """ shortlistedFirms = shortlistedFirms if shortlistedFirms else [] all_keys = set() for firm in shortlistedFirms: key = "{firm_id}_{firm_scheme}".format( ...
def v0_group_by(iterable, key_func): """Group iterable by key_func. The simplest way to write the group_by function is to use a dictionary and an if statement. As we loop over the items in our iterable, we can check whether each item has a key in our dictionary or not. If the key in not yet in our...
def exact_log2(num): """Find and return an integer i >= 0 such that num == 2**i. If no such integer exists, this function raises ValueError. """ if not isinstance(num, int): raise TypeError("unsupported operand type: %r" % (type(num).__name__,)) n = int(num) if n <= 0: raise V...
def flatten(list1): """ Simple function to flatten peers list Format: [((node1 endpoint1 tuple), (node1 endpoint2 tuple), ..., (node1 endpointm tuple)), ....] Example: [(("172.17.0.1",3000,None),), (("2001:db8:85a3::8a2e",6666,None), ("172.17.0.3",3004,None))] """ f_list = [] for i in list1...
def get_per_difference(list1, list2): """list1 : quocient (base value)""" my_size = len(list1) my_range = list(range(0, my_size)) diff = [] if len(list2) != my_size: print('Error! lists have different sizes') exit() else: for i in my_range: diff.append([]) ...
def smooth(x, y): """ Smooth a curve """ xs = x[:] ys = y[:] d = 0 for i in range(0, len(ys)): num = min(len(ys), i + d + 1) - max(0, i - d) _beg = max(0, i - d) _end = min(len(ys), i + d + 1) _ys = ys[_beg:_end] total = sum(_ys) ys[i] = total ...
def alias(name): """ Create a filesystem-friendly alias from a string. Replaces space with _ and keeps only alphanumeric chars. """ name = name.replace(" ", "_") return "".join(x for x in name if x.isalnum() or x == "_").lower()
def rle(seq): """define the rle function""" zipped = [] count = 1 var = seq[0] for i in range(1, len(seq)): if seq[i] == var: count = count + 1 else: zipped.append([var, count]) var = seq[i] count = 1 zipped.append([var, count]) ...
def is_quoted_identifier(identifier, sql_mode=""): """Check if the given identifier is quoted. Args: identifier (string): Identifier to check. sql_mode (Optional[string]): SQL mode. Returns: `True` if the identifier has backtick quotes, and False otherwise. """ if "ANSI_QUO...
def exclusive_id(arg): """Return a regex that captures exclusive id""" assert isinstance(arg, str) return r"(?P<%s>\d+)" % (arg,)
def merge_gaps(gap_list): """ Merges overlapping gaps in a gap list. The gap list is in the form: [('3','4'),('5','6'),('6','7'),('8','9'),('10','11'),('15','16'),('17','18'),('18','19')] Returns a new list containing the merged gaps: [('3','4'),('5','7'),('8','9'),('10','11'),('15','16'),('17','19')] ...
def get_url_stripped(uri): """ :param uri: <uri> or uri :return: uri """ uri_stripped = uri.strip() if uri_stripped[0] == "<": uri_stripped = uri_stripped[1:] if uri_stripped[-1] == ">": uri_stripped = uri_stripped[:-1] return uri_stripped
def insertion_sort(a): """ The insertion sort uses another strategy: at the i-th pass, the i first terms are sorted and it inserts the i + 1 term where it belongs by shifting right all elements greater one notch right to create a gap to insert it. It also runs in O(n^2) """ length = len(a) ...
def func(*args): """Function that returns the provided tuple with 'A' prepended.""" return ('A',) + args
def idx_to_hue(idx, color_num=24): """ Convert color index to hue """ if not isinstance(idx, int) or idx < 0 or idx > color_num-1: raise ValueError('idx should be integer between 0 and color_num-1') used = [-1] * color_num used[0] = color_num - 1 i = 0 result = 0 while i < idx...
def steps_to_coords(hor_steps, vert_steps, start_x, start_y, wire_coords): """Add coordinates to a set of points that the wire passes through. They are defined as a number of steps horizontally or vertically from the starting point for this particular instruction. Parameters ---------- hor_step...
def circ_square(length): """Calculates the circumference of a square. Calculates the circumference of a square based on the lenth of side. Args: length (float) : length is the length of side of a square. Returns: float: circumference of the square. """ if length < 0: r...
def reset_counts_nondeterministic(shots, hex_counts=True): """Reset test circuits reference counts.""" targets = [] if hex_counts: # Reset 0 from |++> targets.append({'0x0': shots / 2, '0x2': shots / 2}) # Reset 1 from |++> targets.append({'0x0': shots / 2, '0x1': shots / 2})...
def listlist_and_matrix_to_listdict(graph, weight=None): """Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation :param graph: in listlist representation :param weight: optional weight matrix :returns: graph ...
def any_lowercase5(s): """ incorrect - returns whether false if s contains any capital letters""" for c in s: if not c.islower(): return False return True
def size_to_kb_mb_string(data_size: int, as_additional_info: bool = False) -> str: """Returns human-readable string with kilobytes or megabytes depending on the data_size range. \n :param data_size: data size in bytes to convert :param as_additional_info: if True, the dynamic data appear in round bracket after t...
def kolmogorov_53_uni(k, epsilon, c=1.6): """ Universal Kolmogorov Energy spectrum Returns the value(s) of C \epsilon^{2/3} k^{-5/3} Parameters ---------- k: array-like, wavenumber epsilon: float, dissipation rate c: float, Kolmogorov constant c=1.6 (default) ... E(k) = c epsilon^(2...
def absolute_difference(x:float, y:float) -> float: """ return the absolute value of the difference between x and y >>> absolute_difference(3, 5) 2 >>> absolute_difference(10, 7) 3 """ return abs(x - y)
def _conv_size_fcn(inp, padding, dilation, kernel, stride): """ Return the output size or a conv layer with the given params. """ numerator = inp + (2*padding) - (dilation*(kernel-1)) - 1 return int((numerator/stride) + 1)
def redirect_to_url(url): """ Return a bcm dictionary with a command to redirect to 'url' """ return {'mode': 'redirect', 'url': url}
def _parse_double_quotion_5(cur_char, cur_token, token_stack): """ a function that analyze character in state 5 of finite automaton that state means the finite automaton has just handled double quotion """ token_stack.append(''.join(cur_token)) del cur_token[:] return None
def damerau_levenshtein_distance(s1, s2, t1, t2): """ Compute the Damerau-Levenshtein distance between two given strings (s1 and s2) """ d = {} max_size = max(t1+t2) lenstr1 = len(s1) lenstr2 = len(s2) for i in range(-1,lenstr1+1): d[(i,-1)] = i+1 for j in range(-1,lenstr...
def splitAtCapitalization(text): """ splits a string before capital letters. Useful to make identifiers which consist of capitalized words easier to read We should actually find a smarter algorithm in order to avoid splitting things like HLT or LW. """ retval = '' for ch in text: ...
def gcd(a: int, b: int) -> int: """Greatest common divisor Returns greatest common divisor of given inputs using Euclid's algorithm. Args: a: First integer input. b: Second integer input. Returns: Integer representing GCD. """ # Return the GCD of a and b using Euclid's...
def matchStrengthNoNoise(x, y, n): """Compute the match strength for the individual *x* on the string *y* excluding noise *n*. """ return sum(xi == yi for xi, yi, ni in zip(x, y, n) if ni != "#")
def convert_timeout(argument): """ Allow -1, 0, positive integers and None These are the valid options for the nbconvert timeout option. """ if argument.lower() == 'none': return None value = int(argument) if value < -1: raise ValueError('Value less than -1 not allowed') ret...
def aggregator_utility(R,r,k,N): """ Calculates the aggregator's utility """ U_ag=[] # utility of aggregator for c in range(N): U_ag.append((R-r)*c + k) return U_ag
def parse_header( line ): """Parses a header line into a (key, value) tuple, trimming whitespace off ends. Introductory 'From ' header not treated.""" colon = line.find( ':' ) space = line.find( ' ' ) # If starts with something with no whitespace then a colon, # that's the ID. if colon > -1 and ( space == -1 o...
def ConcatAttr(scope, attr, slash=False): """Combine the SCOPE and ATTR to give the canonical name of the attribute.""" if scope: if slash: sep = '/' else: sep = '.' return '%s%s%s' % (scope, sep, attr) return attr
def fetch_tmin(dbname, dt, bbox): """Downloads minimum temperature from NCEP Reanalysis.""" url = "http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.DAILY/.Diagnostic/.above_ground/.minimum/dods" varname = "temp" return url, varname, bbox, dt
def clean_name(string): """Clean entity/device name.""" return string.replace("-", " ").replace("_", " ").title()
def filter_data(data, filter_keys): """Applies a key filter to a dictionary in order to return a subset of the key-values. The insertion order of the filtered key-value pairs is determined by the filter key sequence. Parameters: data (dict): key-value pairs to be filtered. filter_keys (...
def handle_generic_error(err): """ default exception handler """ return 'error: ' + str(err), 500
def intify(x): """Change to an int if it is equal to one.""" i = int(x) return i if x == i else x
def bytes_rfind(x: bytes, sub: bytes, start: int, end: int) -> int: """Where is the last location of a subsequence within a given slice of a bytes object? Compiling bytes.rfind compiles this function, when sub is a bytes object. This function is only intended to be executed in this compiled form. Args...
def factorial(n: int) -> int: """Returns the factorial of n, which is calculated recursively, as it's usually defined mathematically.""" assert n >= 0 if n == 0: return 1 elif n == 1 or n == 2: return n else: return n * factorial(n - 1)
def first(l): """ Return the first item from a list, or None of the list is empty. :param l: The list :type l: list :return: The first list item (or None) :rtype: object | None """ return next(iter(l), None)
def generate_message(character, key, dictionary): """Generate Message.""" index = dictionary.find(character) if index > 0: return dictionary[index + key] else: return character
def is_chitoi(tiles): """ Returns True if the hand satisfies chitoitsu. """ unique_tiles = set(tiles) return (len(unique_tiles) == 7 and all([tiles.count(tile) == 2 for tile in unique_tiles]))
def calcGlycerolFractionByVolume(waterVolume, glycerolVolume): """ Calculates the volume fraction of glycerol in a water - glycerol mixture Args: waterVolume (float): volume of water in l glycerolVolume (float): volume of glycerol in l Returns: :class:`float` Fraction of glycer...
def _format_field_name(attr): """Format an object attribute in a human-friendly way.""" # Split at ':' and leave the extension name as-is. parts = attr.rsplit(':', 1) name = parts[-1].replace('_', ' ') # Don't title() on mixed case if name.isupper() or name.islower(): name = name.title()...
def reflect_angle_y_deg(a: float) -> float: """Returns reflected angle of `a` in y-direction in degrees. Angles are counter clockwise orientated and +y-axis is at 90 degrees. Args: a: angle to reflect in degrees """ return (360.0 - (a % 360.0)) % 360.0
def pretty_print(parsed_file): """ We just print so it looks decent in a terminal """ indented_uc = ' ' + parsed_file['uncommented_content'].replace('\n', '\n ') return '{origpath} ({artifact}):\n{indented_uc}'.format( origpath=parsed_file['origpath'], artifact=parsed_file['art...