content
stringlengths
42
6.51k
def gameini_view(request): """Display Imager Detail.""" message = "Hello" return {'message': message}
def decode(code, lower_bound, up_bound, length, mode): """Decode a code to a valid solution. Args: code (binary or real): a single variable to decode. length (int): code length. mode (binary or real): code type, default binary. """ if mode == "binary": precision ...
def clean_post_data(post_data): """ Removes None values from data, so that it can posted to Django's test client without TypeError being raised in Django 2.2+ """ return { key: value for key, value in post_data.items() if value is not None }
def sort_members(members_in): """ Finds first member name Inputs: ------ :param members_in: list of string list of member names (e.g., "r1i1p1", "r1i1p2") Output: ------ :return members_out: list of string given list of member names sorted """ members_tmp = list...
def show_whitespace(text): """Replace whitespace characters with unicode. Args: text (str): The string to work with Returns: The text with the whitespace now visible. """ text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') # Middle dot text = text.replace(...
def helper_to_numeric_value(strs, value): """Converts string values to integers Parameters: value: string value Returns: int: converted integer """ if value is None: return None strs = [s.lower() if isinstance(s, str) else s for s in strs] value = value.lower() ...
def hinge_loss(f_x,y_true,margin=1): """ Compute the hinge loss given the returned value from a linear discrimination function on the feature x and its label y """ return max(0,margin-y_true*f_x)
def data_bytes(n_bytes): """ Generate bytes to send over the TLS connection. These bytes purposefully fall outside of the ascii range to prevent triggering "connected commands" present in some SSL clients. """ byte_array = [0] * n_bytes allowed = [i for i in range(128, 255)] j = 0 ...
def bounded_avg(nums): """ returns average of list of nums (nums must be between 1-100) >>> bounded_avg([2,4,6]) 4.0 >>> bounded_avg([10,20,30,40,50]) 30.0 >>> bounded_avg([2,4,500]) Traceback (most recent call last): ... ValueError: Outside bounds of 1-100 """ for...
def isType(val, types): """ Check if val is of a type in types. """ for a_type in types: if isinstance(val, a_type): return True return False
def convert_volts_to_amps(adc_volts): """ * f(0.5V) = -20A * f(4.5V) = 20A * f(U) = 10*U - 25 [A] """ return 10 * adc_volts - 25
def checkrows(sudoku): """ Checks if each row contains each value only once """ size = len(sudoku) row_num = 0 for row in sudoku: numbercontained = [False for x in range(size)] for value in row: # if placeholder, ignore it if value in range(size): ...
def parse_charge(charge_str): """ Parses a SMILES charge specification. Parameters ---------- charge_str : str The charge specification to parse. Returns ------- int The charge. """ if not charge_str: return 0 signs = {'-': -1, '+': 1} sign = sig...
def calc_test_result_status(step_results): """Calculate overall test result status from list of step results. According to Adaptavist test management: Blocked & Not Executed -> Blocked Blocked & In Progress -> Blocked Blocked & Pass -> Blocked Blocked & Fail...
def rmse(a,b): """calculates the root mean squared error takes two variables, a and b, and returns value """ ### Import modules import numpy as np ### Calculate RMSE rmse_stat = np.sqrt(np.mean((a - b)**2)) return rmse_stat
def _check_ascii(sstr): """ Return True iff the passed string contains only ascii chars """ return all(ord(ch) < 128 for ch in sstr)
def most_frequent(given_list): """given an array of numbers create a function that returns the number that is repeated the most Arguments: given_list {[type]} -- an array of numbers Returns: int: the number that is the most repeated """ max_item = None if len(given_list) ==...
def check_temperature(T, melting_point=3000): """ Check if an instantaneous temperature will melt the divertor. """ if T > melting_point: print("Destroyed divertor!") melted = True elif T <= 0: raise ValueError("Unphysical temperature value!") else: melted = Fal...
def toggle_bit(S, j): """ Returns a new set from set `S` with the j-th item toggled (flip the status of). Examples ======== Toggle the 2-nd item and then 3-rd item of the set >>> S = int('0b101000', base=2) >>> S = toggle_bit(S, 2) >>> S = toggle_bit(S, 3) >>> bin(S) '0b100100'...
def make_locale_path(path, lang): """returns locale url - /home/ --> /en/home/""" return '/{0}{1}'.format(lang, path)
def safe_call(func, *args, **kwargs): """Call function with provided arguments. No throw, but return (result, excepion) tuple""" try: return func(*args, **kwargs), None except Exception as ex: return None, ex
def bnorm(pval, pmax, pmin): """ Normalize parameters by the bounds of the given values. **Parameters**\n pval: array/numeric A single value/collection of values to normalize. pmax, pmin: numeric, numeric The maximum and the minimum of the values. **Return**\n Normalized va...
def p(n): """Calculates maximal revenue and its associated cuts for scarves of length n""" r = list(range(0,n+1)) # Array for revenue s = list(range(0,n+1)) # Array for cuts h = [0,2,5,6,9] # Prices r[0] = 0 lst = [] if n > 4: # h[n] = 0 for n > 4 h.extend([0 for i i...
def string_to_list(the_string): """ converts string to list of ints """ l = [] seperate_secondaries = the_string.split() for secondary in enumerate(seperate_secondaries): l.append([]) for item in secondary[1].split(',')[:-1]: l[secondary[0]].append(int(item)) return l
def twochars(arg): """ Formats a string of two characters into the format of (0X), useful for date formatting. :param arg: The string :return: String """ if len(arg) == 1: return f"0{arg}" return arg
def contains_vendored_imports(python_path): """ Returns True if ``python_path`` seems to contain vendored imports from botocore. """ # We're using a very rough heuristic here: if the source code contains # strings that look like a vendored import, we'll flag. # # Because Python is dynamic, t...
def linear_search(input_list, number): """ Find the index for a given value (number) by searching in a sorted array Time complexity: O(n) Space Complexity: O(1) Args: - input_list(array): sorted array of numbers to be searched in - number(int): number to be searched...
def training_optimization_failed(error, body): """ Method for make message as dict with data which would be send to rabbitmq if training optimization failed :param error: error readable message :param body: body of message received from RabbitMQ queue :type error: str :type body: dict :...
def _flatten_tools_info(tools_info): """ Flatten the dict containing info about what tools to install. The tool definition YAML file allows multiple revisions to be listed for the same tool. To enable simple, iterattive processing of the info in this script, flatten the `tools_info` list to include...
def is_falsy(value): """Check 'value' is Falsy or not (possible to parse into boolean). Args: value (any, required): The value to check. Returns: bool: True if 'value' is valid, False if it is not. """ if value in [False, 0, '0', '0.0', 'FALSE', 'False', 'false', 'NO', 'No', 'no',...
def records_desc(table: bool) -> str: """description records""" return 'Rows' if table else 'Features'
def r_squared(y, estimated): """ Calculate the R-squared error term. Args: y: list with length N, representing the y-coords of N sample points estimated: a list of values estimated by the regression model Returns: a float for the R-squared error term """ import numpy ...
def epoch_time(start_time, end_time): """ Calculate the time spent to train one epoch Args: start_time: (float) training start time end_time: (float) training end time Returns: (int) elapsed_mins and elapsed_sec spent for one epoch """ elapsed_time = end_time - start_time...
def upper_all(lst): """Make all elements of a list uppercase""" return [item.upper() for item in lst]
def torch_to_jax_backend(backend): """Assert correct backend naming.""" if backend == 'cuda': backend = 'gpu' return backend
def hex_to_rgb(hex_color): """Converts a HEX color to a tuple of RGB values. Parameters: hex_color (str): Input hex color string. Returns: tuple: RGB color values. """ hex_color = hex_color.lstrip("#") if len(hex_color) == 3: hex_color = hex_color * 2 return int(hex...
def bfs(initial_state, step_fn, eval_fn, max_depth=None, not_found_value=None): """Bread-first search""" queue2 = [initial_state] states = set(queue2) depth = 0 value = eval_fn(initial_state, depth) if value is not None: return value while queue2 and (max_depth is None or depth <...
def is_invalid_input(string_one, string_two): """ Checks if the first string does not consist only of characters from the second string """ for character in string_one: if character not in string_two and character != '\t': # Dealing with address formatting return True return...
def split_columns(line, separator='\t'): """ Split a line with a "separator" """ return line.split(separator)
def rinko_p_prime(N, t, A, B, C, D, E, F, G, H): """ Per RinkoIII manual: 'The film sensing the water is affect by environment temperature and pressure at the depth where it is deployed. Based on experiments, an empirical algorithm as following is used to correct data dissolved oxygen.' Parameters ...
def regular_polygon_area(perimeter, apothem): """Returns the area of a regular polygon""" area = (perimeter * apothem) / 2 return area
def bbox_vert_aligned_center(box1, box2): """ Returns true if the center of both boxes is within 5 pts """ if not (box1 and box2): return False return abs(((box1.right + box1.left) / 2.0) - ( (box2.right + box2.left) / 2.0)) <= 5
def is_ccw(signed_area): """Returns True when a ring is oriented counterclockwise This is based on the signed area: > 0 for counterclockwise = 0 for none (degenerate) < 0 for clockwise """ if signed_area > 0: return True elif signed_area < 0: return False else: ...
def _get_unique_child(xtag, eltname): """Get the unique child element under xtag with name eltname""" try: results = xtag.findall(eltname) if len(results) > 1: raise Exception("Multiple elements found where 0/1 expected") elif len(results) == 1: return results[0] ...
def phred33ToQ(quolity): """convert character to quolity score accroding to ASCII table""" return ord(quolity) - 33
def strip_non_printing(text): """Removes non-printing (including control) characters from text. (same as moses script). """ return "".join([c for c in text if c.isprintable()])
def remove_account(acc, bank): """ Removes an account from the bank Removes a client from the bank if the client has one existing account. Otherwise, only the chosen account number out of all the existing accounts of that client is removed from the bank. :param acc: intended account number of the clie...
def elimate_whitespace_around(source): """ return contents surrounded by whitespaces. whitespace :: space | tab """ if not source: return source start, length = 0, len(source) end, whitespace = length - 1, ' \t' while start < length: if source[start] not in whitespace: ...
def three_odd_numbers(nums): """Is the sum of any 3 sequential numbers odd?" >>> three_odd_numbers([1, 2, 3, 4, 5]) True >>> three_odd_numbers([0, -2, 4, 1, 9, 12, 4, 1, 0]) True >>> three_odd_numbers([5, 2, 1]) False >>> three_odd_numbers([1, 2, 3, 3, 2])...
def build_parameters(request_args, origin_latitude=None, origin_longitude=None, radius=None, start_latitude=None, start_longitude=None, end_latitude=None, end_longitude=None, start_year=None, end_year=None, threshold=None, cq=True): ...
def merge_key(key, _key, recurse=False): """ Return key as is if not to be merged Merge only the non tag part [0] """ if not recurse: return _key if len(key) > 0: return str(key) + "/" + str(_key[0]) return _key[0]
def updated(d, update): """Return a copy of the input with the 'update' Primarily for updating dictionaries """ d = d.copy() d.update(update) return d
def decode_int(v): """Decodes integer value from hex string. Helper function useful when decoding data from contracts. :param str v: Hexadecimal string :return: Decoded number :rtype: num """ if v[0:2] == '0x': return int(v.replace('0x', ''), 16) else: return int(v)
def coding_problem_08(btree): """ A unival tree (which stands for "universal value") is a tree where all nodes have the same value. Given the root to a binary tree, count the number of unival subtrees. Example: >>> btree = (0, (0, (0, None, None), (0, (0, None, None), (0, None, None))), (1, None, N...
def snapshot_amplitudes_counts(shots): """Snapshot Amplitudes test circuits reference counts.""" targets = [] # Snapshot |000> targets.append({'0x0': shots}) # Snapshot |111> targets.append({'0x7': shots}) # Snapshot 0.25*(|001>+|011>+|100>+|101>) targets.append({'0x0': shots/4, '0x1': s...
def str2int(val, base=None): """String to integer conversion""" try: if isinstance(val, int) or val is None: return val elif base: return int(val, base) elif '0x' in val: return int(val, 16) elif '0b' in val: return int(val, 2) ...
def parse_bool(s: str, default: bool = False, strict: bool = False) -> bool: """ parse_bool(s: str, default: bool = False, strict: bool = False) -> bool Parse a boolean string value. If the string is not recognized as a valid True/False string value, the default is returned if strict is False; other...
def page_not_found(e): """Return a custom 404 error.""" return '<h1>404: Not Found</h1>', 404
def v2_multimax(iterable): """Return a list of all maximum values. Using a list comphrehension """ max_item = max(iterable) return [ item for item in iterable if item == max_item ]
def remove_dups_stringlist(str): """Remove duplicates from list as string""" arr = str.split(',') arr = list(dict.fromkeys(arr)) return ','.join(arr)
def df(x, kwargs): """ Modify x using keyword arguments (dicts,kwarg). """ return x if x not in kwargs else kwargs[x]
def sentence_to_ids(s :str, map_word_id :dict): """ Computes unique indexes for each word of a sentence. Args: s: A string correpsponding to a sentence. map_word_id: An existing dict of words and corresponding indexes. Returns: The map_word_id completed with the words of the sent...
def bitmask(n: int) -> int: """Produces a bitmask of n 1s if n is positive, or n 0s if n is negative.""" if n >= 0: return (1 << n) - 1 else: return -1 << -n
def correct_comment_indentation(comment, indent): """Ensure each line of a given block of text has the correct indentation.""" result = '' for line in comment.splitlines(): result += ' ' * indent + line.lstrip() + '\n' return result
def _get_human_bytes(num_bytes): """Return the given bytes as a human friendly KB, MB, GB, or TB string thanks https://stackoverflow.com/questions/12523586/python-format-size-application-converting-b-to-kb-mb-gb-tb """ num_bytes = float(num_bytes) one_kb = float(1024) one_mb = float(one_kb ** 2)...
def is_pow2(a): """ Return True if the integer a is a power of 2 """ return a == 1 or int(bin(a)[3:], 2) == 0
def _format_as(use_list, use_tuple, outputs): """ Formats the outputs according to the flags `use_list` and `use_tuple`. If `use_list` is True, `outputs` is returned as a list (if `outputs` is not a list or a tuple then it is converted in a one element list). If `use_tuple` is True, `outputs` is ret...
def dict_to_vec(dict_obj, labmt_words): """ dict to labmt word vector for use in hedonometer :param labmt_words: ordered vector of strings for labmt :param dict_obj: dict of word2count :return: np array of labmt counts """ # return np.array([[dict_obj.get(word,0)] for word in labmt_words]) ...
def _get_missing_context(context=None): """Default the context to `jwst-operational` if `context` is None, otherwise return context unchanged. """ return "jwst-operational" if context is None else context
def is_leap_year(year: int) -> bool: """Whether or not a given year is a leap year. If year is divisible by: +------+-----------------+------+ | 4 | 100 but not 400 | 400 | +======+=================+======+ | True | False | True | +------+-----------------+------+ Args: ...
def normalize(s): """ Remove all of a string's whitespace characters and lowercase it. """ return "".join(c for c in s.lower() if not c.isspace())
def Title(object): """The name of a window component""" if getattr(object,"Title","") != "": return object.Title if getattr(object,"title","") != "": return object.title if getattr(object,"Value","") != "": return str(object.Value) if getattr(object,"Label","") != "": return object.Label for chi...
def _dec2hm(dectod=None): """Return truncated time string in hours and minutes.""" strtod = None if dectod is not None: if dectod >= 3600: # 'HH:MM' strtod = u'{0}:{1:02}'.format(int(dectod)//3600, (int(dectod)%3600)//60) else: # 'M' strtod = u'{0}'....
def daylight_saving(m, wd, d): """ Assuming that DST start at last Sunday of March DST end at last Sunday of October Input: m: month, wd: week day, d: day of month are int() type month, week day and day of month count start from 1 Output: 1 if clock need to shift 1 hour forward ...
def check_hotshot(dump): """check to hotshot-profile datafile.""" signature = "hotshot-version".encode() return True if dump.find(signature) > 0 else False
def parse_qsub_defaults(parsed): """Unpack QSUB_DEFAULTS.""" d = parsed.split() if type(parsed) == str else parsed options={} for arg in d: if "=" in arg: k,v = arg.split("=") options[k.strip("-")] = v.strip() else: options[arg.strip("-")] = "" ...
def yy2yyyy(yy): """Add '20' to timestamp. E.g. '21081812' will become '2021081812' Args: yy (string) Returns: yyyy (string) """ return f"20{yy}"
def build_message(valid_dm): """ Build notification message """ message = ''' The following domains are setup on the staging environment without the meta tag robots noindex/nofollow.\n Action is required!\n\n''' for domain in valid_dm: message += "- "+domain+"\n" return message
def regular_polygon_area(perimeter, apothem): """Returns the area of a regular polygon""" return (perimeter*apothem)/2
def tzdata_filter(line: str) -> bool: """Filter tzdata.zi file for zones""" if line and line[0] == 'Z' : return True return False
def pk_list_to_dict(pk_list): """ convert list of multi pk to dict ['id', 1, 'id2', 22, 'foo', 'bar'] -> {'foo': 'bar', 'id2': 22, 'id': 1} """ if pk_list and len(pk_list) % 2 == 0: return dict(zip(pk_list[::2], pk_list[1::2])) return None
def isnumeric(value): """Does a string value represent a number (positive or negative?) Args: value (str): A string Returns: bool: True or False """ try: float(value) return True except: return False
def cmp(a, b): """ cmp function like in python 2. """ return (a > b) - (a < b)
def vizz_params_rgb(collection): """ Visualization parameters """ dic = { 'Sentinel2': {'bands':['B4','B3','B2'], 'min':0,'max':0.3}, 'Landsat7': {'min':0,'max':0.3, 'bands':['B4','B3','B2']}, 'CroplandDataLayers': {} } return dic[collection]
def get_paddings(height, width, factor): """ Compute number of pixels to add on each side to respect factor requirement. :param height: Image height :param width: Image width :param factor: Image dimensions must be divisible by factor :return: Number of pixels to add on each side """ if...
def fibo_generate(number): """ Generate fibonnaci numbers. Arguments: number -- how many numbers to generate Returns: fibo -- a list of fibonnaci numbers. """ fibo = [1, 1] for i in range(0, number - 2): fibo.append(fibo[i] + fibo[i+1]) return fibo
def for_each_in(cls, f, struct): """ Recursively traversing all lists and tuples in struct, apply f to each element that is an instance of cls. Returns structure with f applied. """ if isinstance(struct, list): return [for_each_in(cls, f, x) for x in struct] elif isinstance(struct, tuple): ...
def parse_headers(message): """ We must parse the headers because Python's Message class hides a dictionary type object but doesn't implement all of it's methods like copy or iteritems. """ d = {} for k, v in message.items(): d[k] = v return d
def calculate_padding(input_size, kernel_size, stride): """Calculates the amount of padding to add according to Tensorflow's padding strategy.""" cond = input_size % stride if cond == 0: pad = max(kernel_size - stride, 0) else: pad = max(kernel_size - cond, 0) if pad % 2 == 0:...
def get_RB_blob_attribute(blobdict, attr): """Get Attribute `attr` from dict `blobdict` Parameters ---------- blobdict : dict Blob Description Dictionary attr : string Attribute key Returns ------- Attribute Value """ try: value = ...
def is_leap_year(year): """ Is the given year a leap year? """ if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True else: return False
def triage_hashes(hash_map): """Triage hash map in pair of names to keep and to remove in that order. Three cases: 0. size zero regardless of hash => remove 1. unique hash => keep 2. hash matching two entries => keep both 3. hash with more than two entries => keep first and last, rest remove ...
def get_next_line_from_paragraph(paragraph, ll): """Return the largest substring from `paragraph` that ends in a space and doesn't exceed `ll`. Raise exception f no such string exists. """ if paragraph[ll] is ' ': index = ll+1 else: last_space = paragraph[:ll][::-1].find(' ') ...
def make_output_path (type_name, type_root_namespace, type_namespace): """Create the output path for a generated class file. Args: type_name (str): Name of the class. type_namespace (str): The class's namespace. Returns: str: The output file path. """ return f'../{type_ro...
def ConvertMachineTypeString(machine_type): """Converts a machine type defined in the schema to a GCE compatible form.""" machine_types = { "4 vCPUs, 15 GB Memory": "n1-standard-4", "8 vCPUs, 30 GB Memory": "n1-standard-8" } return machine_types[machine_type]
def _GetEdgeData(faces): """Find edges from faces, and some lookup dictionaries. Args: faces: list of list of int - each a closed CCW polygon of vertex indices Returns: (list of ((int, int), int), dict{ int->list of int}) - list elements are ((startv, endv), face index) dict map...
def DC(info, s = 13, n = 5): """[File Encryptor/Decryptor] Args: info ([string]): [The data to be encrypted or decrypted] s (int, optional): [The decipher key to string characters in data]. Defaults to 13. n (int, optional): [The decipher key to int characters in data]. Defaults to 5. ...
def parse_config_vars(config_vars): """Convert string descriptions of config variable assignment into something that CrossEnvBuilder understands. :param config_vars: An iterable of strings in the form 'FOO=BAR' :returns: A dictionary of name:value pairs. """ result = {} for val...
def coordsToTiles(x, y, ts): """ Translates mouse coordinates to tile coordinates @type x: int @param x: x-coordinate of the mouse @type y: int @param y: y-cooridnate of the mouse @type ts: int @param ts: size of a tile in pixels """ return x // ts, y // ts
def _console_script(name): """Return the default format for a console script declaration.""" return '{name}={package}.{name}:main'.format( name=name, package='dynamicscoping', )