content
stringlengths
42
6.51k
def _build_gcp_extra(metadata): """ Helper function to build the gcp extra dict """ gcp_extra= {} gcp_extra['cloud_project_id']=metadata['project']['projectId'] gcp_extra['cloud_name'] = metadata['instance']['name'] gcp_extra['cloud_hostname'] = metadata['instance']['hostname'] gcp_extra['cloud_zone'] = metadata['instance']['zone'] gcp_extra['cloud_image'] = metadata['instance']['image'] gcp_extra['cloud_machine_type'] = metadata['instance']['machineType'] gcp_extra['cloud_tags'] = metadata['instance']['tags'] interface_list = metadata['instance']['networkInterfaces'] for counter, value in enumerate(interface_list): grain_name_network = "cloud_interface_{0}_network".format(counter) gcp_extra[grain_name_network] = value['network'] grain_name_ip = "cloud_interface_{0}_ip".format(counter) gcp_extra[grain_name_ip] = value['ip'] grain_name_subnetmask = "cloud_interface_{0}_subnetmask".format(counter) gcp_extra[grain_name_subnetmask] = value['subnetmask'] grain_name_mac = "cloud_interface_{0}_mac_address".format(counter) gcp_extra[grain_name_mac] = value['mac'] grain_name_forwardedips = "cloud_interface_{0}_forwarded_ips".format(counter) gcp_extra[grain_name_forwardedips] = ','.join(value['forwardedIps']) grain_name_targetips = "cloud_interface_{0}_target_ips".format(counter) gcp_extra[grain_name_targetips] = ','.join(value['targetInstanceIps']) grain_name_accessconfig_external_ips = "cloud_interface_{0}_" \ "accessconfigs_external_ips".format(counter) external_ips_list = [item['externalIp'] for item in value['accessConfigs'] if 'externalIp' in item] gcp_extra[grain_name_accessconfig_external_ips] = ','.join(external_ips_list) return gcp_extra
def map_wn_pos(pos): """ Map a Penn Treebank POS tag to a WordNet style one """ if pos in ['NN', 'NNS']: # not NNP! return 'n' elif pos.startswith('JJ'): return 'a' elif pos.startswith('RB'): return 'r' elif pos.startswith('VB'): return 'v' else: return None
def is_valid_name(name: str) -> bool: """Returns Ture if a given string represents a valid name (e.g., for a dataset). Valid names contain only letters, digits, hyphen, underline, or blanl. A valid name has to contain at least one digit or letter. """ allnums = 0 for c in name: if c.isalnum(): allnums += 1 elif c not in ['_', '-', ' ']: return False return (allnums > 0)
def is_album_id(item_id): """Validate if ID is in the format of a Google Music album ID.""" return len(item_id) == 27 and item_id.startswith('B')
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] }
def __parse_filter__(query): """ First checks if the provided query is a string and splits by comma to create a list, otherwise the list is used. NOTE: This must be done because falcon parse the query parameters differently depending on the encoding. :param query: The query parameter parsed by falcon :return: List with filter """ query = query.split(',') if isinstance(query, str) else query if isinstance(query, str): query = [query] return query
def __transition_map_cost(ImplementedStateN, IntervalN, SchemeN): """ImplementedStateN -- Number of states which are implemeted in the scheme. IntervalN -- Number of intervals in the transition map. SchemeN -- Number of DIFFERENT schemes in the transition map. Find a number which is proportional to the 'cost' of the transition map. Example: interval 1 --> [1, 3, 5, 1] interval 2 --> drop_out interval 3 --> [1, 3, 5, 1] interval 4 --> 5 interval 5 --> [1, 3, 5, 1] interval 6 --> [2, 1, 1, 2] This transition map has 5 borders and 5 targets. Let the cost of a border as well as the cost for a single target be '1'. The additional cost for a required scheme is chosen to be 'number of scheme elements' which is the number of implemented states. Schemes that are the same are counted as 1. """ #print "#ImplementedStateN", ImplementedStateN #print "#IntervalN", IntervalN #print "#SchemeN", SchemeN cost_border = IntervalN - 1 target_n = IntervalN cost_targets = target_n + SchemeN * ImplementedStateN return cost_border + cost_targets
def average_precision(ret, ans): """ ret: list of tuples [ (docname, score) ] ans: python dictionary with answer as keys """ tp = [float(docID in ans) for docID, val in ret] precisions = [] ans_count = 0 for idx, (docID, val) in enumerate(ret): ans_count += tp[idx] precisions.append(ans_count / (idx + 1) * tp[idx]) return (sum(precisions) / len(ans) if len(ans) else 0.)
def convert_float_time(time): """Converts a time from a string to a float. time is the time that needs to be converted.""" # If an asterisk is in the time, the time is in the wrong time # period. If the asterisk time is in teleop, the time period is # supposed to be in sandstorm, so it sets the time to the lowest # time in sandstorm, and vice versa for when the time is in # sandstorm. if '*' in time: if float(time[:-1]) >= 135.1: return 135.0 else: return 135.1 else: return float(time)
def factorial(x): """returns factorial of x""" if type(x) != int: print("ERROR <- x in factorial(x) is not type int") return result = 1 for i in range(1,x+1): result *= i return result
def sign(a): """Gets the sign of a scalar input.""" if a >= 0: return 1 else: return 0
def string_to_list(t_str, t_char=" "): """ Returns a list of elements that are contains inside the string param. :param str t_str: string with elements and delimiters :param str t_char: delimiter of the elements :return list t_list: list of elements that were inside t_str """ t_list = t_str.strip(t_char).split(t_char) return t_list
def string_to_num(word): """ Converts a string to a list of numbers corresponding to the alphabetical order of the characters in the string >>> assert string_to_num('abc') == [0, 1, 2] >>> assert string_to_num('generator') == [2, 1, 3, 1, 5, 0, 6, 4, 5] """ all_letters = sorted(list(set(word))) return [all_letters.index(letter) for letter in word]
def strand(s1, s2): """ Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2 must be of same length. """ return "".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))
def get_class_hierarchy_names(obj): """Given an object, return the names of the class hierarchy.""" names = [] for cls in obj.__class__.__mro__: names.append(cls.__name__) return names
def _transform_playlist(playlist): """Transform result into a format that more closely matches our unified API. """ transformed_playlist = dict([ ('source_type', 'youtube'), ('source_id', playlist['id']), ('name', playlist['snippet']['title']), ('tracks', playlist['contentDetails']['itemCount']), ]) return transformed_playlist
def signed_to_unsigned(value: int, size: int) -> int: """Converts the given value to its unsigned representation.""" if value < 0: bit_size = 8 * size max_value = (1 << bit_size) - 1 value = max_value + value return value
def get_security_group_id(event): """ Pulls the security group ID from the event object passed to the lambda from EventBridge. Args: event: Event object passed to the lambda from EventBridge Returns: string: Security group ID """ return event.get("detail").get("requestParameters").get("groupId")
def flatten_json(json_dict: dict, block_i: int) -> dict: """Flatten python dict Args: json_dict (dict): post blocks dict structure block_i (int): block numeric id Returns: dict: flat dict """ out = {} def flatten(x: dict, name: str = '') -> None: if isinstance(x, dict): for a in x: flatten(x[a], name + a + '~') elif isinstance(x, list): for i, a in enumerate(x): flatten(a, name + str(i) + '~') else: out[name[:-1]] = x if isinstance(x, str) else str(x).lower() flatten(json_dict) return { f"entry[entry][blocks][{block_i}][{key.replace('~', '][')}]": value for key, value in out.items() }
def get_return_var(return_type: str) -> str: """ int foo() => return r; void foo() => '' """ s = return_type.strip() if 'void' == s: return '' return 'return r;'
def playfair_wrap(n, lowest, highest): """Ensures _n_ is between _lowest_ and _highest_ (inclusive at both ends). """ skip = highest - lowest + 1 while n > highest or n < lowest: if n > highest: n -= skip if n < lowest: n += skip return n
def assert_equal(a, b): """ Wrapper to enable assertions in lambdas """ assert a == b return True
def path_to_url(path): """Convert a system path to a URL.""" return '/'.join(path.split('\\'))
def NE(x=None, y=None): """ Compares two values and returns: true when the values are not equivalent. false when the values are equivalent. See https://docs.mongodb.com/manual/reference/operator/aggregation/ne/ for more details :param x: first value or expression :param y: second value or expression :return: Aggregation operator """ if x is None and y is None: return {'$ne': []} return {'$ne': [x, y]}
def errorInFile(f, line=17, name=''): """ Return a filename formatted so emacs will recognize it as an error point @param line: Line number in file. Defaults to 17 because that's about how long the copyright headers are. """ return '%s:%d:%s' % (f, line, name) # return 'File "%s", line %d, in %s' % (f, line, name)
def randomize_times(times, ids = []): """ Randomize the times of the point events of all the ids that are given. This just reshuffles the event times among all the individuals taking into account. Parameters ---------- times : dictionary of lists The dictionary contains for each element their times of events in a list ids : list of ids If not given, the reshuffling is global, if some ids are given, only those will be used for the reshuffling. Returns ------- times_random : dictionary of lists For each element a list of reshuffled event times """ from random import shuffle times_random = dict() if len(ids) == 0: ids = list(times.keys()) Nevents = dict() aux = 0 tlist = [] N = len(ids) for i in range(N): idn = ids[i] aux += len(times[idn]) Nevents[idn] = aux tlist.extend(times[idn]) shuffle(tlist) aux=0 for i in range(N): idn = ids[i] times_random[idn] = tlist[aux:Nevents[idn]] aux = Nevents[idn] times_random[idn].sort() return times_random
def kth_element(list_a: list, k: int): """Problem 3: Find the K'th Element of a List Parameters ---------- list_a : list The input list k : int The element to fetch Returns ------- element The k'th element of the input list Raises ------ TypeError If the given argument is not of `list` type ValueError If the input list contains less than two elements, or the given k is less than 1 """ if not isinstance(list_a, list): raise TypeError('The argument given is not of `list` type.') if len(list_a) < k: raise ValueError(f'The input list contains less than [{k}] elements.') if k < 1: raise ValueError('The value of k cannot be less than 1.') return list_a[k - 1]
def find_pivot(input_arr, min_idx, max_idx): """ Find the the pivor index of an rotated array Time complexity: O(1og2(n)) Space Complexity: O(1) Args: input_array(array): rotated array Returns: pivot_idx(int) """ mid = (min_idx + max_idx) // 2 # if mid element is higher than the next one, we found an pivot if mid < max_idx and input_arr[mid] > input_arr[mid + 1]: return mid # if mid-1 element is higher than the next one (mid element), we found an pivot if mid > min_idx and input_arr[mid] < input_arr[mid - 1]: return (mid-1) # if the first element is higher than the current (mid) element, # call recrusion for the lower interval if input_arr[min_idx] >= input_arr[mid]: return find_pivot(input_arr, min_idx, mid-1) # else if the first element is lower than the current (mid) element, # call recrusion for the higher interval else: return find_pivot(input_arr, mid + 1, max_idx)
def print_fileinfo(filename, line_number, message, vi=False): """Return a formatted string with filename, line_number and message. Keyword arguments: vi -- output line numbers in a format suitable for passing to editors such as vi (default False) """ if vi: return '%s +%d #%s' % (filename, line_number, message) return '%s:%d: %s' % (filename, line_number, message)
def get_body_payload_initial(dataset, dataset_uid, published): """ Create an initial body payload Keyword arguments: dataset: data set dataset_uid: data set UID published: True=public, False=private Returns: body_payload: initial body payload """ data_set_ref = "EMDataSet#%d" % (dataset_uid) body_payload = {"class": "org.janelia.model.domain.flyem.EMBody", "dataSetIdentifier": dataset, "ownerKey": "group:flyem", "readers": ["group:flyem"], "writers": ["group:flyem"], "dataSetRef": data_set_ref, } if published: body_payload['readers'] = ["group:flyem", "group:workstation_users"] return body_payload
def trailing_zeros(n): """Returns number of trailing zeros in n factorial.""" # factorial of nums less 5 doesn't end with 0 if n < 5: return 0 # example: n = 11 # n % 5 = 1 => n - 1 = 10 => 10 // 5 = 2 reminder = n % 5 result = (n - reminder) // 5 return result
def fix_xiaomi_battery(value: int) -> int: """Convert battery voltage to battery percent.""" if value <= 100: return value if value <= 2700: return 0 if value >= 3200: return 100 return int((value - 2700) / 5)
def get_id_key(entity_name): """Get entity id key. Follows the simple convention that *id_key* is the *entity_name* followed by '_id'. Args: entity_name (str): entity_name Return: id_key (str) .. code-block:: python >>> from utils.db import get_id_key >>> entity_name = 'province' >>> print(get_id_key(province)) 'province_id' """ return '%s_id' % (entity_name)
def is_nonneg_int(num_str): """ Args: num_str (str): The string that is checked to see if it represents a nonneg integer Returns: bool Examples: >>> is_nonneg_int("25.6") False >>> is_nonneg_int("-25.6") False >>> is_nonneg_int("0") True >>> is_nonneg_int("1964") True >>> is_nonneg_int("-1964") False >>> is_nonneg_int("6e5") False >>> is_nonneg_int("1_964") False >>> is_nonneg_int("NaN") False >>> is_nonneg_int("None") False >>> is_nonneg_int("27j+5") False >>> is_nonneg_int("abcdefg") False >>> is_nonneg_int("12345abcdefg") False >>> is_nonneg_int("~26.3") False >>> is_nonneg_int("^26.3") False """ assert isinstance(num_str, str) return num_str.isdigit()
def _is_dynamic(module): """ Return True if the module is special module that cannot be imported by its name. """ # Quick check: module that have __file__ attribute are not dynamic modules. if hasattr(module, '__file__'): return False if hasattr(module, '__spec__'): return module.__spec__ is None else: # Backward compat for Python 2 import imp try: path = None for part in module.__name__.split('.'): if path is not None: path = [path] f, path, description = imp.find_module(part, path) if f is not None: f.close() except ImportError: return True return False
def filter_args(arg_dict, desired_fields=None): """only pass to network architecture relevant fields.""" if not desired_fields: desired_fields = ['net_type', 'num_scales', 'in_channels', 'mid_channels', 'num_levels'] return {k:arg_dict[k] for k in desired_fields if k in arg_dict}
def __dumpbin_parse_exports(input): """Parse thr output from dumpbin as a list of symbols""" ret = [] lines = input.split('\n') for line in lines: arr1 = line.split() if len(arr1) == 4 and arr1[1] != 'number' and arr1[1] != 'hint': ret.append(arr1[3]) return ret
def glue(vec_a, vec_b): """ concatenate two smaller vectors to a larger vector vec_a : first vector vec_b : second vector """ retval = list() retval.extend(vec_a) retval.extend(vec_b) return retval
def calculo_notas(nota): """float-->float OBJ:Calcular la nota redondeando a 0.5 PRE: 10<=nota>=0""" nota_final=round(2*nota)/2 return nota_final
def one_of_k_encoding(x, allowable_set): """ Encodes elements of a provided set as integers. Parameters ---------- x: object Must be present in `allowable_set`. allowable_set: list List of allowable quantities. Example ------- >>> import deepchem as dc >>> dc.feat.graph_features.one_of_k_encoding("a", ["a", "b", "c"]) [True, False, False] Raises ------ `ValueError` if `x` is not in `allowable_set`. """ if x not in allowable_set: raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set)) return list(map(lambda s: x == s, allowable_set))
def parse_field(line, d): """ Extract regular field & value from: Destination directory = "R:\speed-test\big_files\" Directories processed = 1 Total data in bytes = 527,331,269 ... """ if " = " in line: field, value = line.split(" = ") d[field.strip()] = value.strip() return d
def predict_column_type(data): """ Predict the data type of the elements present in a list. It will be defaulted to string. Args: data : array Returns: type: Column data type """ data_types = [type(item) for item in data] data_types = list(set(data_types)) if len(data_types) == 1: return data_types[0].__name__ elif str in data_types: return "str" elif float in data_types: return "float" elif int in data_types: return "int" else: return "str"
def getgain(image): """ Get the gain from the header.""" gain = 1.0 # default # check if there's a header if hasattr(image,'meta'): if image.meta is not None: # Try all versions of gain for f in ['gain','egain','gaina']: hgain = image.meta.get(f) if hgain is not None: gain = hgain break return gain
def get_first_year(data_id): """Returns first year in which ground truth data or forecast data is available Args: data_id: forecast identifier beginning with "nmme" or ground truth identifier accepted by get_ground_truth """ if data_id.startswith("global"): return 2011 if data_id.endswith("precip"): return 1948 if data_id.startswith("nmme"): return 1982 if data_id.endswith("tmp2m") or data_id.endswith("tmin") or data_id.endswith("tmax"): return 1979 if "sst" in data_id or "icec" in data_id: return 1981 if data_id.endswith("mei"): return 1979 if data_id.endswith("mjo"): return 1974 if data_id.endswith("sce"): return 1966 if "hgt" in data_id or "uwnd" in data_id or "vwnd" in data_id: return 1948 if ("slp" in data_id or "pr_wtr" in data_id or "rhum" in data_id or "pres" in data_id or "pevpr" in data_id): return 1948 if data_id.startswith("subx_cfsv2"): return 1999 raise ValueError("Unrecognized data_id "+data_id)
def _stringListEncoderHelper( n, maxLenS ): """ helper method for string encoding for list iterator """ maxLenS[0]= max( maxLenS[0], len( n ) ) return n.encode( "ascii", "ignore" )
def name_standard(name): """ return the Standard VERSION of the input word :param name: the name that should be standard :type name:str :return name: the standard form of word as string >>> name_standard('test') 'Test' >>> name_standard('TesT') 'Test' """ reponse_name = name[0].upper() + name[1:].lower() return reponse_name
def scale(y, a, b): """ Scales the vector y (assumed to be in [0,1]) to [a,b] :param y: :param a: :param b: :return: """ return a * y + (b - a) * y
def hey(phrase): """ Bob is a lackadaisical teenager with limited conversational skills """ phrase = phrase.strip() if phrase == "": return "Fine. Be that way!" if phrase.upper() == phrase and phrase.lower() != phrase: return "Whoa, chill out!" if phrase.endswith("?"): return "Sure." return "Whatever."
def validate_age(age): """ Validate that the age provided is a number """ if isinstance(age, int): return True age_okay = True age_range = age.split('-') for number in age_range: try: int(number) except ValueError: return False return age_okay
def get_all_tags(y_true): """ Return a set of all tags excluding non-annotations (i.e. "_", "O", "-") :param list y_true: a nested list of labels with the structure "[docs [sents [tokens]]]". :return: set of all labels. :rtype: set """ # keep only primary annotation when separated by a pipe tags = {label.split("|")[0].split("-")[-1] for doc in y_true for seg in doc for label in seg} non_tags = [ "_", "-", "O", ] for symbol in non_tags: try: tags.remove(symbol) except KeyError: pass return tags
def convert_validate_date(input_date): """ :param input_date :return: validate date """ if len(input_date) == 1: input_date = '0{}'.format(input_date) return input_date
def is_float(obj): """Check if obj is float.""" return isinstance(obj, float)
def merge(source:dict, destination:dict): """ Utility function to merge two dictionaries .. code-block:: python a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } } b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } } print(merge(b, a)) # { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } } Args: source (dict): first dict to merge destination (dict): second dict to merge Returns: dict: merged dict """ for key, value in source.items(): if isinstance(value, dict): # get node or create one node = destination.setdefault(key, {}) merge(value, node) else: destination[key] = value return destination
def container_for_key(key): """ Determines what type of container is needed for `key` """ try: int(key) return [] except ValueError: return {}
def beaufort(ws_kts): """Return the beaufort number given a wind speed in knots""" if ws_kts is None: return None elif ws_kts < 1: return 0 elif ws_kts < 4: return 1 elif ws_kts < 7: return 2 elif ws_kts < 11: return 3 elif ws_kts < 17: return 4 elif ws_kts < 22: return 5 elif ws_kts < 28: return 6 elif ws_kts < 34: return 7 elif ws_kts < 41: return 8 elif ws_kts < 48: return 9 elif ws_kts < 56: return 10 elif ws_kts < 64: return 11 return 12
def audit_renamed_col_dict(dct: dict) -> dict: """ Description ----------- Handle edge cases where a col could be renamed back to itself. example: no primary_geo, but country is present. Because it is a protected col name, it would be renamed country_non_primary. Later, it would be set as primary_geo country, and the pair added to renamed_col_dict again: {'country_non_primary' : ['country'], "country": ['country_non_primary'] } Parameters ---------- dct: dict renamed_col_dict of key: new column name, value: list of old columns Output ------ dict: The modified parameter dict. """ remove_these = set() for k, v in dct.items(): vstr = "".join(v) if vstr in dct.keys() and [k] in dct.values(): remove_these.add(vstr) remove_these.add(k) for k in remove_these: dct.pop(k, None) return dct
def db_tables(schema_name): """ Manifest of all application tables expected in database when all migrations are run """ if schema_name.lower() == 'transactional': tbl_list = ['participant', 'program', 'participant_program', 'program_provider', 'provider', 'outcome', 'exit_type', 'wage', 'entity_type'] else: tbl_list = [] # sort table list - easier test comparison tbl_list.sort() return tbl_list
def get_mean(l): """ Concatenates two pandas categoricals. Parameters ---------- l : list A list of numbers. Returns ------- float The result. Examples -------- >>> from foocat_tao_huang import foocat_tao_huang >>> a = [1,2,3] >>> foocat.get_mean(a) 2.0 """ return sum(l) / len(l)
def initialize_coverage_dict(taget_revision_dict): """ Initializes coverage dictionary, containing coverage data Currently supported coverage is total document coverage and chapter coverage. total - computes the total amount of paragraphs in a given section ( = chapter, subchapter, document...) and stores it so coverage percentage can be computed later. """ coverage_dict = {} total = 0 for section_id, contents in taget_revision_dict.items(): if not (section_id == "contents" and isinstance( taget_revision_dict[section_id], str)): coverage_dict[section_id], total_rec = initialize_coverage_dict( taget_revision_dict[section_id]) total += total_rec elif section_id in taget_revision_dict and \ taget_revision_dict[section_id] and \ isinstance(taget_revision_dict[section_id], str): coverage_dict[section_id] = False total += 1 coverage_dict["total"] = total coverage_dict["covered"] = 0 return coverage_dict, total
def find_string(s): """ Find start and end of a quoted string """ result = next((i, c) for i, c in enumerate(s) if c in ('"', "'")) if result is not None: start, quote_char = result end = next( i for i, c in enumerate(s[start + 1: ]) if c == quote_char and s[i - 1] != '\\' ) if end is not None: return (start, start + end + 1) return None, None
def numf(s, defval=0.0): """Return interpreted float - unlike num default is 0.0.""" f = str(s).strip() if s else None if not f: return defval try: return float(f) except: print("Could not float(%s)" % (f,)) return defval
def _MakeSignature(app_id=None, url=None, kind=None, db_filename=None, perform_map=None, download=None, has_header=None, result_db_filename=None, dump=None, restore=None): """Returns a string that identifies the important options for the database.""" if download: result_db_line = 'result_db: %s' % result_db_filename else: result_db_line = '' return u""" app_id: %s url: %s kind: %s download: %s map: %s dump: %s restore: %s progress_db: %s has_header: %s %s """ % (app_id, url, kind, download, perform_map, dump, restore, db_filename, has_header, result_db_line)
def _get_coord_zoom_and_shift(ndim, nprepad=0): """Compute target coordinate based on a shift followed by a zoom. This version zooms from the center of the edge pixels. Notes ----- Assumes the following variables have been initialized on the device:: in_coord[ndim]: array containing the source coordinate zoom[ndim]: array containing the zoom for each axis shift[ndim]: array containing the zoom for each axis computes:: c_j = zoom[j] * (in_coord[j] - shift[j]) """ ops = [] pre = f" + (W){nprepad}" if nprepad > 0 else '' for j in range(ndim): ops.append(f''' W c_{j} = zoom[{j}] * ((W)in_coord[{j}] - shift[{j}]){pre};''') return ops
def max_retention(frequencies): """Calculate the amount of seconds in a retention unit.""" sec_dict = { 'minute': 60, 'hourly': 3600, 'daily': 86400, 'weekly': 604800, 'monthly': 2592000, 'quarterly': 7776000, 'yearly': 31536000 } secs = [] for freq, freq_data in frequencies.items(): secs.append(sec_dict[freq] * freq_data['retention']) if not secs: secs = [0] return max(secs)
def convert_chemformula(string): """ Convert a chemical formula string to a matplotlib parsable format (latex). Parameters ---------- string or Adsorbate: str String to process. Returns ------- str Processed string. """ result = getattr(string, 'formula', None) if result is None: result = "" number_processing = False for i in string: if i.isdigit(): if not number_processing: result += '_{' number_processing = True else: if number_processing: result += '}' number_processing = False result += i if number_processing: result += '}' return f'${result}$'
def calculate_range_parameter(part_size, part_index, num_parts, total_size=None): """Calculate the range parameter for multipart downloads/copies :type part_size: int :param part_size: The size of the part :type part_index: int :param part_index: The index for which this parts starts. This index starts at zero :type num_parts: int :param num_parts: The total number of parts in the transfer :returns: The value to use for Range parameter on downloads or the CopySourceRange parameter for copies """ # Used to calculate the Range parameter start_range = part_index * part_size if part_index == num_parts - 1: end_range = '' if total_size is not None: end_range = str(total_size - 1) else: end_range = start_range + part_size - 1 range_param = 'bytes=%s-%s' % (start_range, end_range) return range_param
def headers(token=None): """ Creates a dict of headers with JSON content-type and token, if supplied. :param token: access token for account :return: dictionary of headers """ data = {'Content-Type': 'application/json'} if token: data['Token'] = token return data
def dequeue(queue): """ Return anytype from queue""" return None if not queue else queue.pop(0)
def listToString(s): """ Description: Need to build function because argparse function returns list, not string. Called from main. :param s: argparse output :return: string of url """ # initialize an empty string url_string = "" # traverse in the string for ele in s: url_string += ele # return string return url_string
def replace_id_to_name(main_list, type_list, str_main_id, str_type_id, str_prop): """ Return list replacing type id to type name """ for item in main_list: id_type = item[str_main_id] for type_item in type_list: if type_item[str_type_id] == id_type: item[str_main_id] = type_item[str_prop] break return main_list
def is_core_type(type_): """Returns "true" if the type is considered a core type""" return type_.lower() in { 'int', 'long', 'int128', 'int256', 'double', 'vector', 'string', 'bool', 'true', 'bytes', 'date' }
def get_tag_values_from_ifds(tag_num, ifds): """ Return values of a tag, if found in ifds. Return None otherwise. Assuming any tag exists only once in all ifds. """ for key, ifd in ifds.items(): if tag_num in ifd.tags: return ifd.tags[tag_num].values return None
def all_gt_counts(n_alleles, ploidy): """ all_gt_counts(n_alleles=3, ploidy=2) -> (2, 0, 0), (1, 1, 0), (1, 0, 1), (0, 2, 0), (0, 1, 1), (0, 0, 2) all_gt_counts(n_alleles=2, ploidy=3) -> (3, 0), (2, 1), (1, 2), (0, 3) """ if n_alleles == 1: return ((ploidy,),) genotype = [0] * n_alleles genotype[0] = ploidy res = [tuple(genotype)] ix = 0 remaining = 0 n_alleles_2 = n_alleles - 2 while True: while not genotype[ix]: if not ix: return tuple(res) genotype[ix + 1] = 0 ix -= 1 genotype[ix] -= 1 remaining += 1 genotype[ix + 1] = remaining res.append(tuple(genotype)) if ix < n_alleles_2: ix += 1 remaining = 0
def _build_tags_predicates(match_all=None): """ Build tags predicates """ must = {} if match_all: for condition in match_all: must[condition['tag']] = condition['value'] return must
def get_shape2D(in_val): """ Return a 2D shape Args: in_val (int or list with length 2) Returns: list with length 2 """ in_val = int(in_val) if isinstance(in_val, int): return [in_val, in_val] if isinstance(in_val, list): assert len(in_val) == 2 return in_val raise RuntimeError('Illegal shape: {}'.format(in_val))
def compute_limits(numdata, numblocks, blocksize, blockn): """ Generates the limit of indices corresponding to a specific block. It takes into account the non-exact divisibility of numdata into numblocks letting the last block to take the extra chunk. Parameters ---------- numdata : int Total number of data points to distribute numblocks : int Total number of blocks to distribute into blocksize : int Size of data per block blockn : int Index of block, from 0 to numblocks-1 Return ---------- start : int Position to start assigning indices end : int One beyond position to stop assigning indices """ start = blockn * blocksize end = start + blocksize if blockn == (numblocks - 1): # last block gets the extra end = numdata return start, end
def _take(n, mydict): """Return first n items of the iterable as a list""" return {k: mydict[k] for k in list(mydict)[:n]}
def normalise_dict_keys(dict_obj): """replaces `:` to `-` in dict""" result = {} for key, value in dict_obj.items(): key = key.replace(":", "-") result[key] = value return result
def error_reduction(error_before_split, error_after_split): """ Purpose: Compute the difference between error before and after split Input : Error before split and error after split Output : Difference between error before and after split """ return (error_before_split - error_after_split)
def count_m_w(data): """ Count men and women in the given data (list of dict) Sex is in the 'civilite' column """ men = [item for item in data if item['civilite'] == "M."] women = [item for item in data if item['civilite'] == "Mme"] return len(men), len(women)
def lowest_weight(edges): """ Get edges based on lowest weight first """ return list(sorted(edges, key=lambda data: data[2]["weight"]))
def have_underscore_symbol(l): """Check if underscore is present""" if "_" in str(l): return 1 else: return 0
def calculate_value(player_name, game_data): """ Compute the total ship value of a player. Parameters ---------- player_name: name of the player to count value (str) game_data: game before command execution (dic) Version ------- Specification: Alisson Leist, Bayron Mahy, Nicolas Van Bossuyt (v1. 24/02/17) Implementation: Alisson Leist (v1. 24/02/17) """ total_value = 0 for ship in game_data['ships']: if game_data['ships'][ship]['owner'] == player_name: total_value += game_data['model_ship'][game_data['ships'][ship]['type']]['price'] return total_value
def get_language(file_path): """Returns the language a file is written in.""" # print(file_path) if file_path.endswith(".py"): return "python" else: return ''
def x_to_s (x, chars): """Convert a list of integers to a string. x_to_s(x, chars) -> s The reverse of s_to_x. """ return ''.join(chars[d] for d in x)
def get_median(elements): """The midpoint value of a data set for which an equal number of samples are less than and greater than the value. For an odd sample size, this is the middle element of the sorted sample; for an even sample size, this is the average of the middle elements of the sorted sample.""" elements.sort() length_of_elements = len(elements) mid_position = length_of_elements // 2 if length_of_elements % 2 == 0: # for even number of items, the median is the average of the 2 middle # elements sum_of_the_mids = (elements[mid_position - 1] + elements[mid_position]) median = sum_of_the_mids / 2 else: # for odd number of items, the median is the middle element median = elements[mid_position] return median
def question1(s, t): """input- two strings output- True if anagram of t is substring in s, False otherwise""" if not t: return False t_list = list(t) for i in range(len(s)): value = s[i] if value in t_list: for j in range(len(t_list)): if t_list[j] == value: del t_list[j] break else: t_list = list(t) if not t_list: return True return False
def replace_elem(lst, index, elem): """Create and return a new list whose elements are the same as those in LST except at index INDEX, which should contain element ELEM instead. >>> old = [1, 2, 3, 4, 5, 6, 7] >>> new = replace_elem(old, 2, 8) >>> new [1, 2, 8, 4, 5, 6, 7] >>> new is old # check that replace_elem outputs a new list False """ assert index >= 0 and index < len(lst), 'Index is out of bounds' "*** YOUR CODE HERE ***" return lst[:index] + [elem] + lst[index + 1:]
def no_prefix(name): """does the given constant have a ZMQ_ prefix?""" return name.startswith('E') and not name.startswith('EVENT')
def fastMaxVal(toConsider, avail, memo = {}): """Assumes toConsider a list of items, avail a weight Returns a tuple of the total value of a solution to 0/1 knapsack problem and the items of that solution""" if (len(toConsider), avail) in memo: result = memo[(len(toConsider), avail)] elif toConsider == [] or avail == 0: result = (0, ()) elif toConsider[0].getCost() > avail: result = fastMaxVal(toConsider[1:], avail, memo) else: nextItem = toConsider[0] withVal, withToTake = fastMaxVal(toConsider[1:], avail-nextItem.getCost(), memo) withVal += nextItem.getValue() withoutVal, withoutToTake = fastMaxVal(toConsider[1:], avail, memo) if withVal > withoutVal: result = (withVal, withToTake + (nextItem,)) else: result = (withoutVal, withoutToTake) memo[(len(toConsider), avail)] = result return result
def common_suffix(a, b): """ compute longest common suffix of a and b """ while not a.endswith(b): b = b[1:] return b
def isclassinstance(obj): """Return True if obj is an instance of a class.""" return hasattr(obj, '__class__')
def _check_axis_in_range(axis, ndim): """Checks axes are with the bounds of ndim""" if -ndim <= axis < ndim: return True raise ValueError(f'axis {axis} is out of bounds for array of dimension {ndim}')
def Quiz_Answer_Check(Question, Key, Answers): """ Function to check the Quiz Answers""" Index = 0 Q = 0 Correct = 0 while Q != Question: if Key[Index] == Answers[Index]: Correct += 1 Q += 1 Index += 1 Grade = int((Correct / Question) * 100) return Correct, Grade
def read_str_file(file_name): """ Reads in a file with floating point value strings, 1 per line. """ x = [] try: with open(file_name, 'r') as f: lines = f.read().splitlines() for y in lines: try: x.append(float(y)) except ValueError: continue return x except: print('file {} not successfully read'.format(file_name)) return -1
def leading_zero_template(ceiling): """Return a template suitable for formatting numbers less than 'ceiling'. ceiling -- int or None Returns a string suitable for Python %-formatting numbers from 0 to ceiling-1, with leading zeros so that the strings have constant length. If ceiling is None, there will be no leading zeros. That is, the result is either '%d' or '%0Nd' for some N. """ if ceiling is None: return "%d" else: zeros = len(str(ceiling - 1)) return "%%0%dd" % zeros
def get_int_default_or_max(val, default_val, max_val=None): """Given a string try to turn it into an int and enforce a max and default if the string is not a int value""" try: i = int(val) if max_val and i > max_val: i = max_val except: i = default_val return i
def fix_strength(val, default): """ Assigns given strength to a default value if needed. """ return val and int(val) or default
def pack(ascii, tail=b''): """Packs groups of 4 ascii-encoded edifact chars into 3-byte words.""" assert (len(ascii) + len(tail)) % 4 == 0 raw = [code & 0x3F for code in ascii if 32 <= code <= 94] if len(raw) < len(ascii): raise ValueError('Invalid EDIFACT') raw += tail packed = [] while len(raw) > 0: word = ((raw.pop(0) << 18) + (raw.pop(0) << 12) + (raw.pop(0) << 6) + (raw.pop(0))) packed += [word >> 16, (word >> 8) & 0xFF, (word >> 0) & 0xFF] return bytes(packed)
def halvorsen(xyz, t, a): """Like a rose with only three petals. Cyclically symmetric.""" x, y, z = xyz dx = - a * x - 4 * (y + z) - y ** 2 # dt dy = - a * y - 4 * (z + x) - z ** 2 # dt dz = - a * z - 4 * (x + y) - x ** 2 # dt return dx, dy, dz