content
stringlengths
42
6.51k
def home_view(request): """Home page view.""" return {'project': 'mars-street-view'}
def _is_exported(ident_name): """ Returns `True` if `ident_name` matches the export criteria for an identifier name. This should not be used by clients. Instead, use `pydoc.Module.is_public`. """ return not ident_name.startswith('_')
def sample_types(SAMPLE_TYPE, SAMPLE_BYTES): """Defines a translation from PDS data types to Python data types, using both the type and bytes specified (because the mapping to type is not consistent across PDS3). """ return { "MSB_INTEGER": ">h", "INTEGER": ">h", "MAC...
def ast_rotate_right(ast): """Performs a right rotation of the AST around its root. Args: ast: The AST dict. Returns: The new root of the rotated AST. """ root = ast if "left" in root: # If root is binary pivot = root["left"] if "right" in pivot: # If pivot is...
def top_sentences(query, sentences, idfs, n): """ Given a `query` (a set of words), `sentences` (a dictionary mapping sentences to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the `n` top sentences that match the query, ranked according to idf...
def sql_escape(s): """ Escape strings that might contain single quotes for use in Athena or S3 Select """ escaped = s or "" return escaped.replace("'", "''")
def get_click_file_name(click_file): """ Wrapper around click_file.name with consistent handling for stdin On Windows, if click_file is stdin, click_file.name == "-". On Linux, if click_file is stdin, click_file.name == "<stdin>". During unit testing, the simulated stdin stream has no .name attribute. ...
def box_strings(*strings: str, width: int = 80) -> str: """Centre-align and visually box some strings. Args: *strings (str): Strings to box. Each string will be printed on its own line. You need to ensure the strings are short enough to fit in the box (width-6) or the results wi...
def middleOfRect(rect): """Returns int middle point of rectangle""" (x, y, w, h) = rect return (x + int(w/2.0), y + int(h/2.0))
def hello(friend_name): """ Writes Hello to a friend. :param friend_name: Our friend's name :return: Return a message saying hello to our friend """ return "Hello, {0}!".format(friend_name)
def oxygen_criteria(bit_counts): """Bit criteria for oxygen generator rating.""" return '1' if bit_counts['1'] >= bit_counts['0'] else '0'
def _unpacker(results): """ HELPER: Unpacks results if unpack_scalars is True. """ if not results: # Check for None or empty list results = None else: assert len(results) <= 1, 'throwing away results! { %r }' % (results,) results = results[0] return results
def cmp_val(o1, o2): """ :param o1: object 1 to compare :param o2: object 2 to compare :return: if o1 is less than o2 """ if '_' in o1 and '_' not in o2: return False if '_UD' in o1 and '_W' in o2: return False return True
def is_sentence(text): """ Check if a piece of text ends by a punctuation. """ return text and text[-1] in set('!.:;?')
def get_shape_from_dims(axis_0, axis_1=None): """ Constructs a chain shape tuple from an array-like axis_0 and an optional array-like axis_1 :param axis_0: Iterable of dimensions for the first leg on each site of the chain :param axis_1: Optional iterable of dimensions for the second leg on each sit...
def average_time(times): """ takes a collection of times and finds the average :param times: collection of numeric times :return: average of the collection """ total_time = 0 for element in times: total_time += element return int(total_time / len(times))
def nested_lookup(doc, field): """ Performs a nested lookup of doc using a period (.) delimited list of fields. This is a nested dictionary lookup. :param doc: document to perform lookup on :param field: period delimited list of fields :return: """ value = doc keys = field.split('.'...
def stupid_pluralize(string): """Computer => Computers""" return string + "s"
def get_resource_creators(resource): """Gets all creators of a resource record and concatenate them into a string separated by commas. Args: resource (dict): resource record data. Returns: creators (string): comma-separated list of resource creators. """ creators = [] if re...
def build_annotation(extra_fields=None): """return a valid annotation. All annotations minimally require begin/end/coveredText, plus whatever information is passed in extra_fields """ if extra_fields is None: extra_fields = {} ann = {'begin': 0, 'end': 1} # coveredText isn't actually requir...
def flatten_object(obj, result=None): """ Convert a JSON object to a flatten dictionary. example: { "db": { "user": "bar" }} becomes {"db.user": "bar" } """ if not result: result = {} def _flatten(key_obj, name=''): if isinstance(key_obj, dict): for item in key_obj:...
def paginate(mylist, slice_size): """ Paginates a list into a list of lists of input size. """ return [mylist[i:i+slice_size] for i in range(0, len(mylist), slice_size)]
def is_rooted (path): """ Tests if a path is rooted. """ return path and path [0] == '/'
def move(position, roll): """Simple math.""" new_position = position + (roll * 2) return new_position
def dirname(path): """Returns the directory's name. Args: path: The path to return the directory for Returns: The directory's name. """ last_sep = path.rfind("/") if last_sep == -1: return "" return path[:last_sep]
def format_role_arn(role_name, account_id): """ Gets an IAM ARN string. :param role_name: :param account_id: :return: """ return "arn:aws:iam::{}:role/{}".format(account_id, role_name)
def registrar_conteo(diccionario, clave): """ Registra el conteo de la vista. :param diccionario: :param clave: :return: Diccionario con el conteo deseado. """ if clave in diccionario: diccionario[clave] += 1 else: diccionario[clave] = 1 return diccionario
def _convert_index(index, pos, M=None, is_start=True): """Working best with _lcs_match(), convert the token index to origin text index""" if index[pos] is not None: return index[pos] N = len(index) rear = pos while rear < N - 1 and index[rear] is None: rear += 1 front = pos w...
def input_bool(x): """ Try to get a boolean input that matches with the validation function. * If not validation given, any boolean will work * If there are any error, executes the optional exception_function with the input as parameter * If success, executes the optional success_function with the i...
def create_id_list_from_dict_keys(nested_dict:dict) -> list: """ Create a list of company id from the hierarchical dictionary which is eaqula to get all the keys from the :param : :type : :return: :type: """ list_of_keys = [] for key, value in nested_dict.items(): list_of_keys.exten...
def linear_model_flipper_mass(flipper_length, weight_flipper_length, intercept_body_mass): """Linear model of the form y = a * x + b""" body_mass = weight_flipper_length * flipper_length + intercept_body_mass return body_mass
def _get_operator(spec, context): """ Gets operator from context """ try: return context[spec] except KeyError: print( f"Error: Operator ${spec} is not defined. Make sure you are importing it in the modules section." ) raise
def rootpath(path): """Returns a string which cdexec will interpret as absolute. Specifically, if the path starts with '/', it is returned unmodified. Otherwise, the returns the path prefixed by the literal string '${PWD}/' which will be expanded by the `cdexec` script into the Bazel exec root. """ if path...
def is_key_length_fixed(input_dict): """Check if the input dictionary keys are same-length. Args: input_dict (dict): dictionary. Returns: bool: boolean variable indicating whether dict keys are same-length or not. """ key_length = len(list(input_dict.keys())[0]) return all(len(...
def set_image_scale(imx, imy, opt_dict): """ sets image scale of displayed image, depending on options if scale_win2ima: imscale = zoom, window size adapted to image size else imscale adapted to window size :param imx: width of image :param imy: heigth of image :param opt_dict: option...
def two_oldest_ages(ages): """ The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the two highest numbers within the array. The returned value should be an array in the format [second oldest age, oldest age]. The order of the numbers ...
def calc_area(l, w): """ params: l and w are both real positive numbers representing the length and width of a rectangle """ if l <= 0 or w <= 0: raise ValueError return l * w
def getVec4(default_value, init_value = [0.0, 0.0, 0.0, 1.0]): """ Return vec4 with a given default/fallback value. """ return_value = init_value.copy() if default_value is None or len(default_value) < 4: return return_value index = 0 for number in default_value: return_va...
def get_tuple_list_from_json(list_of_json_information_objects, table_name): """ Returns the data to be inserted in SQLite's executemany compatible format (list of tuples) Input: JSON Object Output: List of tuples Raises Exception: Yes """ list_of_tuples ...
def plotkin_bound_asymp(delta,q): """ Computes the asymptotic Plotkin bound for the information rate, provided `0 < \delta < 1-1/q`. EXAMPLES:: sage: plotkin_bound_asymp(1/4,2) 1/2 """ r = 1-1/q return (1-delta/r)
def AU_to_a_r(AU,R): """ function to convert semi-major axis in AU to scaled semi-major axis a/R*. Parameters: ---------- AU: Semi major axis of the planet in AU. R: Radius of the star in units of solar radii. Returns ------- a_r: Scaled semi-major axis. ...
def pad(value, digits, to_right=False): """Only use for positive binary numbers given as strings. Pads to the left by default, or to the right using to_right flag. Inputs: value -- string of bits digits -- number of bits in representation to_right -- Boolean, direction of padding ...
def _to_indexer(data): """ Return indexible attribute of array-like type. """ return getattr(data, 'iloc', data)
def binary_search(haystack, needle, lo, hi): """ Binary search: Return index of value needle (or the next one if no exact match) in array haystack, within index range lo to hi. """ while lo < hi: mid = (lo + hi) // 2 if haystack[mid] > needle: hi = mid elif haysta...
def dict2str(dictionary, **kwargs): """Converts a dict to a string expression. Args: dictionary (dict): A dictionary to convert to a string. Keyword Args: inverse_dict(boolean): Apply inverse order of string (default: ``False``). Returns: str: The dictionary as flattened text....
def validate_vlan_id(vlan_id): """ Validate VLAN ID provided is an acceptable value :param vlan_id: int :return: list """ errors = [] if vlan_id < 1 or vlan_id > 4094: errors.append("Invalid ID: must be a valid vlan id between 1" " and 4094") return errors
def _general_fuel_checker(mass: int) -> int: """Given the mass of a module, calculate the fuel requirement Args: - mass (int): the mass of the module Returns: int: the fuel requirement """ return (mass // 3) - 2
def lineinfo(region): """ Return sensible values for start/end line/columns for the possibly empty entries in the sarif 'region' structure. """ startLine, startColumn, endLine, endColumn = map( lambda e: region.get(e, -1), ['startLine', 'startColumn', 'endLine', 'endColumn']) # Full informat...
def reverse_and_complement(sequence): """Get the reversed and complemented form of `sequence`. Returns a string that is the reversed and complemented sequence of `sequence`. If `sequence` is empty, and empty string is returned. """ rev = sequence[::-1] if sequence: pass else:...
def normalize_weights_dictionary(weights_dict): """ Normalizes weights provided as values in passed weight_dict so that the sum of the weights equals 1. Arguments ---------- weights_dict: a dictionary containing the columns to be included in the weighted sum as keys, and the associate...
def missing_label(set1, set2): """ Subtraction between two sets""" missing_list = list(set(set1) - set(set2)) return missing_list
def style_negative(v, props=""): """Helper function to color text in a DataFrame if it is negative. Parameters ---------- v: float The text (value) in a DataFrame to color props: str A string with a CSS attribute-value pair. E.g "color:red;" See: https://pandas.pydata.org/pan...
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'input_dataset_path': ['csv'], 'output_model_path': ['pkl'], 'output_dataset_path': ['csv'], 'output_results_path': ['csv'], 'input_model_path': ['pkl'], 'output_test_table_path': ['csv'], 'output_plot_...
def sanitize_hyphens(file_name): """ Replace hyphens with underscores if present in file name """ if "-" in file_name.split("/")[-1]: print( "Replacing hyphens with underscores in SPH file output- check to make sure your audio files and transcript files match" ) file_name = "/".join(file_nam...
def analysis(data: str): """ Example of a task provided by a workflow library. Task-specific details such as the Docker image and memory needs are defined here on the task. However, it is left to the user to define the executor 'utils_executor', so that user can customize project-specific details s...
def find_all(str_:str, key:str): """ Returen all the starting indices of string `key` in string `str_`. Example: ---------- >>> find_all("abcaa", 'a') [0, 3, 4] """ p, indices = -1, [] while True: p = str_.find(key, p + 1) if p < 0: break indices.append(...
def all_true(trues): """ :param trues: :return: Return True if all values of list are True, else returns False """ for true in trues: if true is False: return False return True
def range_string_to_indicies(string, list_len, inclusive=True, sort_unique=True, ones_based=False, zero_pad=0): """ converts a string like "-2,4,10-13,20-" into a list of indicies [1,2,10,11,12,13,20,21,22...] if string is None or 'all', will return the complete list of indicies (0 to list_len-1) on...
def get_single_col_by_input_type(input_type, column_definition): """Returns name of single column. Args: input_type: Input type of column to extract column_definition: Column definition list for experiment """ cols = [tup[0] for tup in column_definition if tup[2] == input_type] if len(cols...
def get_sequences(sequence, min_seq_len=1): """ Transforms the output of get_repeat_counts() into distinct "sequences" and "repeats". Sequences are runs of data that do not contain any repetition inside them. ! This is adjustable using min_seq_len: repeats in the input that are shorter than th...
def extract_submittable_jobs(waiting): """Returns a list of jobs from pending list that can be submitted :param waiting: List of Job objects """ submittable = set() # Holds jobs that are able to be submitted # Loop over each job, and check all the subjobs in that job's dependency # list. If t...
def _fix_ie_filename(filename): """Internet Explorer 6 transmits the full file name if a file is uploaded. This function strips the full path if it thinks the filename is Windows-like absolute. """ if filename[1:3] == ':\\' or filename[:2] == '\\\\': return filename.split('\\')[-1] retu...
def summary_ranges(array): """ :type array: List[int] :rtype: List[] """ res = [] if len(array) == 1: return [str(array[0])] i = 0 while i < len(array): num = array[i] while i + 1 < len(array) and array[i + 1] - array[i] == 1: i += 1 if array[i...
def parse_paranthetical(paran): """ :param: A paranthetical-string is a comma-delimited list of barewords: (foo,bar) :return: A list of barewords """ if paran is None: return [] return [s.strip().lower() for s in paran[1:-1].split(",")]
def dequote(string): """Remove quotes from around a string.""" if ((string.startswith('"') and string.endswith('"')) or (string.startswith("'") and string.endswith("'"))): return string[1:-1] else: return string
def snake_to_capitalized_words(snake_case: str) -> str: """Converts a snake_case or SNAKE_CASE string to Capitalized Words format. Parameters ---------- snake_case : :class:`str` The snake_case string. Returns ------- :class:`str` The resulting Capitalized Words string. ...
def is_device_report(doc): """exclude device reports""" device_report_xmlns = "http://code.javarosa.org/devicereport" def _from_form_dict(doc): return "@xmlns" in doc and doc["@xmlns"] == device_report_xmlns def _from_xform_instance(doc): return "xmlns" in doc and doc["xmlns"] == device_...
def getModuleName(prefix, cnt): """ adds unique number to prevent name collisions""" return prefix + "%" + str(cnt)
def generate_airflow_spec(tasks, args, target_image): """ Generates a dictionary with the spec used by Airflow to construct the DAG """ dag_dict = dict(tasks=[], image=target_image) for name, upstream in tasks.items(): command = f'ploomber task {name}' if args: comm...
def getRemainingFiles(movedFileList, allFiles): """ Make a diff between the moved files and all files """ # loop over all entries and remove those that are in the movedFileList for file in movedFileList: for i in range(len(allFiles)): if file == allFiles[i]: del allFiles...
def merge_lsofs(lsof15, lsof25): """ Checks if lists of shots for C15 and C25 collimators makes sense Parameters ---------- lsof15: array of strings list of C15 shots lsof25: array of strings list of C25 shots returns: array of strings Merged list of shots with in...
def valid_password(password): """Returns whether `password` is a valid password""" if password is None: # SQLite integrity check return False if len(password) < 8: # Arbitrary length minimum return False return True
def _unescape_key(string): """ Unescape '__type' and '__meta' keys if they occur. """ if string.startswith("__") and string.lstrip("_") in ("type", "meta"): return string[1:] return string
def get_agg_funcs(func): """Helper method used to create a mapping of the aggregation functions with their columns. Parameters ---------- functions: dict of str:Callable or Callable Single Callable that aggregates on the entire df or a dict of callables where the keys are column names a...
def calculate_costs(minutes, hourly_rate): """ Returns the costs for a task based on time and hourly rate. Usage:: {{ item.time|calculate_costs:HOURLY_RATE }} """ return round(float(minutes) / 60 * hourly_rate, 2)
def help_get_funargs(func): """ Extract Docstring : (a, b, x='blah') """ import inspect try: ll = str( inspect.signature(func) ) ll = ll[1:-1] ll = [ t.strip() for t in ll.split(", ")] except : ll = "" return ll
def _format_paths(paths, indent_level=1): """Format paths for inclusion in a script.""" separator = ',\n' + indent_level * ' ' return separator.join(paths)
def generateState(start, diff, stateSize, stateName): """Generates a dict that contains a stateName and a list of values.""" values = [] increment = float(1) / stateSize for iteration in range(int(stateSize)): # Get a value between start + diff sample = start + diff * increment * i...
def masks(N): """ all masks, i.e. lists of zeros and ones only, of length N """ seqs = [ [] ] for i in range(N): new_seqs = [ ] for s in seqs: new_seqs += [ [0] + s, [1] + s ] seqs = new_seqs return seqs
def currency(amount): """ Returns the dollar amount in US currency format. """ if amount >= 0: return '${:,.2f}'.format(amount) else: return '-${:,.2f}'.format(-amount)
def check_and_get(data): """ Used to set empty value to JSON if key doesnt exist in API :param data: :return: """ if data != None: return data else: return ""
def height_from_height_buttocks(segment_length): """ Calculates body height based on the height of the buttocks from the ground args: segment_length (float): height of the buttocks Returns: float: total body height """ if segment_length <= 0: raise ValueError('segment_l...
def format_g09_geometry(_arguments, _g09_raw_geometry): """Function to format g09 geometry Arguments: _arguments {obj} -- arguments given by user _g09_raw_geometry {list} -- chosen geometry read from g09 log file Returns: list:geometry -- formatted geometry with splitted attributes...
def is_prime_v1(n): """Return "True" if "n" is a prime number. False otherwise.""" if n == 1: return False for d in range(2, n): if n % d == 0: return False return True
def _chebval(x, c): """ Evaluate a Chebyshev series at points x. This is just a lightly modified copy/paste job from the numpy implementation of the same function, copied over here to put a jit wrapper around it. """ if len(c) == 1: c0 = c[0] c1 = 0 elif len(c) == 2: ...
def has_doi_prefix(v, prefix="10.1234"): """ Returns False, if we cannot parse v or prefix does not match. """ if not v: return False return v.split("/")[0] == prefix
def ler_conf(arquivo): """ Le o arquivo de configuracao e devolve um mapa {PARAMETRO:VALOR}com os parametros lidos """ param = {} linha = 1 with open(arquivo,'r') as f: for l in f: if l.isspace() or l.startswith("#"): ...
def clean_uris(url): """Clean uris.""" url = url.replace('http://', '').replace('https://', '') uris = url.split('/', 3) if len(uris) <= 1: return uris elif len(uris) == 2: return [uris[0], '/'.join([uris[0], uris[1]])] else: return [uris[0], '/'.join([uris[0], uris[1]]),...
def NearZero(z): """ Determines whether a scalar is small enough to be treated as zero :param z: A scalar input to check :return: True if z is close to zero, false otherwise Example Input: z = -1e-7 Output: True """ return abs(z) < 1e-6
def hamming_distance(s1, s2): """Calculate the Hamming distance between two strings of equal lengths. Raise ValueError if strings are of unequal length. """ if len(s1) != len(s2): raise ValueError('strings of unequal length') return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
def create_quotas(n, sum_q): """Returns evenly distributed quotas. Args: n: The number of agents. sum_q: The sum of quotas to distribute. Returns: Evenly distributed upper and lower quotas. """ quotas = [] quotient = int(sum_q / n) remainder = int(sum_q % n) f...
def apply_substitutions(contents, subs): """Apply the provided set of `subs` to `contents`, replacing any occurrences of each KEY with each VALUE. Args: contents: Contents of the file which we should replace within. subs: Map of substitutions to apply. Returns: Rendered file re...
def get_snapshot(module, array): """Return Snapshot or None""" try: snapname = module.params['name'] + "." + module.params['suffix'] for s in array.get_volume(module.params['name'], snap='true'): if s['name'] == snapname: return snapname except: return Non...
def getOptionalAttrib(node, attribName, typeFn=None, default=None): """Get an optional attrib, or default if not set or node is None """ if node != None and attribName in node.attrib: if typeFn != None: if typeFn == bool: aname = node.attrib[attribName].lower() ...
def is_test_filename(filename): """Checks if the file is a test file. Args: filename (str): The name of a source file. Returns: bool: Boolean indicating if ``filename`` is a test file. """ return 'test' in filename
def prune_json(json_dict): """ Method that given a JSON object, removes all its empty fields. This method simplifies the resultant JSON. :param json_dict input JSON file to prune :return JSON file removing empty values """ final_dict = {} if not (isinstance(json_dict, dict)): # E...
def bounds_elementwise(lst): """Given a non-empty list, returns (mins, maxes) each of which is the same length as the list items. >>> bounds_elementwise([[0,6,0], [5,0,7]]) ([0,0,0], [5,6,7]) """ indices = list(range(len(lst[0]))) mins = [min(el[i] for el in lst) for i in indices] maxes...
def get_card_name(number): """Get card name""" card_names = ( "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace", ) return card_names[number]
def calc_f1(precision: float, recall: float): """Calculates the F1 score Args: precision (float): The calculated precision recall (float): The calculated recall Returns: float: The F1 score """ if precision + recall == 0: return 0 return 2 * ((precision * r...
def c2js(plural): """Gets a C expression as used in PO files for plural forms and returns a JavaScript function that implements an equivalent expression. """ if len(plural) > 1000: raise ValueError('plural form expression is too long') return "function(n) { return (" + plural + "); }"