content
stringlengths
42
6.51k
def combinations(n: int, r : int): """Gives the number of possibilities of n objects chosen r times, order matters""" product = 1 for i in range(n - r + 1, n + 1): product *= i for x in range(2, r+1): product /= x return product
def detect_encrypted_resource(resource): """Detect if resource is encrypted with GnuPG Determining factors: a) The resource is ascii-armored text b) The resource is binary data starting with 0x8502""" try: # Read file like line = resource.read(50) resource.seek(0) exce...
def _no_pending_stacks(stacks): """If there are any stacks not in a steady state, don't cache""" for stack in stacks: status = stack['stack_status'] if '_COMPLETE' not in status and '_FAILED' not in status: return False return True
def interval_idx(x, xi): """ Given a grid of points xi (sorted smallest to largest) find in which interval the point x sits. Returns i, where x \in [ xi[i],xi[i+1] ]. Raise ValueError if x is not inside the grid. """ assert x >= xi[0] and x <= xi[-1], ValueError( 'x=%g not in [%g,%g]' %...
def _get_bucket_and_file_names(event: dict): """ Get bucket and file name from s3 trigger event to download transaction source data file. """ bucket_name = event['Records'][0]['s3']['bucket']['name'] file_key = event['Records'][0]['s3']['object']['key'] return bucket_name, file_key
def dump_section(bank_number, separator="\n\n"): """ Returns a str of a section header for the asm file. """ output = "SECTION \"" if bank_number in [0, "0"]: output += "bank0\",HOME" else: output += "bank" output += bank_number output += "\",DATA,BANK[$" ...
def is_cross_host(mpi_nodes, edge): """ Return true if the supplied edge is a cross-host edge according to the mpi nodes supplied. """ out_node_key = edge[0][0] in_node_key = edge[0][1] return mpi_nodes[out_node_key]["host"] != mpi_nodes[in_node_key]["host"]
def upper_bound(l, k): """ >>> upper_bound([1, 2, 2, 3, 4], 2) 3 >>> upper_bound([1, 2, 2, 3, 4], 5) -1 :param l: :param k: :return: """ if l[-1] <= k: return -1 i = len(l) // 2 start, end = 0, len(l) - 1 while start < end: if l[i]...
def convert_environment_id_string_to_int( environment_id: str ) -> int: """ Converting the string that describes the environment id into an int which needed for the http request :param environment_id: one of the environment_id options :return: environment_id represented by an int """ try...
def get_usergraph_feature_names(osn_name): """ Returns a set of the names of the user graph engineered features. :param osn_name: The name of the dataset (i.e. reddit, slashdot, barrapunto) :return: names: The set of feature names. """ names = set() ########################################...
def subsets(n): """ Returns all possible subsets of the set (0, 1, ..., n-1) except the empty set, listed in reversed lexicographical order according to binary representation, so that the case of the fourth root is treated last. Examples ======== >>> from sympy.simplify.sqrtdenest import s...
def parse_file_to_bucket_and_filename(file_path): """Divides file path to bucket name and file name""" path_parts = file_path.split("//") if len(path_parts) >= 2: main_part = path_parts[1] if "/" in main_part: divide_index = main_part.index("/") bucket_name = main_par...
def down(state): """move blank space down on the board and return new state.""" new_state = state[:] index = new_state.index(0) if index not in [6, 7, 8]: temp = new_state[index + 3] new_state[index + 3] = new_state[index] new_state[index] = temp return new_state else...
def _check(rule1, rule2): """ introduction: Verify the correctness of the YYC rules. :param rule1: Correspondence between base and binary data (RULE 1). :param rule2: Conversion rule between base and binary data based on support base and current base (RULE 2). :return: Check result. """ f...
def decode_dict(d): """Decode dict.""" result = {} for key, value in d.items(): if isinstance(key, bytes): key = key.decode() if isinstance(value, bytes): value = value.decode() elif isinstance(value, dict): value = decode_dict(value) resul...
def get_office_result(office): """SQL query to read office results from database Args: office (integer): office id to get results of candidate (integer): candidate id to get results of """ sql = """ SELECT office_id, candidate_id, COUNT(candidate_id) AS result FROM votes WHE...
def is_list(value): """Check if a value is a list""" return isinstance(value, list)
def gf_mult(a, b, m): """Galois Field multiplication of a by b, modulo m. Just like arithmetic multiplication, except that additions and subtractions are replaced by XOR. """ res = 0 while b != 0: if b & 1: res ^= a a <<= 1 b >>= 1 if a >= 256: ...
def deg_plato_to_gravity(deg_plato): """Convert degrees Plato to specific gravity. Parameters ---------- deg_plato : float Degrees Plato, like 13.5 Returns ------- sg : float Specific gravity, like 1.053 """ return 1. + (deg_plato / 250.)
def unescape(s): """ Revert escaped characters back to their special version. For example, \\n => newline and \\t => tab """ return s.replace('\\n', '\n').replace('\\t', '\t').replace('\\r', '\r')
def form_line(ltokens=[], rtokens=[]): """Form line.""" if not isinstance(ltokens, (list, tuple)): return str(ltokens) + ';' ltext = ' '.join(map(str, ltokens)) rtext = ' '.join(map(str, rtokens)) if len(rtokens) > 0: return '{ltext} = {rtext};'.format(ltext=ltext, rtext=rtext) ...
def get_days_in_month(year, month): """ Returns the number of days in the month of a specific year :param int year: the year of the month :param int month: the number of the month :return: :rtype: int """ from calendar import monthrange return monthrange(year, month)[1]
def health(): """Our instance health. If queue is too long or we use too much mem, return 500. Monitor might reboot us for this.""" is_bad_state = False msg = "Ok" import resource stats = resource.getrusage(resource.RUSAGE_SELF) mem = stats.ru_maxrss if mem > 1024**3: is_bad_st...
def read_sealevel_pressure(pressure, altitude_m=0.0): """Calculates the pressure at sealevel when given a known altitude in meters. Returns a value in Pascals.""" p0 = pressure / pow(1.0 - altitude_m/44330.0, 5.255) return p0
def get_provenance_record(ancestor_files, caption, statistics, domains, plot_type='geo'): """Get Provenance record.""" record = { 'caption': caption, 'statistics': statistics, 'domains': domains, 'plot_type': plot_type, 'themes': ['atmDyn', 'mons...
def black_invariant(text, chars=None): """Remove characters that may be changed when reformatting the text with black""" if chars is None: chars = [' ', '\t', '\n', ',', "'", '"', '(', ')', '\\'] for char in chars: text = text.replace(char, '') return text
def camelcase(string): """Convert snake casing where present to camel casing""" return ''.join(word.capitalize() for word in string.split('_'))
def fib_list(n): """[summary] This algorithm computes the n-th fibbonacci number very quick. approximate O(n) The algorithm use dynamic programming. Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be a...
def isAbundant(x): """Returns whether or not the given number x is abundant. A number is considered to be abundant if the sum of its factors (aside from the number) is greater than the number itself. Example: 12 is abundant since 1+2+3+4+6 = 16 > 12. However, a number like 15, where the sum of the...
def tupletupleint(items): """A tuple containing x- and y- slice tuples from a string or tuple""" if isinstance(items, str): for s in " ()[]": items = items.replace(s, "") # we have a string representation of the slices x1, x2, y1, y2 = items.split(",") out = ((int(flo...
def Elastic(m1, m2, v1, v2): """Returns a tuple of the velocities resulting from a perfectly elastic collision between masses m1 traveling at v1 and m2 traveling at v2. This simultaneously conserves momentum and energy.""" vp2 = ((m2 * v2) + (m1 * ((2.0 * v1) - v2))) / (m1 + m2) vp1 = vp2 + v2 - v...
def function_path(func): """ This will return the path to the calling function :param func: :return: """ if getattr(func, 'func_code', None): return func.func_code.co_filename.replace('\\', '/') else: return func.__code__.co_filename.replace('\\', '/')
def _guess_header(info): """Add the first group to get report with some factor""" value = "group" if "metadata" in info: if info["metadata"]: return ",".join(map(str, info["metadata"].keys())) return value
def dehexify(data): """ A URL and Hexadecimal Decoding Library. Credit: Larry Dewey """ hexen = { '\x1c': ',', # Replacing Device Control 1 with a comma. '\x11': ',', # Replacing Device Control 2 with a new line. '\x12': '\n', # Space '\x22': '"', # Double Quote...
def is_zero_depth_field(name): """ Checks if a field name has one dot in it. For example, BuildingCode.Value """ if name.find('.') != -1 and name.find('.') == name.rfind('.'): return True return False
def cpu_usage_for_process(results, process): """ Calculate the CPU percentage for a process running in a particular scenario. :param results: Results to extract values from. :param process: Process name to calculate CPU usage for. """ process_results = [ r for r in results if r['met...
def parse_balanced_delimiters(_input, _d_left, _d_right, _text_qualifier): """Removes all balanced delimiters. Handles multiple levels and ignores those contained within text delimiters.""" # Depth is deep into recursion we are _depth = 0 # Balance is a list of all balanced delimiters _balanced = ...
def _sched_malformed_err(msg=None): """ Returns an error message if the schedule is malformed """ msg = msg if msg else 'schedule malformed' help_msg = "<br><br>Enter a schedule like <i>r1(x)w1(y)r2(y)r1(z)</i>" return msg+help_msg
def var_to_int(var): """ Convert a variable name (such as "t5") to an integer (in this case 5). Variables like "Amat(iq,D1_RA)" should never show up here. """ return int(var[1:])
def object_name(object): """Convert Python object to string""" if hasattr(object, "__name__"): return object.__name__ else: return repr(object)
def count_deck(deck: dict) -> int: """Count the number of remaining cards in the deck.""" total = 0 for card, card_item in deck.items(): total += card_item['count'] return total
def calculate_streak(streak, operation): """ Params: streak: current user's streak operation: 1 if bet hits, -1 if bet doesn't hit If streak is positive and bet hits it will increment streak If streak is negative and bet hits it will assign it 1 If streak is positive and bet misses ...
def firehose_alerts_bucket(config): """Get the bucket name to be used for historical alert retention Args: config (dict): The loaded config from the 'conf/' directory Returns: string: The bucket name to be used for historical alert retention """ # The default name is <prefix>-strea...
def last_in_array(array, operation = None): """Return the last element in an array. I think this is just [-1] """ if len(array) == 0: return None return array[-1]
def service_proxy_settings(service_proxy_settings): """Expect credentials to be passed in headers""" service_proxy_settings.update({"credentials_location": "headers"}) return service_proxy_settings
def ground_truth_to_word(ground_truth, char_vector): """ Return the word string based on the input ground_truth """ try: return ''.join([char_vector[i] for i in ground_truth if i != -1]) except Exception as ex: print(ground_truth) print(ex) input()
def reverse_mapping(mapping): """ For every key, value pair, return the mapping for the equivalent value, key pair >>> reverse_mapping({'a': 'b'}) == {'b': 'a'} True """ keys, values = zip(*mapping.items()) return dict(zip(values, keys))
def clean_file(f, config): """Remove AWS @-based region specification from file. Tools such as Toil use us-east-1 bucket lookup, then pick region from boto. """ approach, rest = f.split("://") bucket_region, key = rest.split("/", 1) if bucket_region.find("@") > 0: bucket, region = b...
def display_attributes(attributes: dict) -> str: """ This function read a dictionary with attributes and returns a string displaying the attributes it gives. A template: {armor} {health} {mana} {strength} {agility} If any are missing, we don't add them """ attributes_to_print = [f'{attr.replace...
def _merge(a, b, path=None): """merges b into a""" if path is None: path = [] for key, bv in b.items(): if key in a: av = a[key] nested_path = path + [key] if isinstance(av, dict) and isinstance(bv, dict): _merge(av, bv, nested_path) ...
def _recursive_parameter_structure(default_parameters): """ Convert a set of parameters into the data types used to represent them. Returned result has the same structure as the parameters. """ # Recurse through the parameter data structure. if isinstance(default_parameters, dict): retur...
def transforms_fields_uktrade(record, table_config, contexts): """ Transform data export fields to match those of the UKTrade Zendesk API. """ service = next( field for field in record["custom_fields"] if field["id"] == 31281329 ) if "requester" in record: org = record['organiza...
def infer_prop_name(name): """Return inferred property name from pandas column name.""" return name.strip(' "').rsplit('(', 1)[0].rsplit( '[', 1)[0].strip().replace(' ', '_')
def cmyk_to_luminance(r, g, b, a): """ takes a RGB color and returns it grayscale value. See http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/ for more information """ if (r, g, b) == (0, 0, 0): return a return (0.299 * r + 0.587 * g + 0.114 * b) * a / 255
def ensure_timed_append_if_cardinality_one( config, extra_config, app_type, app_path, ): """ Automatically sets the "TIMED_APPEND" App Configuration variable automatically to "TRUE" if the "append" option is enabled and the cardinality parameter (if given) is set to "one". ...
def validate_tag(key, value): """Validate a tag. Keys must be less than 128 chars and values must be less than 256 chars. """ # Note, parse_sql does not include a keys if the value is an empty string # (e.g. 'key=&test=a'), and thus technically we should not get strings # which have zero length...
def convert_str_to_mac_address(hex_mac): """Just add colons in the right places.""" hex_pairs = [hex_mac[(x*2):((x+1)*2)] for x in range(6)] mac = "{0}:{1}:{2}:{3}:{4}:{5}".format(*hex_pairs) return mac
def pad_sequences(sequences, pad_func, maxlen = None): """ Similar to keras.preprocessing.sequence.pad_sequence but using Sample as higher level abstraction. pad_func is a pad class generator. """ ret = [] # Determine the maxlen max_value = max(map(len, sequences)) if maxlen is None...
def H(path): """Head of path (the first name) or Empty.""" vec = [e for e in path.split('/') if e] return vec[0] if vec else ''
def uv76_to_uv60(u76, v76): # CIE1976 to CIE1960 """ convert CIE1976 u'v' to CIE1960 uv coordinates :param u76: u' value (CIE1976) :param v76: v' value (CIE1976) :return: CIE1960 u, v """ v60 = (2 * v76) / 3 return u76, v60
def formalize_switch(switch, s): """ Create single entry for a switch in topology.json """ entry= { "mac": "08:00:00:00:01:"+str(s), "runtime_json": "./build/"+switch+"P4runtime.json" } return entry
def compare_lists(list1: list, list2: list): """Returns the diff of the two lists. Returns ------- - (added, removed) ``added`` is a list of elements that are in ``list2`` but not in ``list1``. ``removed`` is a list of elements that are in ``list1`` but not in ``list2``. """ added = ...
def matrices_params(n_samples): """Generate matrices benchmarking parameters. Parameters ---------- n_samples : int Number of samples to be used. Returns ------- _ : list. List of params. """ manifold = "Matrices" manifold_args = [(3, 3), (5, 5)] module = "g...
def index(seq): """ Build an index for a sequence of items. Assumes that the items in the sequence are unique. @param seq the sequence to index @returns a dictionary from item to position in the sequence """ return dict((k,v) for (v,k) in enumerate(seq))
def _whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
def _func(l): """Convert a list to a pretty text.""" return '{' + ", ".join([f"'{x}'" for x in l]) + '}'
def binEntryBytes(binStr): """Convert a sequence of whitespace separated tokens each containing no more than 8 0's and 1's to a list of bytes. Raise Exception if illegal. """ bytes = [] for i, token in enumerate(binStr.split()): if len(token) > 8: raise Exception("Toke...
def exception_to_ec2code(ex): """Helper to extract EC2 error code from exception. For other than EC2 exceptions (those without ec2_code attribute), use exception name. """ if hasattr(ex, 'ec2_code'): code = ex.ec2_code else: code = type(ex).__name__ return code
def RemoveDuplicate(Sortedlist): """Removes duplicates from a sorted list""" _Newlist=[] if not Sortedlist: return(_Newlist) else: iterable=(x for x in Sortedlist) prev=None for element in iterable: if (element == prev): pass else: _Newlist.append(element) prev=element return(_Newli...
def shiftCoordsForHeight(s): """ Shift with height s origin = 0,0 """ coords = ( ( # path (s/2,s), (0,s*4/9), (s*4/15,s*4/9), (s*4/15,0), (s*11/15,0), (s*11/15,s*4/9), (s,s*4/9), ), ) return coords
def get_words_from_string(input_): """This splits a string into individual words separated by empty spaces or punctuation """ return input_.split()
def get_value_for_key_from_json(key, data_structure): """ Given a data_structure return the *first* value of the key from the first dict example: data_structure: [ { "id": 1, "name": "name1" }, { "id": 2, "name": "name2"} ] key: "id" return 1 :param key: key of a dict of which t...
def hash_to_test(): """ Easy way to create test data for hash to test. :var string text_test: holds test text :var string text_format: holds format for test text :var string hash_text: holds test hash :return: test data array that contains text, format of text, hash. """ text_test = 'h...
def count_nests(nest_spec): """ count the nests in nest_spec, return 0 if nest_spec is none """ def count_each_nest(spec, count): if isinstance(spec, dict): return count + sum([count_each_nest(alt, count) for alt in spec['alternatives']]) else: return 1 retu...
def read_error_line(l): """ Reads line? """ print('_read_error_line -> line>', l) name, values = l.split(' ', 1) print('_read_error_line -> name>', name) print('_read_error_line -> values>', values) name = name.strip(': ').strip() values = values.strip(': ').strip() v, error =...
def model_function(X, a, b, c): """ - the analytical expression for the model that aims at describing the experimental data - the X argument is an array of tuples of the form X=[,...,(xi_1,xi_2),...] """ nw1, nw2, I = X f = a * pow(I, 2) * (nw1 + 0.5) + b * I * (nw2 + 0.5) + c return f
def getfmt(n,dtype ="d"): """ Generates the binary format n dtype defualts to double @param n: number of particles @param dtype: data type returns the format string used to decode the binary data """ fmt = "" fmt += dtype for i in range(n): ...
def make_physical_params_sweep_fname(tag: str, param_str: str): """Return a filename for noiseless parameter sweeps inputs. Args: tag: Some identifier string for this simulation result. """ return f"physical_parameter_sweep_{tag}_{param_str}.npy"
def matching(a, b): """ Totals the number of matching characters between two strings Parameters ---------- a: str b: str Returns ------- int """ comp = zip(a, b) diff = abs(len(a)-len(b)) m = sum(1 for x,y in comp if x == y) return m - diff
def anal_q(data_dict): """ Try and get the CCSDT(Q) energy """ try: q_dict = data_dict["ccsdtq"] q_energy = q_dict["ccsdt(q) energy"] - q_dict["ccsdt energy"] except KeyError: q_energy = 0. return q_energy
def get_drop_connect_rate(init_rate, block_num, total_blocks): """Get drop connect rate for the ith block.""" if init_rate is not None: return init_rate * float(block_num) / total_blocks else: return None
def get_round_scaled_dsize(dsize, scale): """ Returns an integer size and scale that best approximates the floating point scale on the original size Args: dsize (tuple): original width height scale (float or tuple): desired floating point scale factor """ try: sx, sy = s...
def get_guest_flag(flags): """ This is get flag index list :param flags: :return: flag index list in GUEST_FLAGS """ err_dic = {} flag_str = '' for flag in flags: if flags.count(flag) >= 2: return (err_dic, flag) for i in range(len(flags)): if i == 0: ...
def _is_package_init(path): """Check whether a file path refers to a __init__.py or __init__.pyc file. Params: ------- path: str File path. Return: ------- bool: Whether the file path refers to a pacvkage init file. """ return path.lower().endswith('__init__.py') o...
def calc_bitmasks_ARGB_color(bdR: int, bdG: int, bdB: int, bdA: int): """Calculates the appropriate bitmasks for a color stored in ARGB format.""" redMask = 0 greenMask = 0 blueMask = 0 alphaMask = 0 if bdA > 0: for _ in range(bdA): alphaMask = (alphaMask << 1) + 1 ...
def read_kwargs_from_dict(input_dict, type_dict): """ Reads, from an input dictionary, a set of keyword arguments. This function is useful to gather optional arguments for a function call from a greater, more complete, input dictionary. For this purpose, keys that are not found at input_dict are simply ...
def f(a, b): """Function with an integer range containing the other.""" return -(a + b)
def regexp_versions(versions_string): """Converts the list of versions from the bulletin data into a regexp""" if len(versions_string) == 0: return '' versions = versions_string.replace('and', ',').replace(' ', '').replace('.', '\\.').split(',') regexp = '' for version in versions: d...
def member_id_validation(input_id): """ function used to check if the input member id is valid """ if len(input_id) != 4: # if the id input is not 4 digits return 1 elif input_id.isdigit(): # if the input id is a number return 0 else: # if not a number ...
def micro(S, C, T): """ Computes micro-average over @elems """ S, C, T = sum(S.values()), sum(C.values()), sum(T.values()) P = C/S if S > 0. else 0. R = C/T if T > 0. else 0. F1 = 2 * P * R /(P + R) if C > 0. else 0. return P, R, F1
def parse_optimization_method(lr_method): """ Parse optimization method parameters. """ if "-" in lr_method: lr_method_name = lr_method[:lr_method.find('-')] lr_method_parameters = {} for x in lr_method[lr_method.find('-') + 1:].split('-'): split = x.split('_') ...
def strip_docstring(docstring): """Return contents of docstring.""" docstring = docstring.strip() quote_types = ["'''", '"""', "'", '"'] for quote in quote_types: if docstring.startswith(quote) and docstring.endswith(quote): return docstring.split(quote, 1)[1].rsplit(quote, 1)[0].st...
def _change_dict_key(the_dict, old_key, new_key, default=None): """ Changes a dictionary key name from old_key to new_key. If old_key doesn't exist the value of new_key becomes and empty dictionary (or the value of `default`, if set). """ if default is None: default = dict() v = the...
def x0_mult(guess, slip): """ Compute x0_mult element-wise Arguments: guess (np.array) slip (np.array) """ return slip*(1.0+guess)/(1.0+slip)
def left_of_center(box, im_w): """ return -1 if left of center, 1 otherwise. """ (left, right, top, bot) = box center_image = im_w / 2 if abs(left - center_image) > abs(right - center_image): return -1 return 1
def sanitize_text(text: str) -> str: """Sanitizes and removes all useless characters from the text, returns sanitized text string""" alphanum_text = "" for letter in list(text): if letter.isalnum() or letter == " " or letter in "!?.,:;\'\"&()$%#@~": alphanum_text += letter return al...
def cal_percents(count_list): """A,C,G,T, depth""" depth = float(count_list[0]) if depth > 0: count_list.append(str(100*(int(count_list[1])/depth))) # perA count_list.append(str(100*(int(count_list[2])/depth))) # perC count_list.append(str(100*(int(count_list[3])/depth))) # perG ...
def change_dict_value(dictionary, old_value, new_value): """ Change a certain value from a dictionary. Parameters ---------- dictionary : dict Input dictionary. old_value : str, NoneType, bool The value to be changed. new_value : str, NoneType, bool Replace value. ...
def findComplement_v4(num: int) -> int: """The lLeetCode solutions runner judges this to be the fastest of all four.""" return num ^ max(1, 2 ** (num).bit_length() - 1)
def get_origin(type_annotation): """ Backport of python 3.8's get_origin. e.g. get_origin(Tuple[str, int]) is Tuple :param type_annotation: A type annotation, e.g Tuple[str, int] :return: The base type, e.g. Tuple """ is_generic_annotation = hasattr(type_annotation, '__origin__') and type_annotatio...