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 = (up_bound - lower_bound) / (2 ** length - 1) code_dec = int(code, 2) solution = lower_bound + precision * code_dec elif mode == 'real': solution = code else: raise ValueError("Unkonw code mode.") return solution
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() for mem in members_in: mem2 = mem.replace("r1i", "r01i").replace("r2i", "r02i").replace("r3i", "r03i").replace("r4i", "r04i") mem2 = mem2.replace("r5i", "r05i").replace("r6i", "r06i").replace("r7i", "r07i").replace("r8i", "r08i") mem2 = mem2.replace("r9i", "r09i") mem2 = mem2.replace("i1p", "i01p").replace("i2p", "i02p").replace("i3p", "i03p").replace("i4p", "i04p") mem2 = mem2.replace("i5p", "i05p").replace("i6p", "i06p").replace("i7p", "i07p").replace("i8p", "i08p") mem2 = mem2.replace("i9p", "i09p") if "f" in mem2: mem2 = mem2.replace("p1f", "p01f").replace("p2f", "p02f").replace("p3f", "p03f").replace("p4f", "p04f") mem2 = mem2.replace("p5f", "p05f").replace("p6f", "p06f").replace("p7f", "p07f").replace("p8f", "p08f") mem2 = mem2.replace("p9f", "p09f") mem2 = mem2.replace("f1", "f01").replace("f2", "f02").replace("f3", "f03").replace("f4", "f04") mem2 = mem2.replace("f5", "f05").replace("f6", "f06").replace("f7", "f07").replace("f8", "f08") mem2 = mem2.replace("f9", "f09") else: mem2 = mem2.replace("p1", "p01").replace("p2", "p02").replace("p3", "p03").replace("p4", "p04") mem2 = mem2.replace("p5", "p05").replace("p6", "p06").replace("p7", "p07").replace("p8", "p08") mem2 = mem2.replace("p9", "p09") members_tmp.append(mem2) members_tmp = sorted(list(set(members_tmp)), key=lambda v: v.upper()) members_out = list() for mem in members_tmp: mem2 = mem.replace("r0", "r").replace("i0", "i").replace("p0", "p").replace("f0", "f") members_out.append(mem2) return members_out
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(' ', '\u00b7') # Small right triangle text = text.replace('\t', '\u25b8') # Downwards arrow with corner leftwards text = text.replace('\n', '\u21b5') return text
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() tmp_dict = dict(zip(strs, list(range(len(strs))))) return tmp_dict[value]
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 for i in range(n_bytes): byte_array[i] = allowed[j] j += 1 if j > 126: j = 0 return bytes(byte_array)
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 n in nums: if n < 1 or n > 100: raise ValueError("Outside bounds of 1-100") return sum(nums) / len(nums)
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): if numbercontained[value]: return False else: numbercontained[value] = True row_num += 1 return True
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 = signs[charge_str[0]] if len(charge_str) > 1 and charge_str[1].isdigit(): charge = sign * int(charge_str[1:]) else: charge = sign * charge_str.count(charge_str[0]) return charge
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 -> Fail Fail & Not Executed -> Fail Fail & In Progress -> Fail Fail & Pass -> Fail Pass & Not Executed -> In Progress Pass & In Progress -> In Progress In Progress & Not Executed -> In Progress """ # map representing status as binary/hex number to be used with & operator status_map = { "Not Executed": 0xB, # 1011 "Pass": 0x7, # 0111 "In Progress": 0x3, # 0011 "Blocked": 0x1, # 0001 "Fail": 0x0 # 0000 } if not step_results: return "Not Executed" status = 0xF for result in step_results: status = status & status_map[result["status"]] return [k for k, v in status_map.items() if v == status][0]
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) == 0: return max_item max_count = -1 repeated_items = {} for item in given_list: if item in repeated_items: repeated_items[item] += 1 else: repeated_items[item] = 1 if repeated_items[item] > max_count: max_count = repeated_items[item] max_item = item print(max_item) return max_item
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 = False return melted
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' """ return S ^ (1 << j)
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 values (with the same dimensions as pval). """ return (pval - pmin) / (pmax - pmin)
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 in range(n-4)]) for j in range(1,n+1): x = 0 for i in range(1,j+1): if x < (h[i] + r[j-i]): x = (h[i] + r[j-i]) s[j] = i r[j] = x i = n lst.append(r[n]) # Maxmimal revenue while i > 0: lst.append(s[i]) i -= s[i] return lst
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, there are lots of ways you could be # importing the vendored modules that wouldn't be caught this way, but: # # 1. Doing it in a complete foolproof way is incredibly complicated, and # I don't care that much. # 2. If you're writing your Lambda code in a deliberately obfuscated way, # you have bigger problems than vendor deprecations. # # In practice, Python imports are usually near the top of the file, so we # read it line-by-line. This means if we find an import, we can skip # reading the rest of the file. # with open(python_path, "rb") as python_src: for line in python_src: if ( b"import botocore.vendored" in line or b"from botocore.vendored import " in line ): return True return False
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 for Returns: - position(int): reuturns array index for the given number returns -1 when the number was not found """ for index, element in enumerate(input_list): if element == number: return index return -1
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 :return: training optimization failed message :rtype: dict """ return { 'CorrelationId': body['CorrelationId'], 'Id': body['Id'], 'UserId': body['UserId'], 'Message': error }
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 one entry per tool revision. :type tools_info: list of dicts :param tools_info: Each dict in this list should contain info about a tool. :rtype: list of dicts :return: Return a list of dicts that correspond to the input argument such that if an input element contained `revisions` key with multiple values, those will be returned as separate list items. """ def _copy_dict(d): """ Iterrate through the dictionary `d` and copy its keys and values excluding the key `revisions`. """ new_d = {} for k, v in d.iteritems(): if k != 'revisions': new_d[k] = v return new_d flattened_list = [] for tool_info in tools_info: revisions = tool_info.get('revisions', []) if len(revisions) > 1: for revision in revisions: ti = _copy_dict(tool_info) ti['revision'] = revision flattened_list.append(ti) elif revisions: # A single revisions was defined so keep it ti = _copy_dict(tool_info) ti['revision'] = revisions[0] flattened_list.append(ti) else: # Revision was not defined at all flattened_list.append(tool_info) return flattened_list
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', 'N', 'n']: return True else: return False
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 error = ((numpy.array(estimated) - numpy.array(y))**2).sum() meanError = error/len(y) # return round(1 - (meanError/numpy.var(y)), 4) return 1 - (meanError/numpy.var(y))
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 elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs
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_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
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 < max_depth): depth += 1 queue1 = queue2 queue2 = [] for state in queue1: for s in step_fn(state, depth): if s not in states: value = eval_fn(s, depth) if value is not None: return value states.add(s) queue2.append(s) return not_found_value
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 False
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 ---------- N : array-like Raw instrument output t : array-like Temperature [degC] A-H : float Calibration parameters """ p_prime = A / (1 + D * (t - 25)) + B / ((N - F) * (1 + D * (t - 25)) + C + F) return p_prime
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: raise ValueError("Degeneracy: No orientation based on area")
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] else: return None except Exception: return None
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 client to be removed :param bank: dictionary consisting of all the bank-related data (mainly the clients' data) :return: clients' data after the intended account number has been removed from the bank """ clients_data = [] for client in bank["clients"]: clients_data.append(client) if client.get("account_number") == acc: clients_data.remove(client) return clients_data
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: break start += 1 while end >= 0: if source[end] not in whitespace: break end -= 1 return source[start:end + 1]
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]) False """ internal_num = 0 while internal_num+2 < len(nums): if (nums[internal_num] + nums[internal_num+1] + nums[internal_num+2]) %2 == 1: return True internal_num = internal_num+1 return False
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): """Build a dictionary of event counter parameters. Use provided defaults, overridden by any arguments present in the request. """ return { 'origin_latitude': request_args.get('olat', origin_latitude), 'origin_longitude': request_args.get('olon', origin_longitude), 'start_latitude': request_args.get('slat', start_latitude), 'start_longitude': request_args.get('slon', start_longitude), 'end_latitude': request_args.get('elat', end_latitude), 'end_longitude': request_args.get('elon', end_longitude), 'radius': request_args.get('r', radius), 'start_year': request_args.get('s', start_year), 'end_year': request_args.get('e', end_year), 'threshold': request_args.get('m', threshold), 'cq': request_args.get('cq', cq), }
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, None)) >>> coding_problem_08(btree)[0] 6 """ val, ln, rn = btree if ln is None and rn is None: # leaf case return 1, True, val lcount, is_uni_l, lval = coding_problem_08(ln) rcount, is_uni_r, rval = coding_problem_08(rn) is_unival = is_uni_l and is_uni_r and val == lval and val == rval count = lcount + rcount + is_unival return count, is_unival, val
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': shots/4, '0x4': shots/4, '0x5': shots/4,}) return targets
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) else: return int(val) except (ValueError, TypeError) as e: raise ValueError("Can't convert '%s' to int!" % val)
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; otherwise, a ValueError is raised. True values are strings (case-insensitive): t true y yes 1 False values are strings (case-insensitive): f false n no 0 """ s = s.lower() if s in ("t", "true", "y", "yes", "1"): return True if s in ("f", "false", "n", "no", "0"): return False if strict: raise ValueError(f"Not a valid boolean string: {s!r}") return default
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 sentence s. """ return [[map_word_id[w]] for w in s.lower().split()]
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) # 1,048,576 one_gb = float(one_kb ** 3) # 1,073,741,824 one_tb = float(one_kb ** 4) # 1,099,511,627,776 if num_bytes < one_kb: return '{0} {1}'.format(bytes, 'Bytes' if 0 == num_bytes > 1 else 'Byte') elif one_kb <= num_bytes < one_mb: return '{0:.2f} KB'.format(num_bytes / one_kb) elif one_mb <= num_bytes < one_gb: return '{0:.2f} MB'.format(num_bytes / one_mb) elif one_gb <= num_bytes < one_tb: return '{0:.2f} GB'.format(num_bytes / one_gb) else: return '{0:.2f} TB'.format(num_bytes / one_tb)
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 returned as a tuple (if `outputs` is not a list or a tuple then it is converted into a one element tuple). Otherwise (if both flags are false), `outputs` is returned. """ assert not (use_list and use_tuple), \ "Both flags cannot be simultaneously True" if (use_list or use_tuple) and not isinstance(outputs, (list, tuple)): if use_list: return [outputs] else: return (outputs,) elif not (use_list or use_tuple) and isinstance(outputs, (list, tuple)): assert len(outputs) == 1, \ "Wrong arguments. Expected a one element list" return outputs[0] elif use_list or use_tuple: if use_list: return list(outputs) else: return tuple(outputs) else: return outputs
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]) # print(list(dict_obj.keys())[:10]) return [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: year (int): The year in question Returns: bool: True if year is a leap year, false otherwise """ def is_div(x: int) -> bool: return year % x == 0 return is_div(4) and ((not is_div(100)) or is_div(400))
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 child in getattr(object,"Children",[]): t = Title(child) if t != "": return t return ""
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}'.format(int(dectod)//60) return strtod
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 -1 if clock need to shift 1 hour backward 0 does not need to adjust clock """ if m == 3: if wd == 7: if 31 >= d > 24: return 1 elif m == 10: if wd == 7: if 31 >= d > 24: return -1 else: return 0
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("-")] = "" return options
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 height % factor == 0: top = 0 bottom = 0 else: pixels = factor - height % factor top = int(pixels / 2) bottom = pixels - top if width % factor == 0: left = 0 right = 0 else: pixels = factor - width % factor left = int(pixels / 2) right = pixels - left return (top, bottom, left, right)
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): return tuple([for_each_in(cls, f, x) for x in struct]) else: if isinstance(struct, cls): return f(struct) else: return struct
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: pad_val = pad // 2 padding = (pad_val, pad_val) else: pad_val_start = pad // 2 pad_val_end = pad - pad_val_start padding = (pad_val_start, pad_val_end) return padding
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 = blobdict['BLOB']['@' + attr] except KeyError: raise KeyError('Attribute @' + attr + ' is missing from Blob.' + 'There may be some problems with your file') return 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 """ keep, remove = [], [] for info in hash_map.values(): if info[0][1] == 0: remove.extend(name for name, _ in info) else: if len(info) == 1: keep.extend(name for name, _ in info) else: first, last = info[0][0], info[-1][0] keep.extend([first, last]) remove.extend(name for name, _ in info[1:-1]) return keep, 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(' ') if last_space is -1: raise Exception("Word length exceeded line length") index = ll-last_space return paragraph[:index-1], paragraph[index:]
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_root_namespace}/{type_namespace}/{type_name}.generated.cs'
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 maps vertices to edge indices """ edges = [] vtoe = dict() for findex, f in enumerate(faces): nf = len(f) for i, v in enumerate(f): endv = f[(i + 1) % nf] edges.append(((v, endv), findex)) eindex = len(edges) - 1 if v in vtoe: vtoe[v].append(eindex) else: vtoe[v] = [eindex] return (edges, vtoe)
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. Returns: [string]: [The data after encryption or decryption] """ rtn = "" for l in info: if l.isalpha(): num=ord(l)+s if (ord(l) in range(65, 91) and num<65) or (ord(l) in range(97, 123) and num <97): num = 26 + num elif (ord(l) in range(65, 91) and num>90) or (ord(l) in range(97, 123) and num>122): num = num - 26 rtn += str(chr(num)) elif l.isnumeric(): rtn += str((int(l)+n)%10) else: rtn += str(l) return rtn
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 in config_vars: try: name, value = val.split('=', 1) except ValueError: raise ValueError("--config-var must be of the form FOO=BAR") result[name] = value return result
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', )