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': 1e6, 'G': 1e9 } # While LibGen lists sizes in '[KM]b', it's actually in bytes (B) return int(count * si_prefix[unit[0]])
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_PERIODIC_TX_TABLE with the suffix corresponding to a specific date - this value is passed in the table parameter. Additional processing can be done by joining with the metadata table as needed. Args: table: A string representing the full path of the BQ table where the periodic transactions are located. This table is the BQ_LTV_ALL_PERIODIC_TX_TABLE with the suffix corresponding to a specific date. It usually has multiple lines per customer. metadata_table: The fully-qualified name of the metadata table. model_date: A string in YYYYMMDD format representing the model date. This can be used to look up relevant rows in the metadata table if needed. Returns: A string with the query. """ del metadata_table # Unused by default del model_date # Unused by default return f"""SELECT * FROM `{table}`"""
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 # shift pointer to left while True: while arr[low] < pivtol: low += 1 while arr[high] > pivtol: high -= 1 if low >= high : break else: arr[low], arr[high] = arr[high], arr[low] arr[low], arr[pivtol_pos] = arr[pivtol_pos], arr[low] return low if high - low <= 0: return None pi = helper(arr_raw, low, high) quick_sort(arr_raw, low, pi - 1) quick_sort(arr_raw, pi + 1, high)
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 of lists of an integer and floating point number pair, e.g. "60000:1e-3,20000:1e-4" returns [[60000, 1e-3], [20000, 1e-4]] """ parts = phases_str.split(',') phases = [] for phase_str in parts: splits = phase_str.split(':') iterations, learning_rate = int(splits[0]), float(splits[1]) phases.append([iterations, learning_rate]) return phases
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: dbfs_list.append(audio.dBFS) max_dbfs_list.append(audio.max_dBFS) return dbfs_list, max_dbfs_list
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 == errors['key_str']]) val_errors = len([1 for fst, snd in nodes if snd == errors['val_str']]) output = 'Key Errors:\t' + str(key_errors) output += '\nValue Errors:\t' + str(val_errors) return key_errors, val_errors, output
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 normalized IP. """ theip = ip if theip.startswith('::'): theip = '0' + theip if theip.endswith('::'): theip += '0' segments = theip.split(':') if len(segments) == 1: raise ValueError('no colons in ipv6 address: ' + repr(ip)) fill = 8 - len(segments) if fill < 0: raise ValueError('ipv6 address has too many segments: ' + repr(ip)) result = [] for segment in segments: if segment == '': if fill == 0: raise ValueError('unexpected double colon: ' + repr(ip)) for n in range(fill + 1): result.append('0000') fill = 0 else: try: int(segment, 16) except ValueError: raise ValueError('invalid hex value in ' + repr(ip)) result.append(segment.rjust(4, '0')) return ':'.join(result).lower()
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 = [str, float, int, bool] for t in types: if isinstance(obj, t): return True return False
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. * wildcard_level: int ~ The wildcard level. """ if wildcard_level == 0: ec_number_one_full_numbers = ec_number_one.split(".") ec_number_two_full_numbers = ec_number_two.split(".") else: ec_number_one_full_numbers = ec_number_one.split(".")[:-wildcard_level] ec_number_two_full_numbers = ec_number_two.split(".")[:-wildcard_level] if ec_number_one_full_numbers == ec_number_two_full_numbers: return True else: return False
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: return 0, "E111 indentation is not a multiple of four" indent_expect = previous_logical.endswith(':') if indent_expect and indent_level <= previous_indent_level: return 0, "E112 expected an indented block" if indent_level > previous_indent_level and not indent_expect: return 0, "E113 unexpected indentation"
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 ------- out : scalar (int, float, ...) depending on the input values. Unique second value. """ h, m, s = hms return 3000 * h + 60 * m + s
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(tab) return tabuleiro
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` This expands `placeholder` to it's full reference name or raise a value error if it is unable to find an appropriate expansion. """ if placeholder in full_names: return placeholder candidates = [ full_name for full_name in full_names if full_name.startswith(placeholder) ] if len(candidates) == 1: return candidates[0] elif len(candidates) > 1: raise ValueError( "Multiple candidates found trying to expand '{0}'. Found '{1}'. " "Searched '{2}'".format( placeholder, ", ".join(candidates), ", ".join(full_names), ) ) else: raise ValueError( "Unable to expand '{0}'. " "Searched {1}".format( placeholder, ", ".join(full_names), ) )
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'] >>> split_word_at_pipe('Bilderbuch') ['Bilderbuch', 'Bilderbuch'] """ if '|' in word: return word.split('|') else: return [word, word]
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( "Expected 0 or 1 for {}, but got `{}`".format(name, value)) return int(value) == 1
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 photo in entry["photos"]: photo_list.append( "{{" + "photos/{}.{}".format(photo["md5"], photo["type"]) + "}}" ) return entry_text + "\n\n" + "\n".join(photo_list)
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 value. """ return (avg * N + new_val) / (N + 1)
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 False otherwise Raises: TypeError if one of arguments is not a builtins.str or not any subclass of str """ if not isinstance(str_1, str) or not isinstance(str_2, str): raise TypeError if len(str_1) != len(str_2): return False str_1_char_freq = { char: str_1.count(char) for char in set(str_1) } str_2_char_freq = { char: str_2.count(char) for char in set(str_2) } is_permutation_result = (str_1_char_freq == str_2_char_freq) return is_permutation_result
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 provide unique consumer ids. """ return "%(agent_type)s@%(agent_host)s" % {'agent_type': agent_type, 'agent_host': agent_host}
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 }, "assets": { "total": 6, "total unavailable": 0 }, "processing": { "start": "t0", "end": "t3", "duration": 5 } } """ _summary = {k: v for k, v in summary.items() if k in ("web html", "web pdf", "renditions", "assets") } total = sum([item.get("total", 0) for item in _summary.values()]) total_u = sum([item.get("total unavailable", 0) for item in _summary.values()]) total_i = _summary.get("web html", {}).get("total incomplete", 0) if total == 0 or total == total_u: return "missing" if total_u == total_i == 0 and total > 0: return "complete" return "partial"
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) * 60 + int(seconds) minutes, seconds = split_time return int(minutes) * 60 + int(seconds)
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 = 0, 0, 0 else: recall = tp / gt_len precision = tp / pred_len f1 = 2 * recall * precision / (recall + precision) accuracy = tp / (gt_len + pred_len - tp) accuracy_balanced = ((tp / (tp + fn)) + (tn / (tn + fp))) / 2 return recall, precision, f1, accuracy, accuracy_balanced
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.insert(-2, '_' + attach) res = ''.join(string_parts) return res
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. """ first_index = len(first) - 1 second_index = len(second) - 1 skip_in_first = 0 skip_in_second = 0 while first_index >= 0 or second_index >= 0: # In the next two blocks we correct words, if there are "#" or what to skip. if first[first_index] == "#": skip_in_first += 1 first_index -= 1 continue elif skip_in_first > 0: first_index -= 1 skip_in_first -= 1 continue if second[second_index] == "#": skip_in_second += 1 second_index -= 1 continue elif skip_in_second > 0: second_index -= 1 skip_in_second -= 1 continue # Here we check if there are letters in one string and another one is empty. if ( first_index >= 0 and second_index < 0 or first_index < 0 and second_index >= 0 ): return False if first[first_index] != second[second_index]: return False first_index -= 1 second_index -= 1 return True
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 in range(len(text) - 3): if text.count("{}{}".format(text[i], text[i + 1])) >= 2: return True return False
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 :param l: :param debug: :return: """ for i in range(len(l)): for j in range(0, len(l) - i - 1): if l[j] > l[j + 1]: l[j], l[j + 1] = l[j + 1], l[j] if debug: print('iteration {}'.format(i), l) return l
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(chrLen)/ genLen) * axLen: return fs fs -= .1 return fs
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 parameter. Raises ------ TypeError If `keyword` is neither `None` nor `str` instance. """ if keyword is None: pass elif type(keyword) is str: pass elif isinstance(keyword, str): keyword = str(keyword) else: raise TypeError(f'`keyword` can be given as `None` or `str` instance, got {keyword.__class__.__name__}.') return keyword
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 { to_camel_case(k): v for k, v in data.items() if v is not None and k not in ['self', 'session', 'params', 'lightweight'] }
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) # insert 0.0 at begining of list rec.append(1.0) # insert 1.0 at end of list mrec = rec[:] prec.insert(0, 0.0) # insert 0.0 at begining of list prec.append(0.0) # insert 0.0 at end of list mpre = prec[:] """ This part makes the precision monotonically decreasing (goes from the end to the beginning) matlab: for i=numel(mpre)-1:-1:1 mpre(i)=max(mpre(i),mpre(i+1)); """ # matlab indexes start in 1 but python in 0, so I have to do: # range(start=(len(mpre) - 2), end=0, step=-1) # also the python function range excludes the end, resulting in: # range(start=(len(mpre) - 2), end=-1, step=-1) for i in range(len(mpre)-2, -1, -1): mpre[i] = max(mpre[i], mpre[i+1]) """ This part creates a list of indexes where the recall changes matlab: i=find(mrec(2:end)~=mrec(1:end-1))+1; """ i_list = [] for i in range(1, len(mrec)): if mrec[i] != mrec[i-1]: i_list.append(i) # if it was matlab would be i + 1 """ The Average Precision (AP) is the area under the curve (numerical integration) matlab: ap=sum((mrec(i)-mrec(i-1)).*mpre(i)); """ ap = 0.0 for i in i_list: ap += ((mrec[i]-mrec[i-1])*mpre[i]) return ap
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.append(line) return '\n'.join(lines)
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) return fmt
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_ANOTHER_CAPTION', 'save_and_add_another_caption'), ('BO_DELETE_CAPTION', 'delete_caption'), ) captions = {} for old_key, new_key in caption_keys: captions[new_key] = context.get(old_key, '') return captions
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`` -- The height of the first rectangle. - ``x2`` -- The horizontal position of the second rectangle. - ``y2`` -- The vertical position of the second rectangle. - ``w2`` -- The width of the second rectangle. - ``h2`` -- The height of the second rectangle. """ return (x1 < x2 + w2 and x1 + w1 > x2 and y1 < y2 + h2 and y1 + h1 > y2)
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 name, version_plus = line.split('==', 1) versions[name.lower()] = version_plus.split(' ', 1)[0] return versions
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','B3','B2']}, 'CroplandDataLayers': {'min':0,'max':3, 'bands':['landcover']}, 'NationalLandCoverDatabase': {'min': 0, 'max': 1, 'bands':['impervious']} } return dic[collection]
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', 'Authorization': 'Bearer ' + token } return headers
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.array List of points organized by time step. plot_points: boolean Switch to indicate if the points should be plotted. Default value is True. plot_lines: boolean Switch to indicate if the lines connecting the points should be plotted. Default value is False. path_colors: list A list of RGBA colors to apply to the plotted elements (lines and points). An easy way to generate this is to use matplotlib's cm module. kwargs: other named arguments Other arguments to pass to ax.scatter and ax.plot Returns ------- artists: tuple A tuple of 2 lists. The first list contains the artist added by the call to ax.scatter (if plot_points is True) and the second list contains the artists added by ax.plot (if plot_lines is True). """ if not isinstance(point_list, list): point_list = [point_list] scatter_artists = [] plot_artists = [] for i, p in enumerate(point_list): x = p[:, 0] y = p[:, 1] pc = None pl = None if path_colors is not None: kwargs['c'] = path_colors[i] if plot_points: pc = ax.scatter(x, y, **kwargs) if plot_lines: pl = ax.plot(x, y, **kwargs) scatter_artists.append(pc) plot_artists.append(pl) return (scatter_artists, plot_artists)
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 """ exts = {"G": 3.214, "R": 2.165, "Z": 1.211, "W1": 0.184, "W2": 0.113} return exts[band]
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 > 0: if (n % 10) * 10 >= n % 100: # units digit > tens digit m = (n - n % 100) / 10 + n % 10 return find_largest_digit(m) else: # units digit < tens digit m = (n - (n % 10)) / 10 return find_largest_digit(m)
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 >> 16, color2 >> 8 & 0xff, color2 & 0xff r = int(r1 + ((r2 - r1) * position) // 1) << 16 g = int(g1 + ((g2 - g1) * position) // 1) << 8 b = int(b1 + ((b2 - b1) * position) // 1) return r | g | b
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: tuple with downsized dictionary and downsized general pattern """ res = {} start = None end = None for context in D: if start is None: assert not length is None assert len(context) > length, f'k-mer:{context} cannot be reduced to length {length}' radius1 = (len(context)//2) radius2 = length//2 start = radius1-radius2 end = (radius1-radius2)+length counts = D[context] context = context[start:end] if context not in res: res[context] = [0]*len(counts) for i in range(len(counts)): res[context][i] += counts[i] return res, general_pattern[start:end]
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('.') for k in keys: config = config[k] return config
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 radius at which the curve turns over, in the same units as 'radius'. p -- Controls the fall-off of the curve after the turn-over; values expected to be between 1 and 1.5 for disks. Returns the value of the rotation curve at the given radius. See Bertola et al. 1991, ApJ, 373, 369 for more information. """ C_ = C # kpc p_ = p return vel * radius / ((radius**2 + C_**2)**(p_/2.))
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. """ max_permission = int(max_permission) given_permission = int(given_permission) allowed_r = False allowed_w = False allowed_x = False given_r = False given_w = False given_x = False if max_permission >= 4: allowed_r = True max_permission = max_permission - 4 if max_permission >= 2: allowed_w = True max_permission = max_permission - 2 if max_permission >= 1: allowed_x = True if given_permission >= 4: given_r = True given_permission = given_permission - 4 if given_permission >= 2: given_w = True given_permission = given_permission - 2 if given_permission >= 1: given_x = True if given_r and (not allowed_r): return False if given_w and (not allowed_w): return False if given_x and (not allowed_x): return False return True
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, Canada, Mexico = Northern List exception is Caracas, which is in South America but is in the Northern hemisphere. Some of the Brazilian TZs are quite close to the equator, as is America/Guayaquil. So in general Northern tzs are farther North than Southern TZs are South. """ northern_timezones = ['Europe/Berlin', 'Europe/Lisbon', 'Europe/Paris', 'Europe/Rome', 'Europe/London', 'Europe/Copenhagen', 'America/Denver', 'Europe/Moscow', 'America/Chicago', 'Europe/Madrid', 'America/Los_Angeles', 'America/New_York', 'America/Vancouver', 'America/Toronto', 'America/Mexico_City', 'America/Caracas'] southern_timezones = ['America/Buenos_Aires', 'Australia/Melbourne', 'Australia/Sydney', 'America/Lima', 'America/Recife', 'America/Santiago', 'America/Fortaleza', 'America/Sao_Paulo', 'America/Guayaquil'] if tz in northern_timezones: return 'Northern' if tz in southern_timezones: return 'Southern' raise Exception("Not a valid timezone")
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: Skincluster joint influence, Skin method index, Use max influence, Max influence count. :rtype: dict """ output = { 'joint_list': [], 'skin_method': 0, 'use_max_inf': False, 'max_inf_count': 4, } if skin_node: output['joint_list'] = skin_node.getInfluence() output['skin_method'] = skin_node.getSkinMethod() output['use_max_inf'] = skin_node.getObeyMaxInfluences() output['max_inf_count'] = skin_node.getMaximumInfluences() return output
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 group id does not change by player for different super # games if there is only 'idividual' choice. if treatment in ['1H1A', '1H2A']: return individual_group_id else: for sg_id, group_ids in super_group_ids.items(): if individual_group_id in group_ids: return sg_id
def get_overlap_region(s1,e1,s2,e2): """0-based system is used (like in Biopython): | INPUT | RETURNS | |-----------------------------|-----------------------------| | | | | s1=3 e1=14 | | | |----------| | [9,14] | | |---------| | | | s2=9 e2=19 | | | | | """ if s1 > e1 or s2 > e2: raise Exception("Something is wrong with the intervals (%i,%i) and (%i,%i)" % (s1,e1,s2,e2)) if s1 <= s2 <= e1 and s1 <= e2 <= e1: # |----------------| # |--------| return s2, e2 elif s2 <= s1 <= e2 and s2 <= e1 <= e2: # |--------| # |----------------| return s1, e1 elif s1 <= s2 <= e1 and s2 <= e1 <= e2: # |------------| # |-------------| return s2, e1 elif s2 <= s1 <= e2 and s1 <= e2 <= e1: # |-------------| # |------------| return s1, e2 else: return None, None
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", "T", "P", "E", "Z"]: if abs(num_bytes) < 1024.0: return "%3.1f%s%s" % (num_bytes, unit, suffix) num_bytes /= 1024.0 return "%.1f%s%s" % (num_bytes, "Y", suffix)
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 else: out = inStr[5:] return out.replace("_", " ").capitalize()
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: The root bookmark entry with filled 'children' key """ json_root_object["children"] = bookmarks return json_root_object
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: str input_type/output_type: e.g. plain list(PipelineInputFieldCreate) input_fields/output_fields: e.g. [PipelineInputFieldCreate(name=input1, data_type=int)] :param bool is_input: whether to use input_ or output_ prefix """ changed_data = dict() type_key = 'input_type' if is_input else 'output_type' type_fields = 'input_fields' if is_input else 'output_fields' # Input/output type changed if type_key in data and getattr(existing_pipeline, type_key) != data[type_key]: changed_data[type_key] = data[type_key] changed_data[type_fields] = data[type_fields] # Input/output fields changed elif type_fields in data and isinstance(data[type_fields], list): # Shuffle fields to {'field_name1': 'data_type1', 'field_name2': 'data_type2'} existing_fields = {field.name: field.data_type for field in getattr(existing_pipeline, type_fields)} fields = {field.name: field.data_type for field in data[type_fields]} # Check if dicts are equal if existing_fields != fields: changed_data[type_fields] = data[type_fields] return changed_data
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_padded = ((N + 2 ** J) // 2 ** J + 1) * 2 ** J return M_padded, N_padded
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) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
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") answer ="'/C={0}/ST={1}/L={2}/O={3}".format(country, state, locality, organization) answer +="/OU={0}/CN={1}/emailAddress={2}'".format(unit, name, email) if len(app_id) > 0: answer += "/serialNumber={0}".format(app_id) return answer
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, '5sigma': 0.999999426696856} q = (1 - sigmas[q]) / 2 if isinstance(q, float) or isinstance(q, int): if q > 0.5: q = 1 - q q = (q, 1-q) return q
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 False return sorted(array2) == sorted(x * x for x in array1)
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')) return data
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 - 0.5 = centre - 1 = right/bottom Returns: float: starting coordinate of the item (top or left) Note: - x axis is left-to-right (and justification 0-1 is left-to-right) - y axis is top-to-bottom (and justification 0-1 is top-to-bottom) - ... so we can treat them equivalently. """ return point - itemsize * just
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 seriesList