content
stringlengths
42
6.51k
def cval(x,digits=2,py2=False) : """ routine to convert value to "Kurucz-style" string, i.e. mXX or pXX Args: x (float) : value to put into output format Returns : (str) : string with output """ if x < -0.000001 : prefix = 'm' else : prefix = 'p' formstr='{{:0{:d}d}}'.format(digits) if py2 : eps=0.0001 else : eps=0. return prefix+formstr.format(int(round((abs(x)+eps)*10.**(digits-1))))
def sd(array): """ Calculates the standard deviation of an array/vector """ import statistics return statistics.stdev(array)
def make_plural(name): """Returns the plural version of the given name argument. Originally developed for Stalker """ plural_name = name + "s" if name[-1] == "y": plural_name = name[:-1] + "ies" elif name[-2:] == "ch": plural_name = name + "es" elif name[-1] == "f": plural_name = name[:-1] + "ves" elif name[-1] == "s": plural_name = name + "es" return plural_name
def cxxs(q, ip): """ Single charge exchange cross section according to the Mueller Salzborn formula Parameters ---------- q : int Charge state of the colliding ion ip : float <eV> Ionisation potential of the collision partner (neutral gas) Returns ------- float <m^2> Charge exchange cross section """ return 1.43e-16 * q**1.17 * ip**-2.76
def myreplace(old, new, s): """ Replace all occurrences of old with new in s. """ s = " ".join(s.split()) return new.join(s.split(old))
def require_package(name): """ Set a required package in the actual working set. Parameters ---------- name: str The name of the package. Returns ------- bool: True if the package exists, False otherwise. """ try: import pkg_resources pkg_resources.working_set.require(name) return True except: # noqa: E722 return False
def default_user_agent(name="python-requests"): """ Return a string representing the default user agent. :rtype: str """ return f"{name}/1.0"
def escape_content(string: str) -> str: """ Escapes given input to avoid tampering with engine/block behavior. """ if string is None: return return pattern.sub(_sub_match, string)
def latin1_encode(text): """ latin1 encode """ try: text.encode("latin1") except UnicodeEncodeError as err: return str(err) return None
def descendants_to_path(path: str): """Get the descendants to a path. :param path: The path to the value :return: The descendants to the path """ parts = path.split(".") return [path.rsplit(".", i)[0] for i in reversed(range(len(parts)))]
def b_prolate(kappa): """ 0 = prolate <= b_P <= -1 = oblate Townes and Schawlow, Ch. 4 """ return (kappa+1.)/(kappa-3.)
def slack_escape(text: str) -> str: """ Escape special control characters in text formatted for Slack's markup. This applies escaping rules as documented on https://api.slack.com/reference/surfaces/formatting#escaping """ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def acceleration_to_dxl(value, model): """Converts from degrees/second^2 to ticks""" return int(round(value / 8.583, 0))
def at(offset, source_bytes, search_bytes): """returns True if the exact bytes search_bytes was found in source_bytes at offset (no wildcards), otherwise False""" return source_bytes[offset:offset+len(search_bytes)] == search_bytes
def add_metadata_columns_to_schema(schema_message): """Metadata _sdc columns according to the stitch documentation at https://www.stitchdata.com/docs/data-structure/integration-schemas#sdc-columns Metadata columns gives information about data injections """ extended_schema_message = schema_message extended_schema_message['schema']['properties']['_sdc_batched_at'] = { 'type': ['null', 'string'], 'format': 'date-time' } extended_schema_message['schema']['properties']['_sdc_deleted_at'] = { 'type': ['null', 'string'] } extended_schema_message['schema']['properties']['_sdc_extracted_at'] = { 'type': ['null', 'string'], 'format': 'date-time' } extended_schema_message['schema']['properties']['_sdc_primary_key'] = {'type': ['null', 'string'] } extended_schema_message['schema']['properties']['_sdc_received_at'] = { 'type': ['null', 'string'], 'format': 'date-time' } extended_schema_message['schema']['properties']['_sdc_sequence'] = {'type': ['integer'] } extended_schema_message['schema']['properties']['_sdc_table_version'] = {'type': ['null', 'string'] } return extended_schema_message
def num_digits(n): """ Given a number n, this function returns its number of digits in base 10. """ return len(str(n))
def vowelsRemover(words): """This function takes in a string and returns a string back without vowels""" m_vowels = ['a', 'e', 'i', 'o', 'u'] m_temp = "" for letter in words: if letter.lower() not in m_vowels: m_temp += letter return m_temp
def duplicate_object_hook(ordered_pairs): """Make lists out of duplicate keys.""" json_dict = {} for key, val in ordered_pairs: existing_val = json_dict.get(key) if not existing_val: json_dict[key] = val else: if isinstance(existing_val, list): existing_val.append(val) else: json_dict[key] = [existing_val, val] return json_dict
def public_dict(d: dict) -> dict: """Remove keys starting with '_' from dict.""" return { k: v for k, v in d.items() if not (isinstance(k, str) and k.startswith("_")) }
def all_subclasses(cls): """Return a set of subclasses of a given cls.""" return set(cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in all_subclasses(c)])
def makelol(inlist): """ Converts a 1D list to a 2D list (i.e., a list-of-lists). Useful when you want to use put() to write a 1D list one item per line in the file. Usage: makelol(inlist) Returns: if l = [1,2,'hi'] then returns [[1],[2],['hi']] etc. """ x = [] for item in inlist: x.append([item]) return x
def batch_action_template(form, user, translations, locale): """Empty batch action, does nothing, only used for documentation. :arg BatchActionsForm form: the form containing parameters passed to the view :arg User user: the User object of the currently logged-in user :arg QuerySet translations: the list of translations that should be affected :arg Locale locale: the current locale :returns: a dict containing: * count: the number of affected translations * translated_resources: a list of TranslatedResource objects associated with the translations * changed_entities: a list of Entity objects associated with the translations * latest_translation_pk: the id of the latest affected translation * changed_translation_pks: a list of ids of affected translations * invalid_translation_pks: a list of ids of translations that have errors or changes on them could introduce new errors e.g. after find & replace """ return { "count": 0, "translated_resources": [], "changed_entities": [], "latest_translation_pk": None, "changed_translation_pks": [], "invalid_translation_pks": [], }
def validateDict(user_cfg={}, defaults={}):# dict """ validates a dictionary by comparing it to the default values from another given dict. """ validated = {} for each in defaults: try: validated[each] = user_cfg[each] except KeyError: validated[each] = defaults[each] return validated
def lcs(a, b): """Longest common substring of two strings.""" lengths = [[0 for j in range(len(b) + 1)] for i in range(len(a) + 1)] # row 0 and column 0 are initialized to 0 already for i, x in enumerate(a): for j, y in enumerate(b): if x == y: lengths[i + 1][j + 1] = lengths[i][j] + 1 else: lengths[i + 1][j + 1] = max(lengths[i + 1][j], lengths[i][j + 1]) # read the substring out from the matrix result = 0 x, y = len(a), len(b) while x != 0 and y != 0: if lengths[x][y] == lengths[x - 1][y]: x -= 1 elif lengths[x][y] == lengths[x][y - 1]: y -= 1 else: assert a[x - 1] == b[y - 1] result += 1 x -= 1 y -= 1 return result
def _GetFailedRevisionFromCompileResult(compile_result): """Determines the failed revision given compile_result. Args: compile_result: A dict containing the results from a compile. Please refer to try_job_result_format.md for format check. Returns: The failed revision from compile_results, or None if not found. """ return ( compile_result.get('report', {}).get('culprit') if compile_result else None)
def type(record): """ Put the type into lower case. :param record: the record. :type record: dict :returns: dict -- the modified record. """ if "type" in record: record["type"] = record["type"].lower() return record
def switch_block_hash(switch_block) -> str: """Returns hash of most recent switch block. """ return switch_block["hash"]
def get_pred_item(list_, index, key): """ retrieves value of key from dicts in a list""" dict_ = list_[index] return dict_.get(key)
def get_story_memcache_key(story_id, version=None): """Returns a memcache key for the story. Args: story_id: str. ID of the story. version: str. Schema version of the story. Returns: str. The memcache key of the story. """ if version: return 'story-version:%s:%s' % (story_id, version) else: return 'story:%s' % story_id
def flatten_dict(data, sep='.', prefix=''): """Flattens a nested dict into a dict. eg. {'a': 2, 'b': {'c': 20}} -> {'a': 2, 'b.c': 20} """ x = {} for key, val in data.items(): if isinstance(val, dict): x.update(flatten_dict(val, sep=sep, prefix=key)) else: x[f'{prefix}{sep}{key}'] = val return x
def lte(value, arg): """Returns a boolean of whether the value is less than or equal to the argument. """ return value <= int(arg)
def prep_grid(D): """ :param D: Dict of dicts :return: """ try: return {key:[{key:val} for val in D[key]] for key in D} except: return {}
def tap(callback, func, *args, **kwargs): """What does this even accomplish...""" result = func(*args, **kwargs) callback(result) return result
def calc_num_opening_mismatches(matches): """(Internal) Count the number of -1 entries at the beginning of a list of numbers. These -1 correspond to mismatches in the sequence to sequence search. """ if matches[0] != -1: return 0 num = 1 while matches[num] == -1: num += 1 return num
def derive_model_combinations(model_template, algorithm_definition): """ A model can have two formats: 1. "model" : "./a001_model.json" : the result is simply one option with one possibility 2. "model": "./a002_2_@@parameter@@_model.json" In the second case the template describes n models. In this case all learn and estimate command lines are cross-joined/matrix-multiplied by the possible combinations for the model. """ result = list() # when the model_template is using the parameter definitions # then we multiply our model_template by all variants of the parameter if "@@parameter@@" in model_template: for parameter in algorithm_definition["parameters"]: template = model_template template = template.replace("@@parameter@@", parameter["filenameext"]) result.append(template) else: # otherwise we return just one version result.append(model_template) return result
def to_string_list(iterable): """Utility function to produce a string like: "'A', 'B', 'C'" from ['B', 'A', 'C']. >>> to_string_list(['B', 'A', 'C']) "'A', 'B', 'C'" """ return ', '.join(map(repr, sorted(iterable)))
def _remove_nulls(output): """Remove nulls from dict. Temporary until we fix this in cosmos :param output: dict with possible null values :type output: dict :returns: dict without null :rtype: dict """ return {k: v for k, v in output.items() if v}
def idFormat(id_num): """Format a numeric id into 5-digit string. Paramters --------- id_num: str A unique string number assigned to a User or Request. """ if len(id_num) == 1: id_num = "0000" + id_num elif len(id_num) == 2: id_num = "000" + id_num elif len(id_num) == 3: id_num = "00" + id_num elif len(id_num) == 4: id_num = "0" + id_num return id_num
def mix_columns(state): """ Compute MixColumns of state. """ return [state[0] ^ state[2] ^ state[3], \ state[0], \ state[1] ^ state[2], \ state[0] ^ state[2]]
def is_identity_matrix(L): """ Returns True if the input matrix is an identity matrix, False otherwise. """ result = len(L) == len(L[0]) for i in range(len(L)): for j in range(len(L)): if i == j: result *= (L[i][j] == 1) else: result *= (L[i][j] == 0) return result
def get_candidate_type_and_position(e, idx): """Returns type and position info for the candidate at the given index.""" if idx == -1: return "[NoLongAnswer]" else: return e["long_answer_candidates"][idx]["type_and_position"]
def prettify(method): """Return a pretty representation of a method for use with logging Args: method Bound method instance Returns: string in the form MyClass.my_method """ rs = "" if hasattr(method, "im_self") and method.__dict__.has_key('__self__'): rs += str(method.__self__.__class__.__name__) elif hasattr(method, "im_self") and method.__dict__.has_key('__class__'): rs += str(method.__class__.__name__) if hasattr(method, "im_func") and method.__dict__.has_key('__func__'): rs += '.' + method.__func__.__name__ if not rs and hasattr(method, 'func_name'): rs += method.func_name return rs
def string_parse(input_str): """ Converts passed string, into *args, **kwargs: Args: input_str(str): input string in format - "1, 2, 3, a\nvalue3=4, value1=arg1, value2=arg2" Returns: tuple(*args, **kwargs): parsed args, and kwargs values """ args_str, kwargs_str = input_str.split('\n') args_raw = args_str.split(',') kwargs_raw = kwargs_str.split(', ') args = [item.strip() for item in args_raw] kwargs = dict((item.split('=') for item in kwargs_raw)) return args, kwargs
def reversedigits(i, base=10): """ >>> reversedigits(0) 0 >>> reversedigits(9) 9 >>> reversedigits(13) 31 >>> reversedigits(80891492769135132) 23153196729419808L """ j = 0 while i: j *= base j += i % base i //= base return j
def xform_entity(entity_dict, data): """ Applies transformation functions specified by the entity dictionary (first param) to the user-supplied data (second param). If no user data is supplied for the given field in the entity dictionary, then the default value for the field is supplied. Parameters ---------- entity_dict: dict Dictionary containing all fields required for the type of record in question. Expected format of this dict is {"key": (value)} where value is a tuple in the following format: (default value, length, fill character, transformation function) data: dict Data to be transformed and inserted into the returned dict. All keys in this dict are expected to be present in entity_dict. Returns ---------- dict Dictionary containing all fields specified in parameter "entity_dict", with transformed values from parameter "data" or defaults. """ data_dict = {} for key, (default, _, _, transform) in entity_dict.items(): if key in data: data_dict[key] = transform(data[key]) else: data_dict[key] = default return data_dict
def binary_search(arr, target): """ ATTENTION: THE PROVIDED ARRAY MUST BE SORTED! Searches for an item using binary search algorithm. Run time: O(log n) """ if arr == []: return False mid_ind = int(len(arr) / 2) if (target < arr[mid_ind]): return binary_search(arr[:mid_ind], target) elif target > arr[mid_ind]: return binary_search(arr[mid_ind + 1:], target) return True
def lower_tokens(tokens): """ Lowers the type case of a list of tokens :param tokens: A list of tokens :return: A comparable list of tokens to the input but all lower case """ cleaned_tokens = [] for token in tokens: token = token.lower() cleaned_tokens.append(token) return cleaned_tokens
def default(value): """ Given a python object, return the default value of that object. :param value: The value to get the default of :returns: The default value """ return type(value)()
def unique_list(lst): """ Removes duplicates from a list while preserving order """ res = [] for i, item in enumerate(lst): if i == len(lst) - 1 or lst[i + 1] != item: res.append(item) return res
def extract_results_in_range(start_index, end_index, keys, total_results): """ Given the indexes and keys this method loop between indexes :param start_index: :param end_index: :param keys: :param total_results: :return: """ return {k: total_results[k] for k in keys[start_index:end_index]}
def get_logs(self): """ returns list of logs for the object """ if hasattr(self, 'logs'): return self.logs return []
def _num_dividends(P, K): """ Returns the number of multiples of K for a 0 index sequence P. :param P: :param K: :return: """ return (P // K) + 1
def progress_bar(label, value, max): """Render a Bootstrap progress bar. :param label: :param value: :param max: Example usage: {% progress_bar label='Toner: 448 pages remaining' value=448 max=24000 %} """ return { 'label': label, 'percent': int((value / max) * 100), 'value': value, 'max': max, }
def win_check(hidden_word, guessed_letters): """ hidden_word: string, the hidden word to guess guessed_letters: list, with all letters user have used return: boolean, True if all letters of hidden_word exist in guessed_letters otherwise False """ for letter in hidden_word: if letter not in guessed_letters: return False return True
def first(iterable, *default): """Returns the first value of anything iterable, or throws StopIteration if it is empty. Or, if you specify a default argument, it will return that. """ return next(iter(iterable), *default)
def power(base, exp): """Finding the power""" assert exp >=0 and int(exp) == exp, 'The exponential must be positive integers only' if exp == 0: return 1 if exp == 1: return base return base * power(base, exp-1)
def fold(s): # function fold: auxiliary function: shorten long option values for output """auxiliary function: shorten long option values for output""" offset = 64 * " " maxlen = 70 sep = "|" # separator for split parts = s.split(sep) # split s on sep line = "" out = "" for f in range(0, len(parts)): if f != len(parts) - 1: line = line + parts[f] + sep else: line = line + parts[f] if len(line) >= maxlen: out = out +line+ "\n" + offset line = "" out = out + line return out
def paren_int(number): """ returns an integer from a string "([0-9]+)" """ return int(number.replace('(', '').replace(')', ''))
def pwin(e1, e2): """probability e1 beats e2""" return (1.0/(1+(10**((e2-e1)/float(400)))))
def div(n, d): """Divide, with a useful interpretation of division by zero.""" try: return n/d except ZeroDivisionError: if n: return n*float('inf') return float('nan')
def isInt(value): """Returns True if convertible to integer""" try: int(value) return True except (ValueError, TypeError): return False
def revert_old_country_names(c: str) -> str: """Reverting country full names to old ones, as some datasets are not updated on the issue.""" if c == "North Macedonia": return "Macedonia" if c == "Czechia": return "Czech Republic" return c
def AsList(val): """Ensures the JSON-LD object is a list.""" if isinstance(val, list): return val elif val is None: return [] else: return [val]
def ibits(ival,ipos,ilen): """Same usage as Fortran ibits function.""" ones = ((1 << ilen)-1) return ( ival & (ones << ipos) ) >> ipos
def scala_T(input_T): """ Helper function for building Inception layers. Transforms a list of numbers to a dictionary with ascending keys and 0 appended to the front. Ignores dictionary inputs. :param input_T: either list or dict :return: dictionary with ascending keys and 0 appended to front {0: 0, 1: realdata_1, 2: realdata_2, ...} """ if type(input_T) is list: # insert 0 into first index spot, such that the real data starts from index 1 temp = [0] temp.extend(input_T) return dict(enumerate(temp)) # if dictionary, return it back return input_T
def unique_values(seq): """ Return unique values of sequence seq, according to ID function idfun. From http://www.peterbe.com/plog/uniqifiers-benchmark and modified. Values in seq must be hashable for this to work """ seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result
def _af_parity(pi): """ Computes the parity of a permutation in array form. The parity of a permutation reflects the parity of the number of inversions in the permutation, i.e., the number of pairs of x and y such that x > y but p[x] < p[y]. Examples ======== >>> from sympy.combinatorics.permutations import _af_parity >>> _af_parity([0,1,2,3]) 0 >>> _af_parity([3,2,0,1]) 1 See Also ======== Permutation """ n = len(pi) a = [0] * n c = 0 for j in range(n): if a[j] == 0: c += 1 a[j] = 1 i = j while pi[i] != j: i = pi[i] a[i] = 1 return (n - c) % 2
def get_material_requires_texcoords(glTF, index): """ Query function, if a material "needs" texture cooridnates. This is the case, if a texture is present and used. """ if glTF.get('materials') is None: return False materials = glTF['materials'] if index < 0 or index >= len(materials): return False material = materials[index] # General if material.get('emissiveTexture') is not None: return True if material.get('normalTexture') is not None: return True if material.get('occlusionTexture') is not None: return True # Metallic roughness if material.get('baseColorTexture') is not None: return True if material.get('metallicRoughnessTexture') is not None: return True # Specular glossiness if material.get('diffuseTexture') is not None: return True if material.get('specularGlossinessTexture') is not None: return True # Unlit Material if material.get('diffuseTexture') is not None: return True return False
def hex_to_rgb(hex: str) -> tuple: """ Args: hex (str): """ return tuple(int(hex.lstrip("#")[i : i + 2], 16) for i in (0, 2, 4))
def is_stupid_header_row(row): """returns true if we believe row is what the EPN-TAP people used as section separators in the columns table. That is: the text is red:-) """ try: perhaps_p = row.contents[0].contents[0] perhaps_span = perhaps_p.contents[0] if perhaps_span.get("style")=='color: rgb(255,0,0);': return True except (AttributeError, KeyError): pass # Fall through to False return False
def Clamp(value, low=0.0, high=1.0): """Clamp a value between some low and high value.""" return min(max(value, low), high)
def _get_snap_name(snapshot): """Return the name of the snapshot that Purity will use.""" return "%s-cinder.%s" % (snapshot["volume_name"], snapshot["name"])
def _calc_ts_complexity(tss, pers): """ Calculates the complexity of a TS schema Complexity = (Number of Schemas + Number of Permutable Symbols + Lenght of each Permutable Symbol) """ return len(tss) + sum([len(per) for ts, per in zip(tss, pers)])
def Crosses(ps, thresh): """Tests whether a sequence of p-values ever drops below thresh.""" if thresh is None: return False for p in ps: if p <= thresh: return True return False
def step_name_str(yaml_stem: str, i: int, step_key: str) -> str: """Returns a string which uniquely and hierarchically identifies a step in a workflow Args: yaml_stem (str): The name of the workflow (filepath stem) i (int): The (zero-based) step number step_key (str): The name of the step (used as a dict key) Returns: str: The parameters (and the word 'step') joined together with double underscores """ # Use double underscore so we can '__'.split() below. # (This should work as long as yaml_stem and step_key do not contain __) return f'{yaml_stem}__step__{i+1}__{step_key}'
def isclose(a, b, rel_tol=1e-02, abs_tol=0.0): """ Parameters ---------- a : int/float first value b : int/float second value rel_tol : float, (optional) relative tolerance abs_tol : float, (optional) the absolute tolerance Returns ------- """ return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def actions(elements, **kwargs): """ Define a block "action". API: https://api.slack.com/reference/messaging/blocks#actions Other Parameters ---------------- block_id : str Returns ------- dict """ return {'type': 'actions', 'elements': elements, **kwargs}
def assert_(condition, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """ Return `value` if the `condition` is satisfied and raise an `AssertionError` with the specified `message` and `args` if not. """ message = None if args: message = args[0] args = args[1:] if message: assert condition, message % args else: assert condition return kwargs.get('value')
def pi_using_float(precision): """Get value of pi via BBP formula to specified precision using floats. See: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula :param precision: Precision to retrieve. :return: Pi value with specified precision. """ value = 0 for k in range(precision): # Dot suffix converts value to a Float. value += 1. / 16. ** k * ( 4. / (8. * k + 1.) - 2. / (8. * k + 4.) - 1. / (8. * k + 5.) - 1. / (8. * k + 6.) ) return value
def get_version(program: str) -> str: """ Return version of a program. :param program: program's name. :return: version. """ import subprocess cmd = "dpkg -l | grep '{}'".format(program) process = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) (out, _) = process.communicate() result = out.decode() version = result.split() if len(version) >= 3: if version[1] == program: return version[2] return "Cannot find version for '{}'".format(program)
def fibonacci(n): """ Returns nth fibonacci number F(n) F(n) = F(n-2) + F(n-1) """ k, m = 1, 1 if n < 2: return n for i in range(2, n): k, m = m, k + m return m
def rescaleInput(input): """ scales input's elements down to range 0.1 to 1.0. """ return (0.99 * input / 255.0) + .1
def filter_techniques_by_platform(tech_list, platforms): """Given a technique list and a platforms list, filter out techniques that are not part of the platforms""" if not platforms: return tech_list filtered_list = [] # Map to easily find objs and avoid duplicates ids_for_duplicates = {} for obj in tech_list: # Do not try to find if it's already on the filtered list if not ids_for_duplicates.get(obj['id']): for platform in platforms: if platform in obj["x_mitre_platforms"]: ids_for_duplicates[obj['id']] = True filtered_list.append(obj) break return filtered_list
def get_secret_variables(app_config: dict) -> dict: """Returns the secret variables from configuration.""" secret_variables = app_config.get("variables", {}).get("secret", {}) formatted_secret_variables = { secret_name: { "secretKeyRef": { "name": secret_variables[secret_name]["name"], "key": secret_variables[secret_name]["key"], }, } for secret_name in secret_variables.keys() } return formatted_secret_variables
def _prefix_statistics(prefix, stats): """Prefix all keys in a statistic dictionary.""" for key in list(stats.keys()): stats['{}/{}'.format(prefix, key)] = stats.pop(key) return stats
def _normalize_jsonpath(jsonpath): """Changes jsonpath starting with a `.` character with a `$`""" if jsonpath == '.': jsonpath = '$' elif jsonpath.startswith('.'): jsonpath = '$' + jsonpath return jsonpath
def get_top_grossing_directors(top_grossing, top_casts): """ Gets all directors who directed top grossing movies :param top_grossing: dictionary of top grossing movies :param top_casts: dictionary of top casts :return: sorted list of top grossing movie directors """ top_directors = {} for grossing in top_grossing: director = top_casts[grossing][0] if director in top_directors: top_directors[director] += 1 else: top_directors.update({director: 1}) top = sorted(top_directors.items(), key=lambda x: x[1], reverse=True) return top
def check_for_newline(s, pos): """This function, given a string s (probably a long string, like a line or a file) and a position 'pos', in the string, eats up all the whitespace it can and records whether a newline was among that whitespace. It returns a tuple (saw_newline, new_pos) where saw_newline will be true if a newline was seen, and new_pos is the new position after eating up whitespace-- so either new_pos == len(s) or s[new_pos] is non-whitespace. """ assert isinstance(s, str) and isinstance(pos, int) assert pos >= 0 saw_newline = False while pos < len(s) and s[pos].isspace(): if s[pos] == "\n": saw_newline = True pos += 1 return (saw_newline, pos)
def sign(value): """Return the sign of a value as 1 or -1. Args: value (int): The value to check Returns: int: -1 if `value` is negative, and 1 if `value` is positive """ if value < 0: return -1 else: return 1
def get_kwargs_set(args, exp_elem2dflt): """Return user-specified keyword args in a dictionary and a set (for True/False items).""" arg_set = set() # For arguments that are True or False (present in set if True) # Add user items if True for key, val in args.items(): if exp_elem2dflt is not None and key in exp_elem2dflt and val: arg_set.add(key) # Add defaults if needed for key, dfltval in exp_elem2dflt.items(): if dfltval and key not in arg_set: arg_set.add(key) return arg_set
def value_of_card(card): """ :param card: str - given card. :return: int - value of a given card (J, Q, K = 10, numerical value otherwise). """ if card == 'J' or card == 'Q' or card == 'K': value = 10 else: value = int(card) return value
def fix_postcode(pc): """ convert postcodes to standard form standard form is upper case with no spaces >>> pcs = ["LA1 4YF", "LA14YF", " LA1 4YF", "L A 1 4 Y f"] >>> [fix_postcode(pc) for pc in pcs] ['LA14YF', 'LA14YF', 'LA14YF', 'LA14YF'] """ return pc.upper().replace(" ","")
def is_even(num : int) -> bool: """ Check if a number is even or not. Parameters: num: the number to be checked Returns: True if number is even, otherwise False """ if (num%2) == 0: return True else: return False
def rep_to_raw(rep): """Convert a UI-ready rep score back into its approx raw value.""" if not isinstance(rep, (str, float, int)): return 0 if float(rep) == 25: return 0 rep = float(rep) - 25 rep = rep / 9 sign = 1 if rep >= 0 else -1 rep = abs(rep) + 9 return int(sign * pow(10, rep))
def introduction(): """Handle a request for the "Introduction" page. This function really doesn't do much, but it returns the data contained at views/introduction.tpl which contains some detail on the project and useful links to other information. Returns: (string) A web page (via the @view decorator) an introduction to the project. """ return {'error': None}
def format_pct(p): """Format a percentage value for the HTML reports.""" return "%.0f" % p
def construct_supervisor_command_line(supervisor_ip, cols, rows, area_size, traffic, road_cells, nodes, apn): """Creates the command to start up the supervisor. :type supervisor_ip: str :param supervisor_ip: the private IP address of supervisor :type cols: int :param cols: city cols :type rows: int :param rows: city rows :type area_size: int :param area_size: size of the area :type traffic: float :param traffic: traffic density :type road_cells: int :param road_cells: road cells :type nodes: int :param nodes: nodes number :type apn: int :param apn: areas per node :rtype: str :return: command line to start up the supervisor """ command_line = [ 'java', '-Dakka.remote.netty.tcp.hostname=' + supervisor_ip, '-Dtrafficsimulation.warmup.seconds=20', '-Dtrafficsimulation.time.seconds=20', '-Dtrafficsimulation.city.cols=' + str(cols), '-Dtrafficsimulation.city.rows=' + str(rows), '-Dtrafficsimulation.area.size=' + str(area_size), '-Dtrafficsimulation.area.traffic_density=%.2f' % traffic, '-Dtrafficsimulation.area.cells_between_intersections=' + str(road_cells), '-Dworker.nodes=' + str(nodes), '-Dworker.areas_per_node=' + str(apn), '-Dakka.remote.log-remote-lifecycle-events=off', '-Dakka.loglevel=INFO', '-jar', '/home/ubuntu/supervisor.jar' ] return ' '.join(command_line)
def reversing_words3(s): """ >>> reversing_words('buffy is awesome') 'awesome is buffy' """ words = s.split(' ') words.reverse() return ' '.join(words)
def toggle_collapse(n, is_open): """ Simple callback that will toggle the collapse :param n: The initial state of n_clicks :param is_open: The initial state of is_open :return: The result state of is_open after it is toggled """ if n: return not is_open return is_open
def is_dict_subset_of(sub_dict, super_dict): """Checks if sub_dict is contained in the super_dict. :param sub_dict: A mapping. This is looked for in the super_dict. :param super_dict: A mapping. May or may not contain the sub_dict. :return: True, if all the key-value pairs of sub_dict are present in the super_dict. False otherwise. """ return all(key in super_dict and super_dict[key] == value for key, value in sub_dict.items())