content
stringlengths
42
6.51k
def generate_banner_url(hex_: str): """Generate a quick banner image so we can use it when we need it.""" return f"https://res.cloudinary.com/demo/image/upload/w_960,h_450,e_colorize,co_rgb:{str(hex_).replace('#', '')}/one_pixel.png"
def filter_cars(car_list: list, year: int) -> list: """Filter cars by year""" result = [] for car in car_list: if car["year"] < year: result.append(car) return result
def fnv1_64(password, seed=0): """ Returns: The FNV-1 hash of a given string. """ #Constants FNV_prime = 1099511628211 offset_basis = 14695981039346656037 #FNV-1a Hash Function hash = offset_basis + seed for char in password: hash = hash * FNV_prime hash = hash ^ or...
def configure(plugins, *args, **kw): """Setup all plugins by calling them with the passed arguments""" c_plugins = [] for name, plugin_factory in plugins: plugin = plugin_factory(name, *args, **kw) c_plugins.append((name, plugin)) return c_plugins
def _count_words(text): """ Count words in a piece of text. """ if isinstance(text, (list, tuple)): text = "\n".join(text) return len(text.split()) if text else 0
def minutes_to_seconds( minutes: str ) -> int: """Converts minutes to seconds""" return int(minutes)*60
def follow_path(game_data, ship_name): """ Make a ship follow a path, found by the path finding. Parameters ---------- game_data: data of the game (dic). ship_name: name of the space ship (str). Return ------ order: the order to do in order to follow the path <none|left|right|faste...
def _to_bool(value): """Simplified version of the bool filter. Avoids having a dependency on Ansible in unit tests. """ if value == 'yes': return True if value == 'no': return False return bool(value)
def delta2wye(Ra, Rb, Rc): """ ''------RA-------''''R2'''''''''R3'''' '''dd''''''''dd'''''''' y'''''y''''''' '''''RC''''RB''''''''''''''y'''''''''' '''''''d''d''''''''''''''''y'''''''''' ''''''''dd'''''''''''''''''R1''''''''' Returns R1, R2, R3 """ Rt = Ra+Rb+Rc R1 = Rb*Rc/Rt ...
def set_bit(arg, index, val): """ Set the index:th bit of arg to 1 if val is truthy, else to 0, and return the new value. """ mask = 1 << index # Compute mask with just bit 'index' set arg &= ~mask # Clear the bit indicated by the mask if val: arg |= mask # If val is True, se...
def get_domain_resources(area): """ Given the size of a domain, returns a dictionary of the keys 'mills', 'mines', 'lumber', 'farms', 'housing' with appropriate values to be assigned to a domain. We just go round robin incrementing the values. """ res_order = ['farms', 'housing', 'm...
def get_final_values(iterable): """Returns every unique final value (non-list/tuple/dict/set) in an iterable. For dicts, returns values, not keys.""" ret = list() if type(iterable) == dict: return(get_final_values(list(iterable.values()))) for entry in iterable: if (type(entry) ...
def get_size_json(doc): """Returns the size of the corresponding tree of the given JSON.""" size = 0 if isinstance(doc, dict): # OBJECT # Count the node of the object and all its keys. size += 1 + len(doc.keys()) # Add the sizes of all values. for key, val in doc.items(): ...
def extract_bits(source, positions): """Get information from the source data based on bit positions. This function will extract each bit sequentially, meaning that as bits are removed, they will offset the position of later bits. The result will affect the osition of all existing and added bit...
def is_multi_channels_image(shape): """Returns true when shape is (channels, rows, cols). Convolutional Neural Network(CNN) and fully connected neural network(NN) require different shape of input. Tuple (channels, rows, cols) and a scalar value. If it detects invalid shape, raise RuntimeError. ...
def get_values_lengthes(dictionary): """returns the sum of the lengthes of values of a dictionary""" return sum(map(lambda value: len(value), dictionary.values()))
def format_star_input(inp): """ *inputs are always wrapped in tuple. Formats *inputs of form "src", "src, src" but also "[src, src]" or ""(src,src") so that 1D lists/tuples come out. """ if len(inp) == 1: return inp[0] return list(inp)
def num_unique_trace_events(data): """Returns the total number of unique traces captured """ unique_events = {} for event in data["traceEvents"]: if "name" in event: unique_events[event["name"]] = 1 return len(unique_events)
def convertFrom1D(list): """ Convert from a list to a matrix with the appropriate dimensions """ return [[x] for x in list]
def check_size(indices: list, queries: list) -> int: """ Check whether size of all indices and queries are the same :param list indices: list of all indices :param list queries: list of all queries :returns: the size when size of all indices and queries are the same or -1 if lists does no...
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): """ resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_' Modification Note: (unless it's the special...
def tupleToStr(obj): """ Function for/to <short description of `netpyne.batch.batch.tupleToStr`> Parameters ---------- obj : <type> <Short description of obj> **Default:** *required* """ if type(obj) == list: for item in obj: if type(item) in [list, d...
def file_size(file_info): """This function receives a tuple to store information about a file: its name, its type and its size in bytes. It returns the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places.""" file_name, file_type, file_size = file_info return("{:.2f}".format(file_size / 1024))
def is_valid_with_skip_back_two(s: str, index1: int, index2: int) -> bool: """ skip one to validate left text """ while index1 < index2: if s[index1] != s[index2]: return False index1 += 1 index2 -= 1 return True
def playoff_series_info(rnd, srs): """Get the title of current round/series""" title = { "01": { "1": "First Round: East #1 vs. Wildcard #2", "2": "First Round: Atlantic #2 vs. Atlantic #3", "3": "First Round: East #2 vs. Wildcard #1", "4": "First Round: M...
def is_array(output): """Check if `output` behaves as np.array (simple).""" return hasattr(output, 'shape')
def _get_fuzzer_module(fuzzer): """Get the module for |fuzzer|'s fuzzer.py.""" return 'fuzzers.{}.fuzzer'.format(fuzzer)
def my_isinstance(in_object, in_class): """ :param in_object: an object :param in_class: a class :return: returns boolean value if class names match """ return in_object.__class__.__name__ == in_class.__name__
def string2bytes(item): """ Converts string to bytes format. 'A' -> b'A' """ if type(item) == str: return bytes(item, 'utf-8') else: return "Wrong data type expected string, received %s" % str(type(item).__name__)
def to_usd(my_price): """ Converts a numeric value to usd-formatted string, for printing and display purposes. Param: my_price (int or float) like 4000.444444 Example: to_usd(4000.444444) Returns: $4,000.44 """ return f"${my_price:,.2f}" #> $12,000.71
def app_info_to_filenames(appinfo): """Takes a list of apps and returns their filenames.""" output = {} for app in appinfo: output[app.get_filename()] = app return output
def join(obj, arg): """ Uses to join on template. """ if type(obj) in (list, tuple): return arg.join(obj) return ''
def UnZeroMatrix(matrix): """ replaces all instances of 0.0000 in the matrix with the lowest observed non-zero value assumes first row and first column of matrix are descriptors """ minNonZero = min([float(m) for m in matrix[1][1:]]) for line in matrix[2:]: for el in line[1:]: if float(el) !=...
def _sorted_properties(orig, prioritized): """Return the sorted properties. :param set orig: original properties. :param list prioritized: properties to be prioritized. The properties will be sorted by: 1. sorted prioritized properties; 2. "*"; 3. the rest properties. """ ret = [] ...
def check_api_token(api_key): """Check if the user's API key is valid.""" if (api_key == '123abc'): return True else: return False
def filter_non_printable(str): """ """ return ''.join([c for c in str if ord(c) > 31 or ord(c) == 9])
def num2str(num,precision): """ Given an float number and desired precision number precision, returm str(num) """ return "%0.*f"%(precision,num)
def all_user(iterable): """ Performs essentially the same function as the builtin all() command. If all items in the list are true, this will return true :param iterable: :return: true/false """ for element in iterable: if not element: return False return True
def _process_anchoring(model_dict): """Process the specification that governs how latent factors are anchored. Args: model_dict (dict): The model specification. See: :ref:`model_specs` Returns: dict: Dictionary with information about anchoring. See :ref:`anchoring` """ anchinfo = ...
def bitval_to_value(bitval, bits=8, min=0, max=1): """ Converts a bits-bit number into its physical value for range from min to max :param bitval: (int) value in bits-bit (e.g. 8-bit from 0 to 2^8-1) :param bits: (int) number of bits of resolution :param min: (float) minimum of range :param max: (...
def hex2rgb(value): """Converts a hexadeximal color string to an RGB 3-tuple EXAMPLE ------- >>> hex2rgb('#0000FF') (0, 0, 255) """ value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3))
def check_duplicate_preferences(preferences: list) -> bool: """ Method for checking duplicates in preferences """ ids = set() for pref in preferences: if pref in ids: return True ids.add(pref) return False
def scan_frame(reference_start): """ Find the frame of a sequencing using the alignment starting position :param int reference_start: Alignment start position :return: Number of bases to slice sequence to make it in-frame :rtype: int """ in_frame_adjustment = 0 while (reference_start + ...
def findUniqueContours(inlist): """ Find list of unique contours""" uniqueContourList = [] for item in inlist: if item not in uniqueContourList: uniqueContourList.append(item) return uniqueContourList
def _transform_array(data, is_array, is_scalar): """Transform an array into a scalar, single value array or return in unmodified.""" if not is_array: return data[0] if is_scalar: return [data[0]] return data
def _resolve_refs(variables: dict, ref_table: dict) -> dict: """Replaces `ref_table` refs while copying `variables` to the output.""" new_vars = {} for num, kvpair in enumerate(variables.items()): k, v = kvpair new_vars[k] = ref_table[str(v)] return new_vars
def kgtk_stringify(x): """If 'x' is not already surrounded by double quotes, add them. """ # TO DO: this also needs to handle escaping of some kind if not isinstance(x, str): x = str(x) if not (x.startswith('"') and x.endswith('"')): return '"' + x + '"' else: return x
def fnRK4_vector(f, dt, x,t,Q=None,L=None): """ fnRK4_vector implements the Runge-Kutta fourth order method for solving Initial Value Problems. f : dynamics function dt : fixed stepsize x : state vector t : current time instant. Refer to Burden, Faires (2011) for the RK4 method. ...
def compute_suffix_array(pattern): """ Compute temporary array to maintain size of suffix which is same as prefix Time/space complexity is O(size of pattern) """ len_pattern = len(pattern) temp_array = [0] * len_pattern index = 0 i = 1 while i < len_pattern: if pattern[i] ==...
def _replace_chars(name, substitutes): """ Replace characters in `name` with the substitute characters. If some of the characters are both to be replaced or other characters are replaced with them (e.g.: ? -> !, ! ->#), than it is not safe to give a dictionary as the `substitutes` (because it is un...
def func_a_args(a=2, *args): """func. Parameters ---------- a: int args: tuple Returns ------- a: int args: tuple """ return None, None, a, None, args, None, None, None
def check_or_form_list_of_str(item, path): """ Check that `item` is a string or a list of strings. If `item` is a string, the function returns a list that contains a single item (the string). Args: item (should be a str or a list) path (str): Full path of `item` for logging purposes """ if is...
def wheel_slip_velocity(v_vehicle, F, slip_rate): """ It computes wheel slip velocity from slip_rate and propulsion Func. """ v_wheel = v_vehicle if F >= 0: v_wheel = v_vehicle / (slip_rate + 1) if F < 0: v_wheel = v_vehicle * (slip_rate + 1) return v_wheel
def first_line(s: str) -> str: """Returns the first line of a multi-line string""" # Just return the 's' if it is empty or 'None'. return s.splitlines()[0] if s else s
def cake(number): """ Returns True if number is cake """ # n-th lazy caterer number is (n**3 + 5*n + 6) / 6 n = 1 while True: p = (n**3 + 5*n + 6) / 6 if p == number: return True elif p > number: return False n = n + 1
def parse_dss_bus_name(dss_bus_name: str, sep='.') -> str: """ Given a bus name string that may include phase from opendss, returns just the busname. Assumes that dss appends bus names with phases, separated by '.' Ex: 'sourcebus.1.2.3' -> 'sourcebus' """ return dss_bus_name.split(sep)[0]
def format_params(url, params): """format_params will add a list of params (?key=value) to a url Parameters ========== params: a dictionary of params to add url: the url to add params to """ # Always try to get 100 per page params["per_page"] = 100 count = 0 for para...
def get_byte(number: int, i: int): """ returns the i-th byte from an integer""" return (number & (0xff << (i * 8))) >> (i * 8)
def get_strings(src_file): """getting strings from file""" res = [] try: res = open(src_file,'r').readlines() res = [x.strip() for x in res] except: res = [] return res
def write_ellipsoid(sz, loc, mat, cut_neg=[-1, -1, -1], cut_pos=[1, 1, 1], cut_global=[1,1,1], orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0): """ @brief Writes an ellipsoid. @param sz [size u_vec 1, size uvec 2, size uvec 3] @param loc locati...
def set_username(strategy, details, user, social, *args, **kwargs): """This pipeline function can be used to set UserProfile.has_username_set = True Normally not used if the auto-generated username is ugly """ if not user: return None response = None if hasattr(user, 'profile'): ...
def ipNum( w, x, y, z ): """Generate unsigned int from components of IP address returns: w << 24 | x << 16 | y << 8 | z""" return ( w << 24 ) | ( x << 16 ) | ( y << 8 ) | z
def _max_thread_depth(thread): """compute the length deepest branch of the thread""" if not thread['children']: return 1 return 1 + max([_max_thread_depth(reply) for reply in thread['children']])
def string_to_ascii(string): """ Encodes a string in ascii (bytes) (> bytes/ascii) """ string_bytes = string.encode('ascii') return string_bytes
def bubblesort(x): """ Describe how you are sorting `x`: Start at the beginning of the list and for each pair of elements i and i+1 flip the order if i+1 is smaller than i. Iterate over the list pairwise until the list is sorted. """ if (len(x) > 1): j=1 while j!=0: j=0 for i in range(...
def flattenByComprehension(lista): """ Flattens a list of lists by comprehension. Args: lista (list): a nested list. Returns: (list): flattened list. """ return [val for sublist in lista for val in sublist]
def _len_version(v_list: list) -> int: """ Compute length of the component, but without the last component if it is a dev or post""" l = len(v_list) return l - 1 if v_list[-1].startswith("dev") or v_list[-1].startswith("post") else l
def double_qoute(s): """Add double quotes to s, needed to produce C strings. >>> double_qoute('program') '"program"' """ return '"' + s + '"'
def to_zebra_params(params): """ Transforms the given `params` dict to values that are understood by Zebra (eg. False is represented as 'false') """ def to_zebra_value(value): transform_funcs = { bool: lambda v: 'true' if v else 'false', } return transform_funcs.get(...
def read_worksheet(worksheet_name, workbook): """Read worksheet table to list of dicts """ output = [] try: data = workbook[worksheet_name].values except KeyError: print("Worksheet {} not found".format(worksheet_name)) return output keys = next(data) data = list(data...
def merge(left, right): """ merges two lists (arrays), sorting them in the process Return a new merged list Takes overall O(n log n) time """ l = [] i = 0 j = 0 while i<len(left) and j<len(right): if left[i] < right[j]: l.append(left[i]) ...
def generate_uniform_distribution(k): """Generate the discrete uniform distribution.""" raw_distribution = [1] * k sum_raw = sum(raw_distribution) prob = [float(y) / float(sum_raw) for y in raw_distribution] return prob
def _pan_prefix(field_data): """ Get prefix of PAN """ return field_data[:9]
def get_hexa(num: int) -> str: """Returns hexadecimal format of decimal integer. """ return str(hex(num))[2:].upper()
def get_aln_mapping(aln_seq1, aln_seq2): """ :return ret1: dict[i]->j i in seq1; j in seq2 :return ret2: dict[j]->i j in seq2; i in seq1 """ if len(aln_seq1) != len(aln_seq2): return None i = j = 0 ret1 = {} ret2 = {} for k in range(len(aln_seq1)): if aln_seq1[k] ...
def parse_morphs(morph): """Parses the strings representing morphological tags into a series of dictionaries, e.g. [ gender=NEUTER|case=NOMINATIVE|number=SINGULAR|degree=POSITIVE, number=SINGULAR|person=PERSON_3|mood=INDICATIVE|voice=ACTIVE|tense=PRESENT, _, gender=MA...
def retrieve_fields(arg: str) -> str: """Strip and filter out the empty elements from the string. :type arg: ``str`` :param arg: The string from which we want to filter out the empty elements. :return: Filtered out result. :rtype: ``str`` """ return ",".join([x.strip() for x in arg.split...
def get_air_quality_qualitative_name(index: int) -> str: """ Gets the qualitative name for the air quality based on the index ordinal supplied More information: https://openweathermap.org/api/air-pollution """ if index == 1: return "Good" elif index == 2: return "Fair" elif...
def legitimize(text): """Converts a string to a valid filename. """ import platform os_ = platform.system() # POSIX systems text = text.translate({ 0: None, ord('/'): '-', ord('|'): '-', }) if os_ == 'Windows': # Windows (non-POSIX namespace) text...
def calculate_penalty(row): """ Calculate penalty as `(current_amount_due + total_paid) - fine_level1_amount` """ # If current amount due is negative or ticket was dismissed, # penalty is null if float(row[14]) < 0 or row[16] == 'Dismissed': penalty = None else: penalty = (f...
def get_free_offer(items, item, offer): """ Remove items that have been offered as free for another deal """ def get_required_offer_items(item, offer): """ If the deal is on the same item we need one more item in the basket for it to be valid """ required = offer...
def flatCommands(cmds): """ Given a list of commands it will return a single one concatenated by '&&' so they will be executed in sequence until any of them fails. :type cmds: list :param cmds: List of strings that contains commands. :rtype: string :return: A single string with the com...
def get_user_group(user_group): """ Formats a user and group in the format ``user:group``, as needed for `chown`. If user_group is a tuple, this is used for the fomatting. If a string or integer is given, it will be formatted as ``user:user``. Otherwise the input is returned - this method does not perfo...
def _and(*args): """Helper function to return its parameters and-ed together and bracketed, ready for a SQL statement. eg, _and ("x=1", "y=2") => "(x=1 AND y=2)" """ return " AND ".join(args)
def check_and_return_expected(value, undefined_value, expected_value, name=None): """ Return the expected value while checking if the given value is undefined or equal to the expected value. """ if (undefined_value is None and value is None) or (undefined_value == value): return expected_val...
def _unicode_sub_super(string, mapping, max_len=None): """Try to render a subscript or superscript string in unicode, fall back on ascii if this is not possible""" string = str(string) if string.startswith('(') and string.endswith(')'): len_string = len(string) - 2 else: len_string =...
def digital_root(n): """Digital root of number passed.""" if n < 10: return n else: total = 0 for i in str(n): total += int(i) return digital_root(total)
def dimdict2sql(dim, dimdict, join="\n"): """ Takes a dimension dict and transforms it to a SQL statement for recoding levels """ sql_when = ["case"] sql_when += [f"when {dim} = '{index}' then '{level}'" for index, level in dimdict.items()] sql_when += ["else '-1' end"] sql_when = join.join(...
def meters_to_miles(meters): """ helper function to convert meters to miles """ return round(float(meters) * 0.00062137,2)
def remdup_preserve_order(lst): """ Removes duplicates from a list but maintains the order. Notes ----- see: https://www.peterbe.com/plog/uniqifiers-benchmark """ val = set() val_add = val.add return [x for x in lst if not ((x in val) or val_add(x))]
def str_split_all(str_in,f): """ example: x_y_z =>[x,y,z] """ l = str_in.split(f) return l
def determine_color(memory_limit_gb, memory_usage_gb, dark_background=False): """Determine a display color based on percent memory usage Parameters ---------- memory_limit_gb : int Overall memory limit in gigabytes memory_usage_gb : int Memory usage value in gigabytes dark_b...
def interpret_useconds(sel_list, useconds_of_selections): """ interprets value of useconds. returns 0 if all the useconds are zero. i.e. that means skipop (expand_ratio=0) """ assert len(sel_list) == len(useconds_of_selections) result = 0 for selection, usecond in zip(sel_list, useconds_of...
def blob_text(filenames): """Create a blob of text by reading in all filenames into a string""" return '\n'.join([open(filename).read() for filename in filenames])
def nb2fr(n): """Displays a number in French format. Keyword argument: n -- float: number to format """ return str(n).replace('.', ',')
def ps(s): """Process String: convert a string into a list of lowercased words.""" return s.lower().split()
def largest_element(a, loc=False): """ Return the largest element of a sequence a. """ maxval= a[0] maxloc= 0 for i in range(1, len(a)): if a[i] > maxval: maxval = a[i] maxloc =i if loc==True: return maxval, maxloc else: return maxval
def loop_bodies(k: int, url_path: str, lines: list) -> dict: """ We loop lines here to extract : - query params - command to execute - response to return """ extracted_params = { "command": [], "body_params": [], "query_params": [], "res": "request sent.", ...
def _is_quoted(s): """Check whether this string is a quoted identifier.""" s = s.replace('_', 'a') return not s.isalnum() or s[:1].isdigit() or s != s.lower()
def remove_extra_space(text): """Remove multiple occurrence of whitespaces """ text = " ".join(text.split()) return text