content
stringlengths
42
6.51k
def safe_append_in_dict(dictionary, key, val): """ Check if a list already exists for a given key. In that case append val to that list, otherwise create a list with val as the first element Parameters ========== dictionary: target dictionary to be filled with new value key: key for the dic...
def get_id_by_link(link): """Takes link on vk profile and returns identificator of user, that can be used in vkapi functions. Vkontakte has to types of links: 1)vk.com/id[userid] ex.: vk.com/id1 2)vk.com/[user_alias] ex.: vk.com/anton21 , vk.com/vasya We need to parse both of them. """ ...
def str2bool(str_val): """ Convert string to boolean :param str_val: boolean in str :return: value in bool or raise error if not matched """ state = str_val.strip().lower() if state in ('t', 'y', 'true', 'yes', '1'): return True elif state in ('f', 'n', 'false', 'no', '0'): ...
def extract_name_from_tags(cs, default_no_name="NO NAME"): """ extract the host name from tags associated with an instance or vpc or subnet on Amazon EC2 """ if cs is None: return default_no_name for d in cs: if 'Key' in d and d['Key'] == 'Name' and 'Value' in d: return d['Value'] return default...
def step_gradient(b_current, m_current, points, learning_rate): """One step of a gradient linear regression. To run gradient descent on an error function, we first need to compute its gradient. The gradient will act like a compass and always point us downhill. To compute it, we will need to differentia...
def get_all_context_names(context_num): """Based on the nucleotide base context number, return a list of strings representing each context. Parameters ---------- context_num : int number representing the amount of nucleotide base context to use. Returns ------- a list of str...
def checkTypes(args, **types): """Return **True** if types of all *args* match those given in *types*. :raises: :exc:`TypeError` when type of an argument is not one of allowed types :: def incr(n, i): '''Return sum of *n* and *i*.''' checkTypes(locals(), n=(float,...
def get_intent(query): """Returns the intent associated with the client_response :param query: :return: [String] """ try: return query.intent except Exception as e: print(e) return None
def item_present_all_lists(item, lists: list): """Check if an item is present in all lists""" for index in range(len(lists)): if item not in lists[index]: return False return True
def sort_012(input_list): """Sort an array of 0s, 1s, and 2s in place. Args: input_list: A list of ints consisting of 0s, 1s, and 2s to be sorted Returns: input_list: The list of ints passed in, sorted. """ idx = 0 left = 0 right = len(input_list) - 1 while idx <= righ...
def _is_kpoint(line): """Is this line the start of a new k-point block""" # Try to parse the k-point; false otherwise toks = line.split() # k-point header lines have 4 tokens if len(toks) != 4: return False try: # K-points are centered at the origin xs = [float(x) for x ...
def tag_name(name): """Removes expanded namespace from tag name.""" result = name[name.find('}') + 1:] if result == 'encoded': if name.find('/content/') > -1: result = 'content' elif name.find('/excerpt/') > -1: result = 'excerpt' return result
def flip_matrix(A): """ :param A: :return: """ # 1. flip horizontally = reverse the elements in the sublists. # reversed returns a iterator object vs .reverse() = inplace # 2. 1-num gives us the compliment for a binary number return [[1-num for num in A[i][::-1]] for i in range(len(A))]
def get_login_provider_items_from_database_cfgitems(_): """Return information for default login providers; present in all cluster configurations. """ return { "dcos-users": { "authentication-type": "dcos-uid-password", "description": "Default DC/OS login provider", ...
def chi_par(x, A, x0, C): """ Parabola for fitting to chisq curve. Arguments: x -- numpy array of x coordinates of fit A -- x0 -- x coordinate of parabola extremum C -- y coordinate of extremum """ return A*(x - x0)**2 + C
def genome_info(genome, info): """ return genome info for choosing representative if ggKbase table provided - choose rep based on SCGs and genome length - priority for most SCGs - extra SCGs, then largest genome otherwise, based on largest genome """ try: scg = info['#SCG...
def bearing_2_status(d): """ Converts wind direction in degrees to a winddirection in letters Used in wind devices Args: d (float): winddirection in degrees, 0 - 360 Returns: description of the wind direction, eg. "NNE", WNW", etc. Ref: Based on https://gist.github.com/Rob...
def B0_rel_diff(v0w, b0w, b1w, v0f, b0f, b1f, config_string, prefact, weight_b0, weight_b1): """ Returns the relative difference in the bulk modulus. THE SIGNATURE OF THIS FUNCTION HAS BEEN CHOSEN TO MATCH THE ONE OF ALL THE OTHER FUNCTIONS RETURNING A QUANTITY THAT IS USEFUL FOR COMPARISON, THIS SIMPLI...
def tr(s): """[If you need to transform a string representation of the output provide a function that takes a string as input and returns one] Arguments: s {[str]} -- [string representation of a ruamel config] Returns: [str] -- [string that has had all new lines replaced] """ retu...
def from_cps(codepoints: str) -> str: """The unicode datafiles often contain entries in this format, which is super useful for copy-pasting reference test cases. """ return ''.join(chr(int(cp, 16)) for cp in codepoints.split())
def score_to_rating_string(score): """ Convert score to rating """ if score < 1: rating = "Terrible" elif score < 2: rating = "Bad" elif score < 3: rating = "OK" elif score < 4: rating = "Good" else: rating = "Excellent" return rating
def transposed_lists(list_of_lists, default=None): """Like `numpy.transposed`, but allows uneven row lengths Uneven lengths will affect the order of the elements in the rows of the transposed lists >>> transposed_lists([[1, 2], [3, 4, 5], [6]]) [[1, 3, 6], [2, 4], [5]] >>> transposed_lists(transpo...
def build_complement(a): """ The function find out the DNA in correspondence. :param a: str, input by user :return: ans: str """ ans = '' for i in range(len(a)): ch = a[i] if ch == 'A': ans += 'T' if ch == 'T': ans += 'A' if ch == 'G': ...
def _tf_polynomial_to_string(coeffs, var='s'): """Convert a transfer function polynomial to a string""" thestr = "0" # Compute the number of coefficients N = len(coeffs) - 1 for k in range(len(coeffs)): coefstr = '%.4g' % abs(coeffs[k]) power = (N - k) if power == 0: ...
def getPrimeList(n): """ Returns a list of primes < n """ sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,n,2) if sieve[i]]
def lucas(n): """ compute the nth Lucas number """ if n < 0: return None if n == 0: return 2 elif n == 1: return 1 else: return lucas(n - 1) + lucas(n - 2)
def mode_dict(lst): # It returns a dict that contains frequencies of the input. """ >>> mode_dict([3,3,4,4,5,5,6]) {3: 2, 4: 2, 5: 2, 6: 1} >>> mode_dict(["x","y","x"]) {'x': 2, 'y': 1} """ unique_values = {i: 0 for i in list(set(lst))} for i in lst: if i in unique_values.keys():...
def is_comment(txt_row): """ Tries to determine if the current line of text is a comment line. Args: txt_row (string): text line to check. Returns: True when the text line is considered a comment line, False if not. """ if (len(txt_row) < 1): return True if ((txt_row...
def asBoolean(s): """Convert a string value to a boolean value.""" ss = str(s).lower() if ss in ('yes', 'true', 'on'): return True elif ss in ('no', 'false', 'off'): return False else: raise ValueError("not a valid boolean value: " + repr(s))
def degrees(d): """Convert degrees to radians. Arguments: d -- Angle in degrees. """ import math return d / 180 * math.pi
def move1(state,b1,dest): """ Generate subtasks to get b1 and put it at dest. """ return [('get', b1), ('put', b1,dest)]
def interpret_line(line, splitter=','): """ Split text into arguments and parse each of them to an appropriate format (int, float or string) Args: line: text line splitter: value to split by Returns: list of arguments """ parsed = list() elms = line.split(splitter) for e...
def _get_spaces_array_helper(n, memo): """Recursively determine number of spaces at each height. :param n: The height to find num spaces for. :param memo: Memoization table. But that dynamic programming tho! """ # Base case. if n == 1: return memo[n-1] else: # Check if memo ...
def format_version(v): """ Return a PEP 440-compliant version number from VERSION. Using "major.minor.micro" versioning. """ version = f'{v[0]}.{v[1]}.{v[2]}' return version
def key_ratio(map): """ Determine the ratio of major keys to minor keys. A ration of 1 means that each major key has only one minor key. """ map_keys = [len(map[key].keys()) for key in map.keys()] if len(map_keys) == 0: return 0 return sum(map_keys) / float(len(map_keys))
def exist_dict_in_list(d, ls): """Check if an identical dictionary exists in the list.""" return any([d == i for i in ls])
def tag_ocds(mapping, bind, value, args): """ Makes tags array according to OCDS specification """ def check_existing(data): return any(( item.get('id') for item in data )) default = args.get('default') tags = [default] if default else [] if 'contracts...
def case_folder_to_name(folder_name): """Convert name of case folder to case name.""" return folder_name.replace('_', '/')
def get_closest_point(x0, y0, a, b, c): """ Returns closest point from x0,y0 to ax + by + c = 0 """ x = (b * (b * x0 - a * y0) - a * c) / (a ** 2 + b ** 2) y = (a * (-b * x0 + a * y0) - b * c) / (a ** 2 + b ** 2) return x, y
def return_text_by_bounds(options, num, overall): """Find to which group value belongs""" keys = list(options.keys()) key = keys[1] if num < overall[0] - overall[1]: key = keys[0] elif num > overall[0] + overall[1]: key = keys[2] return options[key]
def insert_to_table(db, table, q): """ insert record into table or update an existing record if given query """ if 'record_id' in q: def update_record(record): if record[q['record_id']['key']] == q['record_id']['value']: for key in record: if key in q['val...
def ami_version(ami_info): """ Finds source AMI version AMI tag. Parameters ---------- ami_info : dict AMI information. Returns ------- string Version of source AMI. """ for tag in ami_info['Tags']: if tag['Key'] == 'Version': return tag['Val...
def as_chunks(l, num): """ :param list l: :param int num: Size of split :return: Split list :rtype: list """ chunks = [] for i in range(0, len(l), num): chunks.append(l[i:i + num]) return chunks
def parseValue(value, search: bool = False) -> str: """ Parses a value into a valid value to insert or search in a sqlite database. Whenever the search flag is set, % are appended to start and end of a string value to search for all string to match the pattern. Examples for search=False: - 'st...
def sound_to_ts_K(sound, eq_type='gill_manual', e_a=None): """ Convert speed of sound to """ if eq_type=="gill_manual": return (sound ** 2) / 403 if eq_type=="s_audio": return ((sound / 331.3) ** 2 - 1) * 273.15 + 273.15 else: return None
def pearson_correlation_2(x,y): """incase pandas library is not allowed""" xy = [] x2 = [] y2 = [] for i,j in zip(x,y): xy.append(i*j) x2.append(pow(i,2)) y2.append(pow(j,2)) n = len(x) sxy = sum(xy) sx = sum(x) sy = sum(y) sx2 = sum(x2) sy2 = sum(y2...
def _prefix_linear(s, op, false, true): """Apply associative binary operator linearly. @param s: container @param op: operator @param false, true: values if treating `op` as disjunction """ if not s: return false u = s[0] for v in s[1:]: # controlling value ? if ...
def merge(l, r): """ Merge sort helper @type l: list @type r: list """ merged = [] while len(l) and len(r): if l[0] <= r[0]: merged.append(l[0]) l.pop(0) else: merged.append(r[0]) r.pop(0) return merged + l + r
def collatz(x): """ collatz(x) Determina si un par de numeros son amigos. Parameters ---------- x: int Numero donde se inicia la serie. Returns ---------- output: int Lista de enteros de la se...
def dumb_factor(x, primeset): """ If x can be factored over the primeset, return the set of pairs (p_i, a_i) such that x is the product of p_i to the power of a_i. If not, return [] """ factors = [] for p in primeset: exponent = 0 while x % p == 0: exponent = expo...
def find_arguments_region(edit, view, location): """Returns the start, end index of the selected argument list.""" end = location start = location - 1 open_brackets = 0 while start >= 0: if view.substr(start) == '(': open_brackets -= 1 if open_brackets < 0: start += 1 break ...
def truncate_descriptions(requested_user_rooms): """ Cut descriptions if too long """ for i in range(0, len(requested_user_rooms)): if len(requested_user_rooms[i]['description']) >= 85: requested_user_rooms[i]['description'] = requested_user_rooms[i]['description'][0:85] + "..." ...
def is_loc_search_trace(conf_list, text): """Determine if text is location search that should be included.""" for index in range(len(conf_list)): if text.find(conf_list[index].ident_text) != -1: return True return False
def subtraction(a, b): """subtraction: subtracts b from a, return result c""" a = float(a) b = float(b) c = b - a return c
def translate_sequence(rna_sequence, genetic_code): """Translates a sequence of RNA into a sequence of amino acids. Translates `rna_sequence` into string of amino acids, according to the `genetic_code` given as a dict. Translation begins at the first position of the `rna_sequence` and continues until t...
def find_bucket_key(s3_path): """ This is a helper function that given an s3 path such that the path is of the form: bucket/key It will return the bucket and the key represented by the s3 path """ s3_components = s3_path.split('/') bucket = s3_components[0] s3_key = "" if len(s3_comp...
def create_headers(bearer_token): """Twitter function for auth bearer token Args: bearer_token (string): bearer token from twitter api Returns: headers """ headers = {"Authorization": "Bearer {}".format(bearer_token)} return headers
def contained_name(name1, name2): """ Compares two lists of names (strings) and checks to see if all the names in one list also appear in the other list Parameters ---------- name1: list list of strings to be compared to name2 name2: list list of strings to be compared to name1 ...
def _simplify_circuit_string(circuit_str): """ Simplify a string representation of a circuit. The simplified string should evaluate to the same operation label tuple as the original. Parameters ---------- circuit_str : string the string representation of a circuit to be simplified....
def parse_custom_types(types): """ Parses curstom types format as sent through the service. :param types: curstom types JSON :type types: list :return: custom types dictionary :rtype: dict """ model_types = {} for typ in types: name = typ['name'] model_types[name] = ...
def contains_repeats(str): """Determines if a string has repeat letters. This function is worst case O(n) because it must at worst check each character in the string. n is the length of the string. Arguments: str: the string to examine for repeat letters Returns: ...
def get_thumbs_up(review): """ Gets the total thumbs up given. Parameters ---------------- review : BeutifulSoup object The review from metacritic as a BeautifulSoup object. Returns ---------------- thumbs_up : string Returns the number of total thumbs up gi...
def pkg_key(pkg, type_): """ generate a package key for a given type string Generates a compatible "package key" for a unsanitized package name ``pkg`` of a specific key ``type``. The package string is "cleaned" to replaces select characters (such as dashes) with underscores and becomes uppercase. ...
def copy3(v): """ copy3 """ return (v[0], v[1], v[2])
def listOfSetCommands(sdict): """ Returns a list of vclient command line options, readily compiled for the setVclientData method. """ clist = [] cmds = [] for key, value in sdict.items(): cmds.append("%s %s" % (key, value)) clist.append('-c') clist.append('"%s"' % ','.join(c...
def encode_helper(obj, to_builtin): """Encode an object into a two element dict using a function that can convert it to a builtin data type. """ return dict(__class_name__=str(obj.__class__), __dumped_obj__=to_builtin(obj))
def returnZ(x, mu, std): """ Usage for sampling distribution of the difference between two means: z = mgt2001.samp.returnZ(x, mgt2001.samp.returnE(mu1, mu2), mgt2001.samp.returnStd(std1, std2, n1, n2)) """ return (x - mu) / std
def create_typo_table(typo_chars, score=3): """Create a dictionary mapping typographically similar characters to each other. Input is a list (of even length) of characters. The characters are assummed to be listed in pairs, and their presence states that the first character is typographically simil...
def has_abba(code): """Checks for existence of a 4-letter palindromic substring within `code` The palindromic substring must contain 2 unique characters """ palindrome = None for i in range(len(code) - 4 + 1): # substring = code[i:i + 4] if code[i] == code[i + 3] and code[i + 1] == c...
def section_type(jats_content, section_map): """determine the section type of the jats_content looking at the section_map""" content_section_type = None for section_type, section_match in list(section_map.items()): if jats_content.startswith(section_match): content_section_type = section...
def get_bounding_box_volume(bb): """ :param bb: :return: """ width = bb[1][0] - bb[0][0] depth = bb[1][1] - bb[0][1] height = bb[1][2] - bb[0][2] return width * depth * height
def list_response(response_list, cursor=None, more=False, total_count=None): """Creates response with list of items and also meta data used for pagination Args : response_list (list) : list of items to be in response cursor (Cursor, optional) : ndb query cursor more (bool, op...
def cls_token(idx): """ Function helps in renaming cls_token weights """ token = [] token.append((f"cvt.encoder.stages.{idx}.cls_token", "stage2.cls_token")) return token
def format_value(value): """ Convert a list into a comma separated string, for displaying select multiple values in emails. """ if isinstance(value, list): value = ", ".join([v.strip() for v in value]) return value
def dunderkey(*args): """Produces a nested key from multiple args separated by double underscore >>> dunderkey('a', 'b', 'c') >>> 'a__b__c' :param *args : *String :rtype : String """ return '__'.join(args)
def contain_subset(actual, expected): """Recursively check if actual collection contains an expected subset. This simulates the containSubset object properties matcher for Chai. """ if expected == actual: return True if isinstance(expected, list): if not isinstance(actual, list): ...
def keys_exist(element: dict, *keys): """ Check if *keys (nested) exists in `element` (dict). """ if not isinstance(element, dict): raise AttributeError('keys_exists() expects dict as first argument.') if len(keys) == 0: raise AttributeError( 'keys_exists() expects at lea...
def by_bag(bag, tiddlers): """ Return those tiddlers that have bag bag. """ return [tiddler for tiddler in tiddlers if tiddler.bag == bag]
def str2atom(a): """ Helper function to parse atom strings given on the command line: resid, resname/resid, chain/resname/resid, resname/resid/atom, chain/resname/resid/atom, chain//resid, chain/resname/atom """ a = a.split("/") if len(a) == 1: # Only a residue number: return (None, None, i...
def largest_prime_factor(n: int) -> int: """ Returns the largest prime factor of n """ i = 2 while i * i <= n: if n % i: i += 1 else: n //= i return n
def convertArr(arr): """convert string array into an integer array. Input: arr(list) Output: result(list) """ result = [] for i, val in enumerate(arr): result.append([]) for j in val: result[i].append(int(j)) return result
def clear_object_store( securityOrigin: str, databaseName: str, objectStoreName: str ) -> dict: """Clears all entries from an object store. Parameters ---------- securityOrigin: str Security origin. databaseName: str Database name. objectStoreName: str Ob...
def last(iterator, default=None): """Return last member of an `iterator` Example: >>> def it(): ... yield 1 ... yield 2 ... yield 3 ... >>> last(it()) 3 """ last = default for member in iterator: last = member ...
def organize_combinations(attribute_names, attribute_combinations): """Organise the generated combinations into list of dicts. Input: attribute_name: ["latency", "reliability"] attribute_combinations: [[1,99.99], [2,99.99], [3,99.99], [1,99.9], [2,99.9], [3,99.9]] Output: combina...
def is_input_port(prog, inp, tlsa): """Set the Tlsa object's port data if the input is 'port-like'. Args: prog (State): not changed. inp (str): the input to check if it is a port number. tlsa (Tlsa): the Tlsa object to set with the port number if 'inp' is an integer. Re...
def tail(array): """Return all but the first element of `array`. Args: array (list): List to process. Returns: list: Rest of the list. Example: >>> tail([1, 2, 3, 4]) [2, 3, 4] .. versionadded:: 1.0.0 .. versionchanged:: 4.0.0 Renamed from ``rest`` t...
def merge_dict(*args): """ Merges any number of dictionaries into a single dictionary. # Notes In Python 3.5+, you can just do this: ```python r = {**x, **y} ``` But if you want a single expression in Python 3.4 and below: ```python r = merge_dict(x, y) ``` """ result = {} ...
def getNumFavorited(msg): """Counts the number of favorites the mssage received.""" num_favorited = msg['favorited_by'] return len(num_favorited)
def get_onet_occupation(job_posting): """Retrieve the occupation from the job posting First checks the custom 'onet_soc_code' key, then the standard 'occupationalCategory' key, and falls back to the unknown occupation """ return job_posting.get('onet_soc_code', job_posting.get('occupationalCate...
def fill_na(symbols_map, symbols_list): """Fill symbol map with 'N/A' for unmapped symbols.""" filled_map = symbols_map.copy() for s in symbols_list: if s not in filled_map: filled_map[s] = 'N/A' return filled_map
def helper_int(val): """ Helper function for use with `dict_reader_as_geojson`. Returns `None` if the input value is an empty string or `None`, otherwise the input value is cast to an int and returned. """ if val is None or val == '': return None else: return int(val)
def dataset_word_frequencies(nodes): """ Get frequency of words from an extracted dataset. """ freqs = {} for node in nodes.values(): for t in node.tokens: freqs[t.lower()] = freqs.get(t.lower(), 0) + 1 return freqs
def _preppin_nums(in_list): """Function to getting in_list ready for sorting.""" max_size = 0 output = [] for item in in_list: breakdown = [int(d) for d in str(item)] output.append(breakdown) if len(breakdown) > max_size: max_size = len(breakdown) return [max_size...
def cuda_tpb_bpg_1d(x, TPB = 256): """ Get the needed blocks per grid for a 1D CUDA grid. Parameters : ------------ x : int Total number of threads TPB : int Threads per block Returns : --------- BPG : int Number of blocks per grid TPB : int Th...
def try_convert_comparision_token(token): """ This method tries to convert the given token to be a desired comparision token which can be accepted by the Pyomo model or FSL file. Return None if failure. Args: token (str): the given token to be converted. Returns: Return the con...
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'input_pdb_path': ['pdb'], 'output_pockets_zip': ['zip'], 'output_summary': ['json'], 'input_pockets_zip': ['zip'], 'input_summary': ['json'], 'output_filter_pockets_zip': ['zip'], 'output_pocket_pdb': ['pdb'], '...
def get_routes_len(routes_list): """return list of length of routes""" routes_length = [] for i, this_route in enumerate(routes_list): routes_length.append(this_route.get_length()) return routes_length
def has_body(headers): """ :param headers: A dict-like object. """ return 'content-length' in headers
def get_crater_tuple(line_str): """Build crater tuple from line_str.""" line_list=[] for item in line_str.split('\t'): line_list.append(item) try: t=(line_list[0],line_list[1],float(line_list[2]),float(line_list[3]),float(line_list[4])) except ValueError: t=("","",0,0,0) ...
def apply_to_dict_recursively(d, f): """Recursively apply function to a document This modifies the dict in place and returns it. Parameters ---------- d: dict e.g. event_model Document f: function any func to be performed on d recursively """ for key, val in d.items(): ...