content
stringlengths
42
6.51k
def cross3D(v1, v2): """Calculates the vector cross product of two 3D vectors, v1 and v2""" return (v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0])
def translate_size(string): """ Translate a size on the string form '1337 kb' and similar to a number of bytes. """ try: count, unit = string.split(' ') count = int(count) except (ValueError, TypeError): return si_prefix = { 'k': 1e3, 'K': 1e3, 'M...
def hook_get_prepare_tx_query(table: str, metadata_table:str, model_date: str) -> str: """Returns the query that prepares the transactions to aggregate. It loads all customer transactions and aggreagets it into a single row, so they are prepared for prediction. Ideally it's loading from the table BQ_LTV_ALL_PE...
def get_diffs(global_state: list, local_state: list) -> list: """ Return list of transactions that are present in `global_state` but not in `local_state` """ return list(filter(lambda elem: elem not in local_state, global_state))
def quick_sort(arr_raw, low, high): """ args: arr_raw: list to be sorted return: arr_sort: list sorted """ def helper(arr, low, high): # recurrent helper pivtol = arr[high] # center for partition pivtol_pos = high # record the psotion high -= 1 # s...
def phases_from_str(phases_str): """ Parses a command line argument string describing the learning rate schedule for training. :param phases_str: string formatted like 60000:1e-3,20000:1e-4 for 60k iterations with learning rate 1e-3 followed by 20k iterations with learning rate 1e-4. :return: list o...
def get_audio_dbfs(audios): """ Gets a list of dBFS and max_dBFS values from Pydub audio segment Objects. :param audios: A list of Pydub audio segment Objects. :return: Retuns a list of dBFS values and a list of max_dBFS values. """ dbfs_list = [] max_dbfs_list = [] for audio in audios...
def parse_errors(nodes, errors): """Count errors in nodes. Args nodes: list of tuples of two items errors: dict representing error values Returns Tuple (int of key erros, int of val errors, string of error output). """ key_errors = len([1 for fst, snd in nodes if snd == error...
def normalize_ip(ip): """ Transform the address into a standard, fixed-length form, such as: 1234:0:01:02:: -> 1234:0000:0001:0002:0000:0000:0000:0000 1234::A -> 1234:0000:0000:0000:0000:0000:0000:000a :type ip: string :param ip: An IP address. :rtype: string :return: The nor...
def to_camel(s): """returns string to camel caps. Example to_camel('foo_bar') == 'FooBar' """ # assume the titles are ascii, else class name fail # "%s doesn't convert to a good string for a class name" % s) return str(s.title().replace('_', ''))
def check_instance(obj): """ Check if a specific object con be inserted in the json file. :param obj: an object of the optimization to be saved :type obj: [str,float, int, bool, etc.] :return: 'True' if the object can be inserted in a json file, 'False' otherwise :rtype: bool """ types ...
def is_fitting_ec_numbers(ec_number_one: str, ec_number_two: str, wildcard_level: int) -> bool: """Check whether the EC numbers are the same under the used wildcard level. Arguments ---------- * ec_number_one: str ~ The first given EC number. * ec_number_two: str ~ The second given EC number. *...
def create(name, vcpus, ram, disk, **kwargs): """Create flavor(s).""" url = '/flavors' req = {'flavor': {'name': name, 'vcpus': vcpus, 'ram': ram, 'disk': disk}} req['flavor'].update(kwargs) return url, {'json': req}
def try_strftime(x, *args, **kwargs): """Try strftime. In case of failure, return an empty string""" try: return x.strftime(*args, **kwargs) except: return ''
def indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level): """ Use 4 spaces per indentation level. For really old code that you don't want to mess up, you can continue to use 8-space tabs. """ if indent_char == ' ' and indent_level % 4: ...
def struct_init(*args): """Struct initializer >>> from emlearn import cgen >>> cgen.struct_init([ 1, 2, 3 ]) "{ 1, 2, 3 }" """ return '{ ' + ', '.join(str(a) for a in args) + ' }'
def check_equal(lst): """ Return True if all items in `lst` are equal, False otherwise. Note that check_equal([1, True]) is True. """ return not lst or lst.count(lst[0]) == len(lst)
def hms_to_sec(hms): """ Converts a given half-min-sec iterable to a unique second value. Parameters ---------- hms : Iterable (tuple, list, array, ...) A pack of half-min-sec values. This may be a tuple (10, 5, 2), list [10, 5, 2], ndarray, and so on Returns ------- ou...
def sidebar_skin(color, light=False): """Returns a collection of classes to style the main sidebar bar.""" if color: style = 'light' if light else f'dark' return f'sidebar-{style}-{color}' return ''
def tabuleiro_tpl(tab): """ Converte o tabuleiro de tuplos para listas Parametros: tab (lista): Tabuleiro a converter Retorna: tabuleiro (tuplo): Tabuleiro do tipo tuplo """ for i in range(len(tab)): tab[i] = tuple(tab[i]) tabuleiro = tuple(ta...
def nextTagID(tags): """Returns the next tag ID given the list of tags""" return 0 if not tags else sorted(tags, key=lambda x: x['id'])[-1][0] + 1
def knightList(x,y,int1,int2): """sepcifically for the rook, permutes the values needed around a position for noConflict tests""" return [(x+int1,y+int2),(x-int1,y+int2),(x+int1,y-int2),(x-int1,y-int2),(x+int2,y+int1),(x-int2,y+int1),(x+int2,y-int1),(x-int2,y-int1)]
def expand_placeholder(placeholder, full_names): """ Link references whos names are longer than their bytecode representations will get truncated to 4 characters short of their full name because of the double underscore prefix and suffix. This embedded string is referred to as the `placeholder` ...
def split_word_at_pipe(word): """ This function splits a word separated by a | symbol Args: word (str): Word with a pipe symbol Returns: A list of split items Examples: >>> split_word_at_pipe('Bilderbuch|Absturz') ['Bilderbuch', 'Absturz'] ...
def int_round(x: int, n: int) -> int: """Return the multiple of `n` the closest to the integer `x`.""" return n * round(x / n)
def _attr_set(attr, value): """Create an 'update 'dictionary for update_workspace_attributes()""" return { "op" : "AddUpdateAttribute", "attributeName" : attr, "addUpdateAttribute" : value }
def is_unbound(method): """Checks if it is an unbounded method.""" return not (hasattr(method, '__self__') and method.__self__)
def assert_bool(name: str, value: str) -> int: """ Makes sure the value is a integer that represents a boolean, otherwise raises AssertionError :param name: Argument name :param value: Value :return: Value as integer """ if int(value) not in [0, 1]: raise AssertionError( ...
def inrange(imagine, punct): """Punctul apartine imaginii """ ccx, ccy = punct length = len(imagine[0]) width = len(imagine) if ccx < width and ccx > -1 and ccy < length and ccy > -1: return 1 return 0
def link_photos(entry_text, entry): """Summary Args: entry_text (str): Journal text entry entry (dict): DayOne entry dict Returns: TYPE: journal text entry with inserted image links """ if "photos" not in entry: return entry_text photo_list = [] for ...
def calculate_new_average(avg, N, new_val): """Calculate new average given a new value and an existing average. Args: avg: The old average value. N: The old number of data points averaged over. new_val: The new value to recalculate the average with. Returns: The new average...
def is_permutation_nocounter(str_1, str_2) -> bool: """Check if str_1 and str_2 are permutations of each other Use str.count to calculate appearance frequency of each unique character Arguments: str_1 -- first string str_2 -- other string Returns: True if str_1 is permutation of str_2 ...
def get_agent_consumer_id(agent_type, agent_host): """Return a consumer id string for an agent type + host tuple. The logic behind this function, is that, eventually we could have consumers of RPC callbacks which are not agents, thus we want to totally collate all the different consumer types and provi...
def get_status(summary): """ { "web html": { "total": 1, "total unavailable": 0, "total incomplete": 1 }, "web pdf": { "total": 1, "total unavailable": 0 }, "renditions": { "total": 1, "total unavailable": 0 }, ...
def _is_async_func(func): """ returns if a func is a async function not a generator :rtype: bool """ return isinstance(func, type(lambda: (yield)))
def str2sec(time_str): """ Convert hh:mm:ss to seconds since midnight :param time_str: String in format hh:mm:ss """ split_time = time_str.strip().split(":") if len(split_time) == 3: # Has seconds hours, minutes, seconds = split_time return int(hours) * 3600 + int(minutes...
def metrics(tp, pred_len, gt_len, labels_num): """ Calc metrics per image :param tp: :param pred_len: :param gt_len: :param labels_num: :return: """ fn = gt_len - tp fp = pred_len - tp tn = labels_num - tp - fn - fp if tp == 0: recall, precision, f1 =...
def convert_kwh_gwh(kwh): """"Conversion of MW to GWh Input ----- kwh : float Kilowatthours Return ------ gwh : float Gigawatthours """ gwh = kwh * 0.000001 return gwh
def str_attach(string, attach): """ Inserts '_' followed by attach in front of the right-most '.' in string and returns the resulting string. For example: str_attach(string='sv.new.pkl', attach='raw') -> 'sv.new_raw.pkl) """ string_parts = list(string.rpartition('.')) string_parts.i...
def renameEnv(lines, newname): """ Rename environment """ for i, line in enumerate(lines): if line.startswith('name: '): lines[i] = 'name: ' + newname return lines
def _get_epsg(lat, zone_nr): """ Calculates the epsg code corresponding to a certain latitude given the zone nr """ if lat >= 0: epsg_code = '326' + str(zone_nr) else: epsg_code = '327' + str(zone_nr) return int(epsg_code)
def backspace_compare(first: str, second: str) -> bool: """Edits two given strings and compare them. Args: first: string for correction and comparison; second: string for correction and comparison. Returns: True if both edited arguments are equal, otherwise False. """ fir...
def has_double_pair(text): """Check if a string has a pair appearing twice without overlapping""" # Go over each pair of letters, and see if they occur more than once. # The string.count method checks only for non-overlapping strings. # Return True if there are two or more, False otherwise. for i i...
def bubble_sort(l, debug=True): """ https://www.quora.com/In-laymans-terms-what-is-the-difference-between-a-bubble-sort-and-an-insert-sort http://stackoverflow.com/questions/17270628/insertion-sort-vs-bubble-sort-algorithms Every Iteration, it will try to bubble the Max number to the end of the list ...
def scaleFont( c, chrLen, genLen, axLen, options, data): """ find the approximate font size that will allow a string, c, to fit in a given space. """ fs = 9.0 if len(c) * float(fs)/900.0 <= ( float(chrLen)/ genLen) * axLen: return fs while fs > 1: if len(c) * float(fs)/900.0 <= ( float(ch...
def validate_command_line_parameter_keyword(keyword): """ Validates ``CommandLineParameter``'s `keyword` parameter. Parameters ---------- keyword : `None` or `str` Keyword parameter to validate. Returns ------- keyword : `None` or `str` The validated keyword par...
def clean_locals(data): """ Clean up locals dict, remove empty and self/session/params params and convert to camelCase. :param {} data: locals dicts from a function. :returns: dict """ if data.get('params') is not None: return data.get('params') else: return { ...
def count_points(cards): """Count the total victory points in the player's hand, deck and discard pile return the number of victory points """ vp = 0 for card in cards: vp += card.Points return vp
def voc_ap(rec, prec): """ Calculate the AP given the recall and precision array 1st) We compute a version of the measured precision/recall curve with precision monotonically decreasing 2nd) We compute the AP as the area under this curve by numerical integration. """ rec.insert(0, 0.0) ...
def wrap(text, length): """Wrap text lines based on a given length""" words = text.split() lines = [] line = '' for w in words: if len(w) + len(line) > length: lines.append(line) line = '' line = line + w + ' ' if w is words[-1]: lines.appe...
def commoncharacters(s1: str, s2: str) -> int: """ Number of occurrences of the exactly same characters in exactly same position. """ return sum(c1 == c2 for c1, c2 in zip(s1, s2))
def vector_sub(vector1, vector2): """ Args: vector1 (list): 3 value list vector2 (list): 3 value list Return: list: 3 value list """ return [ vector1[0] - vector2[0], vector1[1] - vector2[1], vector1[2] - vector2[2] ]
def printtime(t0: float, t1: float) -> str: """Return the elapsed time between t0 and t1 in h:m:s formatted string Parameters: t0: initial time t1: final time Returns: elapsed time """ m, s = divmod(t1 - t0, 60) h, m = divmod(m, 60) fmt = '%d:%02d:%02d' % (h, m, s) ...
def _uses_auto_snake(super_class): """Get the whether auto-snake is in use or not""" return getattr(super_class, "__deserialize_auto_snake__", False)
def mean(vals): """Calculate the mean of a list of values.""" return sum([v for v in vals])/len(vals)
def get_captions(context): """Extract captions from context and map them to more readable names.""" caption_keys = ( ('BO_SAVE_CAPTION', 'save_caption'), ('BO_SAVE_AS_NEW_CAPTION', 'save_as_new_caption'), ('BO_SAVE_AND_CONT_CAPTION', 'save_and_cont_caption'), ('BO_SAVE_AND_ADD_AN...
def _string_type(val, loc): """Returns 'string' unless the value is a paths based on the runtime path of the module, since those will not be accurite.""" if not val.startswith(loc): return 'string' return None
def si_prefix(n, prefixes=("", "k", "M", "G", "T", "P", "E", "Z", "Y"), block=1024, threshold=1): """Get SI prefix and reduced number.""" if (n < block * threshold or len(prefixes) == 1): return (n, prefixes[0]) return si_prefix(n / block, prefixes[1:])
def removeForwardSlash(path): """ removes forward slash from path :param path: filepath :returns: path without final forward slash """ if path.endswith('/'): path = path[:-1] return path
def insertion_sort2(L): """ Slightly improved insertion sort Complexity: O(n ** 2) """ for i in range(len(L)): key = L[i] j = i - 1 while j > -1 and L[j] > key: L[j + 1] = L[j] j -= 1 L[j + 1] = key return L
def power(base: int, exponent: int) -> float: """ power(3, 4) 81 >>> power(2, 0) 1 >>> all(power(base, exponent) == pow(base, exponent) ... for base in range(-10, 10) for exponent in range(10)) True """ return base * power(base, (exponent - 1)) if exponent else 1
def rectangles_collide(x1, y1, w1, h1, x2, y2, w2, h2): """ Return whether or not two rectangles collide. Arguments: - ``x1`` -- The horizontal position of the first rectangle. - ``y1`` -- The vertical position of the first rectangle. - ``w1`` -- The width of the first rectangle. - ``h1`` ...
def percent(value, total): """ Convert absolute and total values to percent """ if total: return float(value) * 100.0 / float(total) else: return 100.0
def pythoniscool(text="is cool"): """ Receive string and print it""" text = text.replace('_', ' ') return 'Python %s' % text
def get_package_versions(lines): """Return a dictionary of package versions.""" versions = {} for line in lines: line = line.strip() if len(line) == 0 or line.startswith('#') or line.startswith('-r '): continue if line.startswith('https://'): continue ...
def vizz_params_rgb(collection): """ Visualization parameters """ dic = { 'Sentinel2_TOA': {'min':0,'max':3000, 'bands':['B4','B3','B2']}, 'Landsat7_SR': {'min':0,'max':3000, 'gamma':1.4, 'bands':['B3','B2','B1']}, 'Landsat8_SR': {'min':0,'max':3000, 'gamma':1.4, 'bands':['B4','B...
def init_headers(token): """ Returns a dictionary of headers with authorization token. Args: token: The string representation of an authorization token. Returns: The headers for a request with the api. """ headers = { 'Content-Type': 'application/json', 'Authorizatio...
def left(left, right): """Returns keys from right to left for all keys in left.""" return set(left.keys())
def get_releases(data, **kwargs): """ Gets all releases from pypi meta data. :param data: dict, meta data :return: list, str releases """ if "version" in data: return [data["version"], ] return []
def _plot_timelapse_lamp(ax, point_list, plot_points=True, plot_lines=False, path_colors=None, **kwargs): """ A helper function to plot the time lapse lamp points. Parameters ---------- ax: matplotlib.Axes The axes to plot the points. point_list: list of numpy.a...
def get_ext_coeffs(band): """ Returns the extinction coefficient for a given band. Args: band: band name: "G", "R", "Z", "W1", or "W2" (string) Returns: ext: extinction coefficient (float) Note: https://www.legacysurvey.org/dr9/catalogs/#galactic-extinction-coefficients ...
def find_largest_digit(n): """ :param n: the input number :return: the largest digit in the number """ if n < 0: # negative number m = n * -1 return find_largest_digit(m) # m is a positive number now else: # positive number if n < 10: # Base case! n = int(n) return n elif n % 100 > 0 and n % 10 ...
def transition(color1, color2, position): """Generates a transitive color between first and second ones, based on the transition argument, where the value 0.0 is equivalent to the first color, and 1.0 is the second color.""" r1, g1, b1 = color1 >> 16, color1 >> 8 & 0xff, color1 & 0xff r2, g2, b2 = color2 >>...
def precision(tp, fp, fn): """ :param tp: (int) number of true positives :param fp: (int) number of false positives :param fn: (int) number of false negatives :returns: precision metric for one image at one threshold """ return float(tp) / (tp + fp + fn + 1.0e-9)
def downsize_contextD(D, general_pattern, length): """Change a dictionary of kmer counts to a dictinary with kmer counts for a smaller value of k. Args: D (dict): kmer count dictonary general_patttern (str): the general pattern length (int): The new value of k Returns: ...
def slice_config(config, key): """ Slice config for printing as defined in key. :param ConfigManager config: configuration dictionary :param str key: dotted key, by which config should be sliced for printing :returns: sliced config :rtype: dict """ if key: keys = key.split('.')...
def RotCurve(vel, radius, C=0.3, p=1.35): """Create an analytic disk galaxy rotation curve. Arguments: vel -- The approximate maximum circular velocity. radius -- The radius (or radii) at which to calculate the rotation curve. Keywords: C -- Controls the r...
def _is_permission_in_limit(max_permission, given_permission): """ Return true only if given_permission is not more lenient that max_permission. In other words, if r or w or x is present in given_permission but absent in max_permission, it should return False Takes input two integer values from 0 to 7. ...
def get_hemisphere_of_timezone(tz): """ Checked. Returns the hemisphere of the most common timezones or raises an exception if we haven't figured out the hemisphere. some of the Southern TZs are right on the equator broadly the division is: South America + Australia = southern list Europe, USA, Can...
def get_skincluster_info(skin_node): """Get joint influence and skincluster method. Result key : - joint_list, - skin_method, - use_max_inf, - max_inf_count :arg skin_node: Skincluster PyNode that need to get info extracted. :type skin_node: pm.nt.SkinCluster :return: Skinc...
def add_super_group_id(individual_group_id, super_group_ids, treatment): """ Add the super group id based on the *super_group_ids* dict and the treatment. """ # If there was no direct interaction with a human participant # the super group id is simply the group id. # Note that this...
def get_overlap_region(s1,e1,s2,e2): """0-based system is used (like in Biopython): | INPUT | RETURNS | |-----------------------------|-----------------------------| | | | | s1=3 e1=14 ...
def cast_bytes_to_memory_string(num_bytes: float) -> str: """ Cast a number of bytes to a readable string >>> from autofaiss.utils.cast import cast_bytes_to_memory_string >>> cast_bytes_to_memory_string(16.*1024*1024*1024) == "16.0GB" True """ suffix = "B" for unit in ["", "K", "M", "G"...
def filter_pdf_files(filepaths): """ Returns a filtered list with strings that end with '.pdf' Keyword arguments: filepaths -- List of filepath strings """ return [x for x in filepaths if x.endswith('.pdf')]
def pretty_label(inStr): """ Makes a pretty version of our column names "zone_1" -> "Zone 1" "zone_2"-> "Zone 2 ... "zone_strength" -> "Strength" """ import re pattern = re.compile("zone_[12345]{1}|zone_1,2") if pattern.match(inStr): out = inStr el...
def set_bookmark_children(json_root_object, bookmarks): """ Sets bookmarks as value for 'children' key entry of a root bookmark :param json_root_object: First (root) bookmark entry of a dict :param bookmarks: The children list [{}, {},...] of dictionaries for root's 'children' key :return...
def get_changed_pipeline_structure(existing_pipeline, data, is_input=True): """ Get pipeline input/output type and field if pipeline input/output changed :param ubiops.PipelineVersion existing_pipeline: the current pipeline version object :param dict data: the pipeline input or output data containing: ...
def compute_padding(M, N, J): """ Precomputes the future padded size. Parameters ---------- M, N : int input size Returns ------- M, N : int padded size """ M_padded = ((M + 2 ** J) // 2 ** J + 1) * 2 ** J N_padde...
def which(program): """ Search for the presence of an executable Found in: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python """ import os def is_exe(filep): return os.path.isfile(filep) and os.access(filep, os.X_OK) fpath, fname = os.path.split(program)...
def answers(name, app_id, country, state, locality, organization, unit, email) : """Answer string generator Generate answer for certificate creation with openssl Country argument need to be 2 symbol size """ if len(country) != 2 : raise ValueError("Country argument need to be 2 symbol size")...
def quantile_plot_interval(q): """Interpret quantile q input to quantile plot range tuple.""" if isinstance(q, str): sigmas = {'1sigma': 0.682689492137086, '2sigma': 0.954499736103642, '3sigma': 0.997300203936740, '4sigma': 0.999936657516334, ...
def sift(items, cls): """ Filter out items which are not instances of cls. """ return [item for item in items if isinstance(item, cls)]
def comp(array1, array2): """ Determines if the squares of array1 is the same as array2. :param array1: an array of integers. :param array2: an array of integers. :return: True if the squares of array1 are the same as array2 otherwise, False. """ if array1 is None or array2 is None: return F...
def parseOutputPattern(outpat): """Parses an output pattern""" r, g, b = outpat.strip().lower().split(',') return (r, g, b)
def height_to_metric(height): """Converts height in cm to m/cm.""" meters = int(height) // 100 centimeters = height % 100 return meters, centimeters
def sanitize_to_wdq_result(data): """Format data to match WDQ output. @param data: data to sanitize @type data: list of str @return: sanitized data @rtype: list of int """ for i, d in enumerate(data): # strip out http://www.wikidata.org/entity/ data[i] = int(d.lstrip('Q')) ...
def remove_xml_namespace(tag_name): """ Remove a namespace from a tag, e.g., "{www.plotandscatter.com}TagName" will be returned as "TagName" """ if '}' in tag_name: tag_name = tag_name.split('}', 1)[1] return tag_name
def justify_to_point( point: float, itemsize: float, just: float = 0.0) -> float: """ Args: point: align to this coordinate itemsize: size of the item we are aligning just: How should we align? - 0 = left/top ...
def one_hot_encode(x): """ To one hot encode the three classes of rainfall """ if(x==0): return [1 , 0 , 0] if(x==1): return [0 , 1 , 0] if(x==2): return [0 , 0 , 1]
def aliasByMetric(requestContext, seriesList): """ Takes a seriesList and applies an alias derived from the base metric name. .. code-block:: none &target=aliasByMetric(carbon.agents.graphite.creates) """ for series in seriesList: series.name = series.name.split('.')[-1].split(',')[0] return seri...