content
stringlengths
42
6.51k
def _check_all_same_type(sequence): """ Check consistency of types across a sequence :param sequence: the iterable :return: bool """ iter_seq = iter(sequence) first_type = type(next(iter_seq)) return first_type if all((type(x) is first_type) for x in iter_seq) else False
def generate_name_from_values(attributes_dict): """Generate name from AttributeValues. Attributes dict is sorted, as attributes order should be kept within each save. Args: attributes_dict: dict of attribute_pk: AttributeValue values """ return " / ".join( str(attribute_value) ...
def is_valid(board, pos, num): """ Returns true same number isn't found in the same row, volumn or grid """ # Check row for i in range(0, len(board)): if board[pos[0]][i] == num and pos[1] != i: return False # Check Column for i in range(0, len(board)): if board...
def NormalizeScores(scores): """Normalize scores into a scale of 0 to 999.""" norm_scores = [] for score in scores: if score != 'None': if score < 0.0: norm_score = 0.0 elif score*100.0 > 999.0: norm_score = 999.0 else: norm_score = score*100.0 else: norm_s...
def _return_first_nonnull(l): """ Returns first nonnull element of l, otherwise returns None This is needed since functions like next() aren't available """ for item in l: if item: return item return None
def dela0(n,a0,a1,x,y): """ Dela0 dela0. Args: n: (array): write your description a0: (array): write your description a1: (array): write your description x: (array): write your description y: (array): write your description """ s=0; for i in range(n): ...
def get_lineno(node, default=0): """Gets the lineno of a node or returns the default.""" return getattr(node, 'lineno', default)
def calculate_16bit_parts(value): """Calculate the low and high part representations of value.""" if not (0 <= value < 65535): value = min(max(value, 0), 65535) # high_byte = value // 256 # low_byte = value % 256 # return high_byte, low_byte # faster: # return value // 256, value % 2...
def _rgb2hsl(rgb): """Create HSL from an RGB integer""" r = ((rgb >> 16) & 0xFF) / 255 g = ((rgb >> 8) & 0xFF) / 255 b = (rgb & 0xFF) / 255 min_c = min(r, g, b) max_c = max(r, g, b) delta_c = max_c - min_c l = min_c + (delta_c / 2) h = 0 s = 0 if max_c != min_c: if l ...
def _describe_bitmask(bits, table, default='0'): """Returns a bitmask in human readable form. This is a private function, used internally. Args: bits (int): The bitmask to be represented. table (Dict[Any,str]): A reverse lookup table. default (Any): A default return value when bits...
def token_count(value: str, delimiter: str = " ") -> int: """ Return count of delimiter-separated tokens pd.Series column. Parameters ---------- value : str Data to process delimiter : str, optional Delimiter used to split the column string. (the default is ' ') Ret...
def LimiterG3forDYS(dU1, dU2, dU3): """Return the limiter for Davis-Yee Symmetric TVD limiter function. This limiter is further used to calculate the flux limiter function given by Equation 6-141. Calculated using Equation 6-144 in CFD Vol. 1 by Hoffmann. """ if dU1 != 0: S = dU...
def camel_case(snake_str): """ Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar" """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one #...
def conv_len(a, l): """ Function that converts a number into a bit string of given length :param a: number to convert :param l: length of bit string :return: padded bit string """ b = bin(a)[2:] padding = l - len(b) b = '0' * padding + b return b
def calculateMid(paddle): """Calculates midpoint for each paddle, much easier to move the paddle this way""" midpoint = int(paddle[0][1] + paddle[1][1]) / 2 return midpoint
def base64(value): """The intrinsic function Fn::Base64 returns the Base64 representation of \ the input string. This function is typically used to pass encoded data to Amazon EC2 instances by way of the UserData property. Args: value: The string value you want to convert to Base64 Re...
def solution(n): """ Given a positive integer N, returns the length of its longest binary gap. """ # possible states (START state is necessary to ignore trailing zeros) START = -1 LAST_SAW_ONE = 1 LAST_SAW_ZERO = 0 current_state = START # we move the bit mask's bit one position at a time, # so ...
def api_argument_type(value): """ A workaround for the Prowl API not accepting the string "0" as a valid argument. """ if value == '0': value += ' ' return value
def closest_power(base, num): """ base: base of the exponential, integer > 1 num: number you want to be closest to, integer > 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case of a tie, re...
def CO2_scrubber_rating(report, index): """ Determine the CO2 scrubber rating value. :param report: list of read binary numbers :return: CO2 scrubber rating """ ones = 0 zeros = 0 if len(report) == 1: return report[0] for number in report: if int(number[index]): ...
def is_primitive(thing) -> bool: """ Check if a given thing is a primitive type Parameters ---------- thing The thing to check Returns ------- bool True if thing is a primitive """ primitives = [int, str, bool, dict, list, float] return type(thing) in primi...
def _json_force_object(v): """Force a non-dictionary object to be a JSON dict object""" if not isinstance(v, dict): v = {'payload': v} return v
def intmonth(value): """ returns a month label from an int number In template: Invoice Month - {{ invoice_month|intmonth }} Will show: Invoirce Month: Jan""" try: return ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][int(value)-1] except: return value
def handle_block_dev(line): """Handle if it match root device information pattern :param line: one line of information which had decoded to 'ASCII' """ block_format = '' for root_type in line.split(): if "ext4" in root_type or "ext3" in root_type: block_type = '' bloc...
def convert_link(link): """Convert the D3 JSON link data into a Multinet-style record.""" return { "_from": f"""characters/{link["source"]}""", "_to": f"""characters/{link["target"]}""", "value": link["value"], }
def namestr(obj, namespace): """This function extracts the name of the variable in a list Args: obj: variable whose name we want to extract namespace: namespace of interest """ return [name for name in namespace if namespace[name] is obj]
def pvalue_to_significance_string(pvalue): """Return significance string like '*' based on pvalue""" if pvalue < .001: return '***' elif pvalue < .01: return '**' elif pvalue < .05: return '*' else: return 'n.s.'
def _split_channels(total_filters, num_groups): """ https://github.com/tensorflow/tpu/blob/master/models/official/mnasnet/mixnet/custom_layers.py#L33 """ split = [total_filters // num_groups for _ in range(num_groups)] split[0] += total_filters - sum(split) return split
def is_extention_allowed(filename): """ Checks file extension is allowed :param filename: :return: is_allowed """ ALLOWED_EXTENSIONS = ["txt", "csv", "xlsx"] return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def barell_isrcode(code): """Give the nature of an injury. """ str_code = str(code) if len(str_code) == 3: str_code += "00" elif len(str_code) == 4: str_code += "0" dx13 = int(str_code[0:3]) dx14 = int(str_code[0:4]) dx15 = int(str_code[0:5]) D5 = int(str_code[-1]) # ...
def normalize(hash): """Return normalized copy of _hash_, dividing each val by sum(vals). :param hash: a key->number dict :return: dict >>> [(k,v) for k,v in sorted(normalize({1:3, 2:3, 3:6}).items())] [(1, 0.25), (2, 0.25), (3, 0.5)] """ total = sum(hash.values()) ans = {...
def generate_url(year, month, day): """Generates the dynamic Medium url to be scraped """ return "https://towardsdatascience.com/archive/{}/{:0>2}/{:0>2}".format(year, month, day)
def jsonrpc_result(id, result): """Create JSON-RPC result response""" return { 'jsonrpc': '2.0', 'result': result, 'id': id, }
def bitwise_and_2lists(list1, list2): """ Takes two bit patterns of equal length and performs the logical inclusive AND operation on each pair of corresponding bits """ list_len = len(list2) return_list = [None] * list_len for i in range(list_len): return_list[i] = list1[i] & list2[i...
def isConnected(stateList, stateGraph): """ Checks if list of states is connected in the order given """ state_pairs = zip(stateList[:-1], stateList[1:]) for first, second in state_pairs: if first not in stateGraph or second not in stateGraph[first]: return False return True
def filter_scenes_by_path_row(scene_list, path_row_list): """ Takes a scene list and list of path/rows and returns the correct scenes. Prints the available products for the scenes Args: scene_list: list of scene strings from get_scene_list path_row_list: user supplied lis tof path/row ...
def fibword(n, A0, A1): """ Given the first 2 characters A0 and A1, it returns the fibonacci string of n concatenations ----------------------------------------- Parameters: A0 (str) A1 (str) n (int) """ A=[A0,A1] for i in range(2,n): ...
def get_provider_thumbnail_name(provider_slug): """ Get a short identifier for thumbnail images for a provider. :param provider_slug: slug (or identifier) for the specified DataProvider """ return f"{provider_slug}_thmb"
def pipe_Di(Do, WT): """Calculate pipe inner diameter, given the pipe outer diamater and wall thickness. """ Di = Do - 2 * WT return Di
def _get_text(nodes): """ DOM utility routine for getting contents of text nodes """ return ''.join([n.data for n in nodes if n.nodeType == n.TEXT_NODE])
def _upgrade_chunk_info(chunk_info, improved_chunk_info): """Replace chunk info items with better ones while preserving number of dumps.""" for key, improved_info in improved_chunk_info.items(): original_info = chunk_info.get(key, improved_info) if improved_info['shape'][1:] != original_info['sh...
def match_to_key(match): """Convert a OF match string in dictionary form""" key = {} for token in match.split(";"): key_t, value_t = token.split("=") key[key_t] = value_t return key
def _transform_invalid_identifier(invalid_identifier: str) -> str: """Applies a transformation to an invalid C++ identifier to make it valid. Currently, this simply appends an underscore. This addresses the vast majority of realistic cases, but there are some caveats; see `fix_cc_identifier` function d...
def get_default_attr(obj, name, default): """Like getattr but return `default` if the attr is None or False. By default, getattr(obj, name, default) returns default only if attr does not exist, here, we return `default` even if attr evaluates to None or False. """ value = getattr(obj, name, def...
def gradient(x1: int, x2: int) -> int: """Calculate value and direction of change of x1 to get closer to x2. It can be one: -1, 0, 1 """ if x1 == x2: return 0 dx = x1 - x2 return int(dx / abs(dx))
def _escape(input_string: str) -> str: """ Adopted from https://github.com/titan550/bcpy/blob/master/bcpy/format_file_builder.py#L25 """ return ( input_string.replace('"', '\\"') .replace("'", "\\'") .replace("\r", "\\r") .replace("\n", "\\n") )
def init_actions_(service, args): """ This needs to return an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'test': ['install'] }
def create_message_report(message_body): """ This creates a message using the notification json about the status of the glacier restore for reporting. """ return f"{message_body['Records'][0]['s3']['object']['key']} has been restored and will be returned to Glacier at {message_body['Records'][0]['g...
def removePrefix(s, prefix): """ If the string starts with prefix, return the string with the prefix removed. Note: str.lstrip() should work, but gobbles up too many characters. See: http://stackoverflow.com/questions/4148974/is-this-a-bug-in-python-2-7 See: https://mail.python.org/pipermail/python-de...
def gamma(n, m): """Gamma function.""" if n == 1 and m == 2: return 3 / 8 elif n == 1 and m > 2: mm1 = m - 1 numerator = 2 * mm1 + 1 denominator = 2 * (mm1 - 1) coef = numerator / denominator return coef * gamma(1, mm1) else: nm1 = n - 1 nu...
def subtract(a, b): """Subtraction applied to two numbers Args: a (numeric): number to be subtracted b (numeric): subtractor Raises: ValueError: Raised when inputs are not numeric """ try: return a - b except: raise ValueError("inputs should be numeric")
def f1(predictions, gold): """ Calculates F1 score(a.k.a. DICE) Args: predictions: a list of predicted offsets gold: a list of offsets serving as the ground truth Returns: a float score between 0 and 1 """ if len(gold) == 0: return 1 if len(predicti...
def vecintlerp(l1, l2, pos): """ linear approximation for a vector of ints """ return tuple( int(round(a1+(a2-a1)*pos)) for a1, a2 in zip(l1, l2))
def split_email(email): """Split an email address :param email: email address :type email: str :returns: email address parts, or False if not an email address :rtype: dict, bool """ parts = email.strip().split("@") if len(parts) < 2: return False for i in parts: if i...
def do_get_time_spent(text): """ If the line is a "APPL-OK : : : X:" line then get the RealTimeSpent value """ if text.find('APPL-OK : : :') != -1: offset = text.find('OK : : :') if offset == -1: print(' This line must be wrong') print (text) ...
def previewColorEvent(r, g, b): """Callback for rgb color preview. Positional arguments: r -- Value for red. g -- Value for green. b -- Value for blue. """ if r == None or b == None or g == None: return {'backgroundColor': 'rgb(255, 255, 255)', 'color': 'rgb(255, 255, 255)'} el...
def to_integer(string: str) -> int: """converts string to integer""" return int(string.strip().replace(" ", "").replace("_", ""))
def resolve_parent(previous, parent): """ Figure out the parent to use based on the previous pane or given parent Breadth-based recursion means the previous pane should take precedence over the original parent if one is provided Parameters ---------- previous The previous pane ...
def zero_cross_down(values, start=0, end=-1): """ Returns the indexes of the values so that values[i] > 0 and values[i+1] < 0 params: - values: list of values to consider - start: index of the first value to consider - end: index of the last value to consider (can be < 0) """ ...
def create_template_dict(dbs): """ Generate a Template which will be returned by Executor Classes """ return {db: {'keys': [], 'tables_not_found': []} for db in dbs}
def _tag_tuple(revision_string): """convert a revision number or branch number into a tuple of integers""" if revision_string: t = [int(x) for x in revision_string.split('.')] l = len(t) if l == 1: return () if l > 2 and t[-2] == 0 and l % 2 == 0: del t[-2] return tuple(t) return (...
def transpose(array: list) -> list: """Return the transposed array.""" return [[array[i][j] for i in range(len(array))] for j in range(len(array[0]))]
def remove_empty(d): """ Remove elements from a dictionary where the value is falsey. :param d: The dict to remove falsey elements from. :return: Dict with no falsey values. """ return {k: v for k, v in d.items() if v}
def checkType(obj, ref_type): """Check if obj is of ref_type""" if type(obj) is ref_type: return True else: return False
def prepare_patch(data, pattern, replacement, op): """Prepare patch statement to pass to jsonpatch""" value = data[0] json_path = data[1] return { 'op': op, 'path': "/" + json_path.replace('.', '/').replace('/[', '/').replace(']/', '/'), 'value': str(value.replace(patter...
def _check_inputs(X,y=None): """Converts a matrix X into a list of lists and a vector y into a list.""" new_X = [] for row in X: new_row = [] for val in row: new_row.append( float(val) ) new_X.append( new_row ) if y is None: return new_X else: ...
def clip(v, vMin, vMax): """ @param v: number @param vMin: number (may be None, if no limit) @param vMax: number greater than C{vMin} (may be None, if no limit) @returns: If C{vMin <= v <= vMax}, then return C{v}; if C{v < vMin} return C{vMin}; else return C{vMax} """ if vMin is None: ...
def get_type(args_str, entry_type): """Determines the Python method type (METH_NOARGS or METH_VARARGS) from the C++ argument list and type of function. """ # The C-method-implementations accept self as the first argument, # so a one-argument method will be invoked with zero arguments in Pytho...
def year_sequence(start_year, end_year): """ returns a sequence from start_year to end_year inclusive year_sequence(2001,2005) = [2001, 2002, 2003, 2004, 2005] year_sequence(2005,2001) = [2005, 2004, 2003, 2002, 2001] """ if start_year == end_year: return [start_year] if start_year < end_ye...
def fix_limit(limit): """ fix limit integer from user Args: limit: limit integer - default 10 Returns: limit integer or 10 """ if limit: try: if int(limit) > 10000: return 10000 return int(limit) except Exception: ...
def shift(vec, dist): """Return a copy of C{vec} shifted by C{dist}. @postcondition: C{shift(a, i)[j] == a[(i+j) % len(a)]} """ result = vec[:] N = len(vec) # noqa dist = dist % N # modulo only returns positive distances! if dist > 0: result[dist:] = vec[:N-dist] res...
def get_default_value(schema, key, count=None): """Get the default value for a key in a schema. Parameters ---------- schema : dict[dict] Schema to compare to key : str Key to look for in the schema. count : int, optional For default functions that return different value...
def binary_search(lst, key): """searches the list for the key. if the key is present, the function returns the index of the key. Otherwise it returns -low-1. The list must be sorted""" lst.sort() low = 0 high = len(lst) - 1 while low <= high: mid = low + (high - low) //2 if l...
def find(lst, a): """Return list of indices for positions in list which contain a character in set 'a'.""" return [i for i, x in enumerate(lst) if x in set(a)]
def most_frequent(data: list) -> str: """ determines the most frequently occurring string in the sequence. """ # your code here return max(data, key=lambda x: data.count(x))
def sexastr2deci(sexa_str): """Converts as sexagesimal string to decimal Converts a given sexagesimal string to its decimal value Args: A string encoding of a sexagesimal value, with the various components separated by colons Returns: A decimal value corresponding to the sexagesimal...
def intString(s): """ check if the string s represents a number for components of field output s: a string return: True if s represents a component number False if s represents invariants """ try: int(s) return True except ValueError: ...
def replace_cr_with_newline(message: str): """ TQDM and requests use carriage returns to get the training line to update for each batch without adding more lines to the terminal output. Displaying those in a file won't work correctly, so we'll just make sure that each batch shows up on its one line. ...
def getFactoryMeritMultiplier(factoryId): """ Returns the skill merit multiplier for a particular factory. factoryId is the factory-interior zone defined in ToontownGlobals.py. """ # Many people complained about how many runs you must make now that # we lowered the cog levels so I have upped thi...
def reddit_response_parser(results): """ :param results: JSON Object :return: List of dictionaries [ { "title": "title of the news", "link": "original link of the news source", "source":"your-api-name" },...
def Binary(data): """Builds and returns the Binary JSON""" return { "request": { "method": "PUT", "url" : "Binary/" + data["id"] }, "resource": { "id" : data["id"], "resourceType": "Binary", "contentType" : data["mim...
def _extract_dialog_node_name(dialog_nodes): """ For each dialog_node (node_id) of type *standard*, check if *title exists*. If exists, use the title for the node_name. otherwise, use the dialog_node For all other cases, use the dialog_node dialog_node: (dialog_node_title, dialog_node_type) In...
def _binomial_coefficients(n): """"Return a dictionary of binomial coefficients Based-on/forked from sympy's binomial_coefficients() function [#] .. [#] https://github.com/sympy/sympy/blob/sympy-1.5.1/sympy/ntheory/multinomial.py """ data = {(0, n): 1, (n, 0): 1} temp = 1 for k in range(1...
def dict_no_none(*args, **kwargs) -> dict: """ Helper to build a dict containing given key-value pairs where the value is not None. """ return { k: v for k, v in dict(*args, **kwargs).items() if v is not None }
def map_number_ranges(x, old_min, old_max, new_min, new_max): """ Converts a number that exists in the range [old_min, old_max] to the range [new_min, new_max] :param x: the number to convert :param old_min: current number range minimum value :param old_max: current number range maximum value :...
def patch_env(env, path, value): """ Set specified value to yaml path. Example: patch('application/components/child/configuration/__locator.application-id','777') Will change child app ID to 777 """ def pathGet(dictionary, path): for item in path.split("/"): ...
def iteration_delay(level: int) -> float: """Determines the iteration delay in seconds given the current level""" if level == 1: return 0.5 elif level == 2: return 0.45 elif level == 3: return 0.4 elif level == 4: return 0.35 elif level == 5: return 0.3 ...
def get_edge_name(edge): """Separates the edge name from its abbreviation""" # the true edge name is everything before the final '_' character # so if we have PROCESS_OF_PpoP, we still want to keep 'PROCESS_OF' with the underscores intact. return '_'.join(edge.split('_')[:-1])
def bu8(u): """Convert an 8-bit integer to bytes. Example: bu8(0x12) == b'\x12' """ return bytes([u])
def mod_sqrt(n: int, p: int, is_odd: bool) -> int: """ Find Square Root under Modulo p Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists. https://www.geeksforgeeks.org/find-square-root-under-modulo-p-set-1-when-p-is-in-form-of-4i-3/ """ n %= p y = pow(n, (p + ...
def next_state(s,counter,N,args): """ implements particle number conservation. """ if(s==0): return s; # t = (s | (s - 1)) + 1 return t | ((((t & (0-t)) // (s & (0-s))) >> 1) - 1)
def constructor_is_method_name(constructor: str) -> bool: """Decides wheter given constructor is a method name. Cipher is not a method name Cipher.getInstance is a method name getS is a method name """ found_index = constructor.find(".") method_start_i = found_index + 1 return ...
def adjustForGroupOffers(skuCounts): """ X, S, T, Y, Z increasing prices""" decr = ['Z', 'Y', 'T', 'S', 'X'] special = [skuCounts.get(sku, 0) for sku in decr] groupOffer = 0 n = sum(special) if n >= 3: # group offer price groups = n // 3 deduce = groups * 3 ...
def string_to_weld_literal(s): """ Converts a string to a UTF-8 encoded Weld literal byte-vector. Examples -------- >>> string_to_weld_literal('hello') '[104c,101c,108c,108c,111c]' """ return "[" + ",".join([str(b) + 'c' for b in list(s.encode('utf-8'))]) + "]"
def toHexByte(n): """ Converts a numeric value to a hex byte Arguments: n - the vale to convert (max 255) Return: A string, representing the value in hex (1 byte) """ return "%02X" % n
def lin_objective(x, m, b): """Linear objective function""" return m*x + b
def nt2codon_rep(ntseq): """Represent nucleotide sequence by sequence of codon symbols. 'Translates' the nucleotide sequence into a symbolic representation of 'amino acids' where each codon gets its own unique character symbol. These characters should be reserved only for representing the 64 individual...
def close_enough(v1,v2): """ Helper function for testing if two values are "close enough" to be considered equal. """ return abs(v1-v2) <= 0.0001
def _argument_string(*args, **kwargs): """Return the string representation of the list of arguments.""" return "({})".format( ", ".join( [ *["{!r}".format(v) for v in args], # arguments *[ "{}={!r}".format(k, v) for k, v in kwargs.items() ...
def corrupt_with_vowels(input): """ Takes in a base string input. Returns a string that has been corrupted by removing all the vowels (a, e, i, o, u) from it. Parameters: input: Base string that will be corrupted. Returns: String input with all vowels removed. >>> corrupt_w...