content
stringlengths
42
6.51k
def _build_url(base_url, *args): """ formats a string based on the parameters passed in""" return base_url.format(*args)
def get_email_username(email: str) -> str: """Returns username part of email, if valid email is provided.""" if "@" in email: return email.split("@")[0] return email
def pack_varint(data): """Pack a VARINT for the protocol.""" return bytes([(0x40 * (i != data.bit_length() // 7)) + ((data >> (7 * i)) % 128) for i in range(1 + data.bit_length() // 7)])
def get_resource_and_action(action, pluralized=None): """Return resource and enforce_attr_based_check(boolean) per resource and action extracted from api operation. """ data = action.split(':', 1)[0].split('_', 1) resource = pluralized or ("%ss" % data[-1]) enforce_attr_based_check = data[...
def getcommand(argv): """Retrieve a string version of the command that was invoked at the shell We can't get it exactly because the shell does substitutions on the command-line arguments.""" return ' '.join(argv)
def is_leap(year): """Return True for leap years, False for non-leap years """ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def sanitize_filename(file_name): """Sanitize the filename. Returns a new filename with only filename-safe characters. """ # Removes quotes and other unsafe characters. # This is easier than keeping good characters and trying to be unicode-friendly. badchars = set('''!#$%&*()[]{}'"/\\<>''') ...
def update_list_unique_order(listt, string): """ Given a list *listt* we want to append it with a string We do so by avoiding repetitions, and making the list ordered No need to be super efficient here """ if string not in listt: listt.append(string) listt.sort() return listt
def ip_to_hex(ip_addr, reverse=False): """ Will return hex of ip address. reverse will reverse the octet exemple >>> ip_to_hex('10.1.2.23') '0A010217' >>> ip_to_hex('10.1.2.23',reverse = True) '1702010A' """ array_of_octets = ip_addr.split('.') if reve...
def _str_replace(mystring, rd): """replaces a value based on a key/value pair where the key is the text to replace and the value is the new value. The find/replace is case insensitive. """ import re patternDict = {} myDict = {} for key,value in rd.items(): pattern = re.compile(...
def boolify(s): """ http://stackoverflow.com/questions/7019283/automatically-type-cast-parameters-in-python """ if s == 'True': return True if s == 'False': return False raise ValueError("huh?")
def median(lst): """ Calculates list mediana """ n = len(lst) if n < 1: return None if n % 2 == 1: return sorted(lst)[n//2] else: return sum(sorted(lst)[n//2-1:n//2+1])/2.0
def explode_deps(s): """ Take an RDEPENDS style string of format: "DEPEND1 (optional version) DEPEND2 (optional version) ..." and return a list of dependencies. Version information is ignored. """ r = [] l = s.split() flag = False for i in l: if i[0] == '(': f...
def seq2seq_indexer(max_segment_length): """ hard-coded b2s model output vocabulary """ outputs = { 'O': 0, 'PER': 1, 'ORG': 2, 'GPE': 3, 'LOC': 4, 'MISC': 5, 'FAC': 6, 'TTL': 7, 'MISSING': 8 } outputs['STOP'] = len(outputs) ou...
def _split_comment(lineno, comment): """Return the multiline comment at lineno split into a list of comment line numbers and the accompanying comment line""" return [(lineno + index, line) for index, line in enumerate(comment.splitlines())]
def isinteger(x): """ determine if a string can be converted to an integer """ try: a = int(x) except ValueError: return False except TypeError: return False else: return True
def tAdjust(sTime): """Takes a string representing time. If it has only one/two digit adds ':00' otherwise it only replaces the '.' separator between hours and minutes with ':'. Returns the modified string.""" if len(sTime) <= 2: return sTime + ":00" return sTime.replace('.', ':')
def _convert_labels_for_svm(y): """ Convert labels from {0, 1} to {-1, 1} """ return 2.*y - 1.0
def warning_on_one_line(message, category, filename, lineno, line=None): # pylint: disable=unused-argument """Warning formating method.""" return '\n\n%s:%s\n\n' % (category.__name__, message)
def decrement_items(inventory, items): """ :param inventory: dict - inventory dictionary. :param items: list - list of items to decrement from the inventory. :return: dict - updated inventory dictionary with items decremented. """ for item in filter(lambda item: item in inventory, items): ...
def field_to_flag(f,suffix): """ Convert a field in the form of namespace:termname, along with a flag suffix, to a flag of the form: namespace_termname_suffix """ return "{0}_{1}".format(f.replace(":","_"),suffix)
def eval_AP(ranked_labels): """Recovers AP from ranked labels""" n = len(ranked_labels) pos = sum(ranked_labels) neg = n - pos tp = pos tn = 0 fn = 0 fp = neg sumprec=0 #IPython.embed() for x in ranked_labels: precision = tp / (tp + fp) recall = tp / (tp + fn) if x: s...
def can_open_file(gcode_filepath): """ check whether a given filepath can be opened. If the filepath throws an error, False is returned. If the file can be opened, True is returned. """ if isinstance(gcode_filepath, str): # if gcode_filepath is a string try: # try opening file ...
def get_union(a, b): """ return the union of two lists """ return list(set(a) | set(b))
def parse_resource_ids(resource_id): """ Split the resource ids to a list parameter: (string) resource_id Return the resource_ids as a list """ id_list = resource_id.replace(" ", "") resource_ids = id_list.split(",") return resource_ids
def constructUniqueStringID(values, delimiter="."): """Creates a unique string id based on delimited passed values. The function will strip the last/first delimiters added.-David Wasserman""" final_chained_id = "" for value in values: final_chained_id = "{0}{1}{2}".format(final_chained_id, str(...
def _ofc(id): """OFC ID converter""" return "ofc-%s" % id
def _getitem_from_frame(f_locals, key, default=None): """ f_locals is not guaranteed to have .get(), but it will always support __getitem__. Even if it doesn't, we return ``default``. """ try: return f_locals[key] except Exception: return default
def peak_index(li): """Return index of integer when left integer sum equals right integer sum. input = integers, list output = integer, the index of the value edge = if not possible for peak, return -1 ex. [1,2,3,5,3,2,1] = 3 because left = [1 + 2 + 3] right = [3 + 2 + 1] ex. [1,12,3,3,6,3,1] =...
def extract_sentences(lines): """ Extracts the non-empty sentences and their numbers of the "lines" field in a JSON object from a FEVER wiki-pages JSONL file. """ sentences = [] sentence_index = 0 for line in lines.split('\n'): tokens = line.split('\t') if not tokens[0].isnu...
def isSetNode(node): """ Returns true if the node is a positive reply. """ return (node and node.getType() == "set")
def work_dtype(dtype): """ Return the data type for working memory. """ if dtype == 'float16': return 'float32' else: return dtype
def _get_game_points_color(points: int) -> str: """Returns the markup color that should be used to display the game score.""" assert 0 <= points < 7, "Invalid game points: %s" % points if points < 4: return "33aa33" # green if points == 4: return "ffffff" # white if points == 5: return "ffff33" ...
def unpack_related_queries_response(response): """Unpack response from dictionary and create one dataframe for each ranking and each keyword""" assert isinstance(response, dict), "Empty response. Try again." ranking = [*response[[*response][0]]] keywords = [*response] return response, ranking, key...
def r_int(n): """round() but it returns an integer""" return int(round(n))
def f_to_c(fahrenheit): """Convert to Celsius.""" return (fahrenheit - 32.0) / 1.8
def GetCidrBlock(regional_index=0, subnet_index=0, mask_size=24): """Returns a Cidr Block. Each cloud region should be assigned a unique IP Address Space. And each Subnet within a regional cloud network should also have an unique space. This function returns the IP Address allocation based on the regional and ...
def is_base_class(clsname): """ Returns true if |clsname| is a known base (root) class in the object hierarchy. """ return clsname == 'CefBaseRefCounted' or clsname == 'CefBaseScoped'
def extract_indi_id( tag ): """ Use the id as the xref which the spec. defines as "@" + xref + "@". Rmove the @ and change to lowercase leaving the "i" Ex. from "@i123@" get "i123".""" return tag.replace( '@', '' ).lower().replace( ' ', '' )
def num_to_char(num): """ Function to map a number to a character.""" switcher = { 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f' } return switcher.get(num, ' ')
def calculate_price(base_price: float, tax: float, discount: float) -> float: """ >>> calculate_price(10, 0.2, 0.5) 6.0 >>> calculate_price(10, 0.2, 0) 12.0 """ return (base_price * (1 + tax)) * (1 - discount)
def uniso(timestamp): """Removes T and Z from an ISO 8601-formatted text for readability.""" return timestamp.replace('T', ' ').replace('Z', '')
def get_highest_bench_points(bench_points): """ Returns a tuple of the team with the highest scoring bench :param bench_points: List [(team_name, std_points)] :return: Tuple (team_name, std_points) of the team with most std_points """ max_tup = ("team_name", 0) for tup in bench_points: ...
def clean_html_of_csrf_for_local_comparison(html_data): """Removes content that is omitted by render_to_string(), for fair comparison between the response and local html. Expects that each logical line also occupies one physical line. (Especially the lines to be cleaned.)""" lines = html_d...
def getPass(compromised): """just create a dict with two lists: one for all the acounts, another for the active accounts only""" passwords = {"all":[], "active":[]} for c in compromised: passwords["all"].append(compromised[c]['password']) if 'account_disabled' not in compromised[c]['status']...
def _expand_rec_to_vars(var_items, rec_items, input_order, items_by_key, parallel): """Expand record to apply to number of variants. Alternative approach to _nest_vars_in_rec to combining a single record with multiple variants. """ num_items = var_items var_items = list(var_items)[0] if rec...
def dict2_to_tuplelist(d): """ Converts a dictionary of dictionary items into a list of tuples """ tuple_list = [] data = [] for k, v in d.items(): for w, x in v.items(): tuple_list.append((k, w)) data.append(x) return tuple_list, data
def percentageDecrease(x, y): """Return the percentage decrease from x towards y Args: x: original value y: changed value Returns: percentage decrease from x towards y. """ return (float(x)-float(y))/float(x)
def encode_integer(integer, prefix_bits): """ This encodes an integer according to the wacky integer encoding rules defined in the HPACK spec. """ # log.debug("Encoding %d with %d bits", integer, prefix_bits) max_number = (2 ** prefix_bits) - 1 if (integer < max_number): return byt...
def _format_ref_pr_link(pr_num): """Return a reference link to the PR `pr_num`. This goes at the bottom of the file and allows earlier `_format_inline_pr_link` to work.""" url = f"https://github.com/RobotLocomotion/drake/pull/{pr_num}" return f"[_#{pr_num}]: {url}"
def format_input_source(input_source_name, input_source_number): """Format input source for display in UI.""" return "{} {}".format(input_source_name, input_source_number)
def division(dividend: float, divisor: float) -> float: """Returns the result of division of two numbers. Returns 0 in case of divisor = 0. >>> division(4, 2) 2.0 """ return 0 if divisor == 0 else dividend / divisor
def _parse_source_file_list_blob_key(blob_key): """Parse the BLOB key for source file list. Args: blob_key: The BLOB key to parse. By contract, it should have the format: `${SOURCE_FILE_LIST_BLOB_TAG}.${run_id}` Returns: - run ID """ return blob_key[blob_key.index(".") + 1 :]
def clasificacionDecolor(L,a,b): """ Determina la clasificacion del color mediante los espectros de color Lab param: L: valor L param: a: valor a param: b: valor b regresa v: verde, r: rojo, c: cafe, a: amarillo, n: naranja, az: azul, f: fondo """ if L >= 0 and L <= 88 and a >= -86 and a <= -20 and b >= 3 and ...
def strip_numbers(text): """Strip numbers from text.""" return ''.join(filter(lambda u: not u.isdigit(), text))
def is_single_leaf(tree): """Return true if the tree is actually just a single leaf node.""" return len(tree) == 1 and len(tree[tree.keys()[0]]) == 0
def _strong_gens_from_distr(strong_gens_distr): """ Retrieve strong generating set from generators of basic stabilizers. This is just the union of the generators of the first and second basic stabilizers. Parameters ========== ``strong_gens_distr`` - strong generators distributed by membe...
def cleanup_vm_data(vm_data, uuids): """ Remove records for the VMs that are not in the list of UUIDs. :param vm_data: A map of VM UUIDs to some data. :type vm_data: dict(str: *) :param uuids: A list of VM UUIDs. :type uuids: list(str) :return: The cleaned up map of VM UUIDs to data. :...
def get_path_parameters(parameters): """ get paramters creates the parameter list for the method call """ param_list = [] for param in parameters: if param['paramType'] == 'path': param_name = param['name'] param_list.append('{0}={1}'.format(param_name, param_name)) ...
def prime_sieve(limit): """Deprecated. Found online this implementation of the famous prime sieve. I applogize to the original author for lack of credit. """ limitn = limit+1 primes = dict() for i in range(2, limitn): primes[i] = True for i in primes: factors = range(i,limitn, i) ...
def softsign(x): # DOES NOT WORK WITH NN """This function returns the softsign of x""" return x/(1.0+abs(x))
def naive_inv_count(arr: list) -> int: """Given an unsorted array, finds the number of inversions/swaps required to get a sorted array - Naive Method""" inv_count = 0 n = len(arr) for i in range(n): for j in range(i + 1, n): if arr[i] > arr[j]: inv_count += 1 ...
def get_token_path(token_name): """ Formats the token name into a token path. Returns: The token path """ return "tokens.{}".format(token_name)
def escape(value: str, escape_quotes=False): """Escape string value. Args: value (str): Value to escape. escape_quotes (bool): If we should escape quotes. return: str: Escaped string value. """ # Escape backslashes first since the other characters are escaped with # bac...
def asNormalizedJSON(value): """Answer the value as normalized object, where all values are converted into base objects, dict, list and string. >>> src = dict(aa='bb', cc=[1,2,3,4], dd=dict(ee=123, ff='ABC'), gg={3,4,5,5,6,6,7,7}) >>> result = asNormalizedJSON(src) >>> sorted(result.keys()) ['a...
def headers_add_host(headers, address): """ If there is no Host field in the headers, insert the address as a Host into the headers. :param headers: a 'dict'(header name, header value) of http request headers :param address: a string represents a domain name :return: headers after adding """ ...
def _match_etag(etag, if_none_match_header): """Check to see if an etag matches.""" for if_none_match_ele in if_none_match_header.split(","): if if_none_match_ele.strip() == etag: return True return False
def square_boxes(boxes): """ Takes bounding boxes that are almost square and makes them exactly square to deal with rounding errors. Parameters ---------- boxes : list of tuple of tuple of int The bounding boxes to be squared. Returns ------- boxes : list of tuple of tuple ...
def add(a, b=0, c=0): """Function to add three numbers Notebook: PCP_module.ipynb Args: a: first number b: second number (Default value = 0) c: third number (Default value = 0) Returns: Sum of a, b and c """ d = a + b + c print('Addition: ', a, ' + ', b, ' ...
def get_filename_from_pathname(pathname): """splits the filename from end of string after path separators including }""" # https://github.com/jgstew/tools/blob/master/Python/get_filename_from_pathname.py return pathname.replace('\\', '/').replace('}', '/').split('/')[-1]
def pretty(n): """ Format a number, assumed to be a size in bytes, as a human readable string. """ if type(n) != type(42): return str(n) if n >= (1024*1024*1024) and (n % (1024*1024*1024)) == 0: return str(n//(1024*1024*1024)) + " GB" if n >= (1024*1024) and (n % (1024*1024)) == ...
def get_params(leftovers): """Turn arguments leftovers into service params.""" params = {} for param in leftovers: tokens = param.split("=") if len(tokens) != 2: continue key = tokens[0].replace("--", "") value = tokens[1] params[key] = value return...
def check_renewal(renewal): """check into the auxiliary area is not expired""" if renewal == "yes" or renewal == "no": return True return False
def _datetime_to_html(dict_, html=None): """Convert JSON-LD datetime to HTML.""" if html is None: html = [] datetime = dict_['@value'] html.append('<time datetime="%s">%s</time>' % (datetime, datetime)) return html
def stones(n, a, b): """Hackerrank Problem: https://www.hackerrank.com/challenges/manasa-and-stones/problem Manasa is out on a hike with friends. She finds a trail of stones with numbers on them. She starts following the trail and notices that any two consecutive stones' numbers differ by one of two values...
def insert(arr, x, order="descending"): """ Inserts element in the correct position in sorted array (in the descending/ascending order of absolute values) """ arr.append(x) i = len(arr) - 1 if order == "descending": while (i != 0 and abs(arr[i]) > abs(arr[i - 1])): arr[i...
def decode(current_output): """ bytes to str """ encodings = ["sjis", "utf8", "ascii"] decoded_current_output = "" for enc in encodings: try: decoded_current_output = current_output.decode(enc) break except: continue return decoded_current_...
def getsearchresult(title='', type='', items=None): """Return a dict containing a group of items used for search results""" return {'title': title, 'type': type, 'items': items or []}
def align_trailing_slashes(text_or_lines, trailer='\\'): """ >>> t = 'foo; \\\n bar; \\\n superhornet; \\\n' >>> align_trailing_slashes(t) """ if isinstance(text_or_lines, list): lines = text_or_lines was_list = True else: lines = text_or_lines.splitlines() was_...
def _map_tensor_names(original_tensor_name): """ Tensor name mapping """ global_tensor_map = { "model/wte": "word_embedder/w", "model/wpe": "position_embedder/w", "model/ln_f/b": "transformer_decoder/beta", "model/ln_f/g": "transformer_decoder/gamma", } if origina...
def f7(seq): """ https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def check_file_extension(filename, extension_list): """ Check if the extension file match with the authorized extension list :param string filename: Filename to check :param list extension_list: The list of extension the file have to match to :return: True if the extension is correct, False...
def bw_percent(v, in_speed=None, out_speed=None, bandwidth=None, **kwargs): """ Convert speed to speed to bandwidth percent ratio :param v: :param in_speed: :param out_speed: :param bandwidth: :param kwargs: :return: """ value = v // 1000000 if bandwidth: return value...
def _scan_text_for_literal(text, character): """scans a string until it finds an instance of character and returns the index of it""" count = 0 for c in text: if c is not character: return count, c count = count + 1 return count, None
def _list_product(lst): """Computes product of element of the list.""" result = 1 for item in lst: result *= item return result
def pairs_to_dict(response): """Creates a dict given a list of key/value pairs""" it = iter(response) return dict(zip(it, it))
def match_in_patterns(text, patterns): """Tests if a string matches any regex pattern in the given list.""" return any(pattern.search(text) for pattern in patterns)
def is_required_version(version, specified_version): """Check to see if there's a hard requirement for version number provided in the Pipfile. """ # Certain packages may be defined with multiple values. if isinstance(specified_version, dict): specified_version = specified_version.get('versio...
def unicode_binary_map(target): """Decode binary keys and values of map to unicode.""" # Assumes no iteritems() result = {} for k in target: key = k if isinstance(k, bytes): key = str(k, "utf8") if isinstance(target[k], bytes): result[key] = str(target[k...
def os_to_cpe(os_rec): """Takes a Nexpose XML OS field and finds CPE db id. If no CPE db id exists then a new one is added.""" if os_rec is None: return None result = {} result['f_vendor'] = None result['f_product'] = None result['f_version'] = None result['f_update'] = None re...
def balance_movement(current_balance, trans_code, trans_amount): """Adjusts the current balance based on the transaction type. :param current_balance: The starting balance of the transaction :type current_balance: str :param trans_code: The type of transaction :type trans_code: str :param trans...
def orig_atom(atom,big_table): """ Returns the 0-indexed position of atom from the full list of atoms in the supercell mapped back into the original unit cell """ n = 0 bonds_per_pair = len(big_table[0])/len(big_table) while atom > bonds_per_pair: atom -= bonds_per_pair n += ...
def relpath(origin, dest): """Given two absolute paths, work out a path from origin to destination. Assumes UNIX/URL type relative paths. If origin doesn't *end* with '/' we assume it's a file rather than a directory. If the same paths are passed in : if the path ends with ('/') th...
def get_WCC_2002_Blockage_factor(Structure, verbose=True): """ If the Structure has a single dimension it is assumed a Diameter (hence Pipe) Else it is a Box with w & h -------------------------------------------------------------------- 2017 - 06 - 22 Wollongong Blockage Factor Calculator...
def to_str(s): """ :param s: :return: str value (decoded utf-8) """ if isinstance(s, str): return s if hasattr(s, '__str__'): return s.__str__() return str(bytes(s), 'utf-8', 'strict')
def _kolda_reorder(ndim, mode): """Reorders the elements """ indices = list(range(ndim)) element = indices.pop(mode) return ([element] + indices[::-1])
def transmittance(n1, n2): """ Fresnel equation fro transmittance from medium 1 toward medium 2. :param n1: :param n2: :return: """ return 1 - (((n1 - n2) ** 2) / ((n1 + n2) ** 2))
def RGBToString(rgb_tuple): """ Convert a color to a css readable string """ color = 'rgb(%s,%s,%s)' % rgb_tuple return color
def diff(a, b): """ Return the difference between operations a and b. """ if a is None: a = {} if b is None: b = {} keys = set(a.keys()).union(set(b.keys())) attributes = {} for k in keys: av, bv = a.get(k, None), b.get(k, None) if av != bv: ...
def coerce_date_dict(date_dict): """ given a dictionary (presumed to be from request.GET) it returns a tuple that represents a date. It will return from year down to seconds until one is not found. ie if year, month, and seconds are in the dictionary, only year and month will be returned, the rest ...