content
stringlengths
42
6.51k
def has_async_fn(fn): """Returns true if fn can be called asynchronously.""" return hasattr(fn, "async") or hasattr(fn, "asynq")
def str2list_row(row): """ convert str to list in a row. """ row = row.strip('\n') # delete '\n'. row = row.strip('\r') # delete '\r'. row = row.split(',') return row
def get_target_delta(data_size: int) -> float: """Generate target delta given the size of a dataset. Delta should be less than the inverse of the datasize. Parameters ---------- data_size : int The size of the dataset. Returns ------- float The target delta value. """ den = 1 while data_size // den >= 1: den *= 10 return 1 / den
def normalize_params(text:str) -> list: """ need to create standard function to normalize parametrs But first need to understand what params there could be """ result = list() # for default value list of one 0 will be returned result.append('0') if ' ' in text: if '/' in text: params = text.split(' ')[1:] for param in params: pass # stoped creating here cause of different possible value types... result = params elif "_" in text: params = text.split('_')[1:] result = params return result
def getCanonicalSvnPath(path): """Returns the supplied svn repo path *without* the trailing / character. Some pysvn methods raise exceptions if svn directory URLs end with a trailing / ("non-canonical form") and some do not. Go figure... """ if path and path.endswith('/'): path = path[:-1] return path
def isfastq(f, verbose=False): """ Simple check for fastq file """ if 'fq' in f or 'fastq' in f: return True return False
def _str_to_bool(s): """Convert string to bool (in argparse context).""" if s.lower() not in ['true', 'false']: raise ValueError('Need bool; got %r' % s) return {'true': True, 'false': False}[s.lower()]
def create_INFO_dict(INFO): """return a dict of values from the INFO field of a VCF """ d = {} for entry in INFO.split(";"): if "=" in entry: variable, value = entry.split("=", 1) d[variable] = value return d
def first(obj): """ return first element from object (also consumes it if obj is an iterator) """ return next(iter(obj))
def is_config_file(filename, extensions=[".yml", ".yaml", ".json"]): """ Return True if file has a valid config file type. Parameters ---------- filename : str filename to check (e.g. ``mysession.json``). extensions : str or list filetypes to check (e.g. ``['.yaml', '.json']``). Returns ------- bool """ extensions = [extensions] if isinstance(extensions, str) else extensions return any(filename.endswith(e) for e in extensions)
def pos2wn (pos): """Take PTB POS and return wordnet POS a, v, n, r, x or None 'don't tag' z becomes z FIXME: add language as an attribute """ if pos in "CC EX IN MD POS RP VAX TO".split(): return None elif pos in "PDT DT JJ JJR JJS PRP$ WDT WP$".split(): return 'a' elif pos in "RB RBR RBS WRB".split(): return 'r' elif pos in "VB VBD VBG VBN VBP VBZ".split(): return 'v' elif pos == "UH": # or titles return 'x' elif pos == "z": # phrase return 'z' else: # CD NN NNP NNPS NNS PRP SYM WP return 'n';
def markupify(string): """ replace _ with \_ [ not need for all markup ] """ return string.replace("_","\_")
def combine_counts (counts, sample_names): """ Combine a set of count dictionaries counts is a dictorinary of count_data where key is sample name """ full_tag_list = [] num_of_samples = len(sample_names) # Generate the complete tag list (some samples won't have some tags) for sample in sample_names: full_tag_list = full_tag_list + list(counts[sample].keys()) full_tag_list = list(set(full_tag_list)) # Generate matrix zero matrix count_matrix = {} for tag in full_tag_list: count_matrix[tag] = [0]*num_of_samples # Update where count exists for sample_idx in range(num_of_samples): sample = sample_names[sample_idx] for tag in counts[sample].keys(): count_matrix[tag][sample_idx] = counts[sample][tag] return count_matrix
def u(s, encoding="utf-8"): """ bytes/int/float to str """ if isinstance(s, (str, int, float)): return str(s) if isinstance(s, bytes): return s.decode(encoding) raise TypeError("unsupported type %s of %r" % (s.__class__.__name__, s))
def get_tags(line): """Get tags out of the given line. :param str line: Feature file text line. :return: List of tags. """ if not line or not line.strip().startswith("@"): return set() return set((tag.lstrip("@") for tag in line.strip().split(" @") if len(tag) > 1))
def effective_decimals(num): """ find the first effective decimal :param float num: number :return int: number of the first effective decimals """ dec = 0 while 0. < num < 1.: dec += 1 num *= 10 return dec
def check_states(user_action, expected_action): """this function check the dialogue states of the json_object. assume both expected action and user action went through action standarlization, which means they must have a flight and name field. """ # first status needs to match status_match = expected_action['status'] == user_action['status'] # second flight need to match # if user flight is empty, expected flight has to be empty if len(user_action['flight']) == 0: flight_match = len(expected_action['flight']) == 0 else: # there can only be one user flight assert len(user_action['flight']) == 1 flight_match = user_action['flight'][0] in expected_action['flight'] a = expected_action['name'].strip().lower() b = user_action['name'].strip().lower() name_match = (a == b) res = status_match and flight_match and name_match return res, status_match, flight_match, name_match
def _contains_instance_of(seq, cl): """ :type seq: iterable :type cl: type :rtype: bool """ for e in seq: if isinstance(e, cl): return True return False
def block(name, content, converter): """ Create terraform block. Args: . name - block name. . content - block dict. . converter - schema converter function """ res ="" res += f'\n {name} ' + '{' for key, val in content.items(): res += converter(key, val) return res + '\n } '
def get_group_size_and_start(total_items, total_groups, group_id): """ Calculate group size and start index. """ base_size = total_items // total_groups rem = total_items % total_groups start = base_size * (group_id - 1) + min(group_id - 1, rem) size = base_size + 1 if group_id <= rem else base_size return (start, size)
def leading_indent(str): """Count the lead indent of a string""" if not isinstance(str, list): str = str.splitlines(True) for line in str: if line.strip(): return len(line) - len(line.lstrip()) return 0
def binary_xor(a, b): """ xor the binary numbers passed in parameters as strings Args: a -- string b -- string return a ^ b in binary """ initial_len = len(a) return bin(int(a, 2) ^ int(b, 2))[2:].zfill(initial_len)
def extract_fields(json): """Extracts a JSON dict of fields. REST and RPC protocols use different JSON keys for OpenSocial objects. This abstracts that and handles both cases. Args: json: dict The JSON object. Returns: A JSON dict of field/value pairs. """ return json.get('entry') or json
def LJ(r): """Returns the LJ energy""" return 4 * (((1 / r) ** 12) - ((1 / r) ** 6))
def _state_diff(state, previous_state): """A dict to show the new, changed and removed attributes between two states Parameters ---------- state : dict previous_state : dict Returns ------- dict with keys 'new', 'changed' and 'removed' for each of those with content """ new = {k: v for k, v in state.items() if k not in previous_state} changed = { k: {"from": previous_state[k], "to": v} for k, v in state.items() if k in previous_state and v != previous_state[k] } removed = {k: v for k, v in previous_state.items() if k not in state} diff = {"new": new, "changed": changed, "removed": removed} result = {k: v for k, v in diff.items() if len(v) > 0} return result if len(result) > 0 else None
def dns(addrs): """Formats the usage of DNS servers. Very important to define this parameter when ever running a container as Ubuntu resolves over the loopback network, and RHEL doesn't. If you don't supply this in a docker run command, than users running RHEL based Linux cannot run automation built from Ubuntu based containers. Same thing for Ubuntu OS users running RHEL based containers. :Returns: String :param addrs: A comma separated list of DNS IPs :type addrs: String """ if addrs: return [x.strip(' \n') for x in addrs.split(',')] return None
def get_uv_3(x, y): """Get the velocity field for exercise 6.1.3.""" return x*(x-y), y*(2*x-y)
def firstjulian(year): """Calculate the Julian date up until the first of the year.""" return ((146097*(year+4799))//400)-31738
def fix_kwargs(kwargs): """Return kwargs with reserved words suffixed with _.""" new_kwargs = {} for k, v in kwargs.items(): if k in ('class', 'type'): new_kwargs['{}_'.format(k)] = v else: new_kwargs[k] = v return new_kwargs
def square_of_sum(N): """Return the square of sum of natural numbers.""" return (N * (N + 1) // 2) ** 2
def box(keyword): """Validation for the ``<box>`` type used in ``background-clip`` and ``background-origin``.""" return keyword in ('border-box', 'padding-box', 'content-box')
def sentitel_strict_acc(y_true, y_pred): """ Calculate "strict Acc" of aspect detection task of Sentitel. """ total_cases=int(len(y_true)) true_cases=0 for i in range(total_cases): if y_true[i]!=y_pred[i]:continue true_cases+=1 aspect_strict_Acc = true_cases/total_cases return aspect_strict_Acc
def face_num_filter(ans): """ ans -list of (pic_url, face_num) """ return list(filter(lambda x: x[1] == 1, ans))
def less_than(val1, val2): """ Simple function that returns True if val1 <= val2 and False otherwise. :param val1: first value of interest :param val2: second value of interest :return: bool: True if val1 <= val2 and False otherwise """ if round(val1, 3) <= round(val2, 3): # only care to the 3rd position after decimal point return True else: return False
def jekyll_slugify(input: str, mode: str = "default") -> str: """Slugify a string Note that non-ascii characters are always translated to ascii ones. Args: input: The input string mode: How string is slugified Returns: The slugified string """ if input is None or mode == "none": return input from slugify import slugify # type: ignore if mode == "pretty": return slugify(input, regex_pattern=r"[^_.~!$&'()+,;=@\w]+") if mode == "raw": return slugify(input, regex_pattern=r"\s+") return slugify(input)
def less_equal(dict1: dict, dict2: dict): """equal the same key to respect the key less dict""" if len(dict1) > len(dict2): dict1, dict2 = dict2, dict1 for key in dict1.keys(): if dict1[key] != dict2[key]: return False return True
def default_dev_objective(metrics): """ Objective used for picking the best model on development sets """ if "eval_mnli/acc" in metrics: return metrics["eval_mnli/acc"] elif "eval_mnli-mm/acc" in metrics: return metrics["eval_mnli-mm/acc"] elif "eval_f1" in metrics: return metrics["eval_f1"] elif "eval_mcc" in metrics: return metrics["eval_mcc"] elif "eval_pearson" in metrics: return metrics["eval_pearson"] elif "eval_acc" in metrics: return metrics["eval_acc"] raise Exception("No metric founded for {}".format(metrics))
def list_comprehension(function, argument_list): """Apply a multivariate function to a list of arguments in a serial fashion. Uses Python's built-in list comprehension. Args: function: A callable object that accepts more than one argument argument_list: An iterable object of input argument collections Returns: List of output results Example: >>> def add(x, y, z): ... return x+y+z ... >>> list_comprehension(add, [(1, 2, 3), (10, 20, 30)]) [6, 60] References: - https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions """ result_list = [function(*args) for args in argument_list] return result_list
def listify(x): """ Example: >>> listify('a b c') ['a', 'b', 'c'] >>> listify('a, b, c') ['a', 'b', 'c'] >>> listify(3) [3] """ if isinstance(x, str): if ',' in x: return [x1.strip() for x1 in x.split(',')] else: return [x1 for x1 in x.split(' ') if x1] elif isinstance(x, list): return x elif isinstance(x, tuple) or isinstance(x, dict): return list(x) else: return [x]
def check_similar_cpds(cpds, moa_dict): """This function checks if two compounds are found in the same moa""" for x in range(len(cpds)): for y in range(x+1, len(cpds)): for kys in moa_dict: if all(i in moa_dict[kys] for i in [cpds[x], cpds[y]]): return True return False
def strip_dot_git(url: str) -> str: """Strip trailing .git""" return url[: -len(".git")] if url.endswith(".git") else url
def reciprocal_overlap(astart, aend, bstart, bend): """ creates a reciprocal overlap rule for matching two entries. Returns a method that can be used as a match operator """ ovl_start = max(astart, bstart) ovl_end = min(aend, bend) if ovl_start < ovl_end: # Otherwise, they're not overlapping ovl_pct = float(ovl_end - ovl_start) / max(aend - astart, bend - bstart) else: ovl_pct = 0 return ovl_pct
def get_parameter(kwargs, key, default=None): """ Get a specified named value for this (calling) function The parameter is searched for in kwargs :param kwargs: Parameter dictionary :param key: Key e.g. 'loop_gain' :param default: Default value :return: result """ if kwargs is None: return default; value = default; if key in kwargs.keys(): value = kwargs[key]; return value;
def header_line(name, description, head_type=None, values=None): """ A helper function to generate one header line for the capabilities() """ ret = {'name': name, 'description': description} if head_type is None: ret['type'] = 'string' else: ret['type'] = head_type if values is not None: ret['values'] = values return ret
def filter_by_lines(units, lines): """Filter units by line(s).""" return [i for i in units if i.line in lines]
def singleton(cls): """ This method is used for provide singleton object. :param cls: :return: type method """ instances = {} def get_instance(): if cls not in instances: instances[cls] = cls() return instances[cls] return get_instance()
def same_frequency(num1, num2): """Do these nums have same frequencies of digits? >>> same_frequency(551122, 221515) True >>> same_frequency(321142, 3212215) False >>> same_frequency(1212, 2211) True """ set1 = set(str(num1)) set2 = set(str(num2)) result = set1 - set2 if len(result) > 0: return False else: return True
def divisors_to_string(divs): """ Convert a list of numbers (representing the orders of cyclic groups in the factorization of a finite abelian group) to a string according to the format shown in the examples. INPUT: - ``divs`` -- a (possibly empty) list of numbers OUTPUT: a string representation of these numbers EXAMPLES:: sage: from sage.interfaces.genus2reduction import divisors_to_string sage: print(divisors_to_string([])) (1) sage: print(divisors_to_string([5])) (5) sage: print(divisors_to_string([5]*6)) (5)^6 sage: print(divisors_to_string([2,3,4])) (2)x(3)x(4) sage: print(divisors_to_string([6,2,2])) (6)x(2)^2 """ s = "" n = 0 # How many times have we seen the current divisor? for i in range(len(divs)): n += 1 if i+1 == len(divs) or divs[i+1] != divs[i]: # Next divisor is different or we are done? Print current one if s: s += "x" s += "(%s)"%divs[i] if n > 1: s += "^%s" % n n = 0 return s or "(1)"
def average(iterable): """Return the average of the values in iterable. iterable may not be empty. """ it = iterable.__iter__() try: sum = next(it) count = 1 except StopIteration: raise ValueError("empty average") for value in it: sum = sum + value count += 1 return sum/count
def calculate_ratios(x1, y1, x2, y2, width, height): """ Calculate relative object ratios in the labeled image. Args: x1: Start x coordinate. y1: Start y coordinate. x2: End x coordinate. y2: End y coordinate. width: Bounding box width. height: Bounding box height. Return: bx: Relative center x coordinate. by: Relative center y coordinate. bw: Relative box width. bh: Relative box height. """ box_width = abs(x2 - x1) box_height = abs(y2 - y1) bx = 1 - ((width - min(x1, x2) + (box_width / 2)) / width) by = 1 - ((height - min(y1, y2) + (box_height / 2)) / height) bw = box_width / width bh = box_height / height return bx, by, bw, bh
def get_vocabs(datasets): """ Args: datasets: a list of dataset objects Return: a set of all the words in the dataset """ print("Building vocab...") vocab_words = set() vocab_tags = set() for dataset in datasets: for words, tags in dataset: vocab_words.update(words) vocab_tags.update(tags) print("- done. {} tokens".format(len(vocab_words))) return vocab_words, vocab_tags
def intdiv(p, q): """ Integer divsions which rounds toward zero Examples -------- >>> intdiv(3, 2) 1 >>> intdiv(-3, 2) -1 >>> -3 // 2 -2 """ r = p // q if r < 0 and q*r != p: r += 1 return r
def contains_filepath(filepath1, filepath2): """ contains_filepath checks if file1 is contained in filepath of file2 """ return filepath2.startswith(filepath1)
def shallow_compare_dict(source_dict, destination_dict, exclude=None): """ Return a new dictionary of the different keys. The values of `destination_dict` are returned. Only the equality of the first layer of keys/values is checked. `exclude` is a list or tuple of keys to be ignored. """ difference = {} for key in destination_dict: if source_dict.get(key) != destination_dict[key]: if isinstance(exclude, (list, tuple)) and key in exclude: continue difference[key] = destination_dict[key] return difference
def format_thousands(value): """Adds thousands separator to value.""" return "{:,}".format(int(value))
def _preprocess_path(path: str) -> str: """ Preprocesses the path, i.e., it makes sure there's no tailing '/' or '\' :param path: The path as passed by the user :return: The path of the folder on which the model will be stored """ if path.endswith("/") or path.endswith("\\"): path = path[: len(path) - 1] return path
def get_bitfinex_candle_url(url: str, pagination_id: int): """Get Bitfinex candle URL.""" if pagination_id: url += f"&end={pagination_id}" return url
def ucfirst(word): """ Capitialize the first letter of the string given :param word: String to capitalize :type word: str :return: Capitalized string :rtype: str """ return word.upper() if len(word) == 1 else word[0].upper() + word[1:] if word else word
def add_log(log, theta, logl, pseudo): """ function to append thata and ll value to the logs """ log['logl'].append(logl) if pseudo: log['pseudo_data'].append('#FF4949') else: log['pseudo_data'].append('#4970FF') for parameters in theta: log[parameters].append(theta[parameters]) return log
def binary_search(nums, key): """Returns the index of key in the list if found, -1 otherwise. List must be sorted.""" left = 0 right = len(nums) - 1 while left <= right: middle = (left + right) // 2 if nums[middle] == key: return middle elif nums[middle] > key: #Checking the left side right = middle - 1 elif nums[middle] < key: #Checking the right side left = middle + 1 return -1
def string_to_ascii_html(string: str) -> str: """Convert unicode chars of str to HTML entities if chars are not ASCII.""" html = [] for c in string: cord = ord(c) if 31 < cord < 127: html.append(c) else: html.append('&#{};'.format(cord)) return ''.join(html)
def phys2dig(signal, dmin, dmax, pmin, pmax): """ converts physical values to digital values Parameters ---------- signal : np.ndarray or int A numpy array with int values (digital values) or an int. dmin : int digital minimum value of the edf file (eg -2048). dmax : int digital maximum value of the edf file (eg 2048). pmin : float physical maximum value of the edf file (eg -200.0). pmax : float physical maximum value of the edf file (eg 200.0). Returns ------- digital : np.ndarray or int converted digital values """ m = (pmax-pmin) / (dmax-dmin) b = pmax / m - dmax digital = signal/m - b return digital
def get_overtime(hour_out, check_out): """menghitung lembur pegawai""" if check_out > hour_out: result = check_out - hour_out else: result = ' ' return result
def get_length(input_data): """ Obtain the number of elements in each dataset Parameters ---------- input_data : list Parsed dataset of genes Returns ------- length : list the length of each dataset """ length = [] for data in input_data.values(): length.append(len(data)) return length
def iff( a, b, c ): """ Ternary shortcut """ if a: return b else: return c
def list_elongation(lst, length, value=None): """Append value to lst as long as length is not reached, return lst.""" for i in range(len(lst), length): lst.append(value) return lst
def fibList(n): """[summary] This algorithm computes the n-th fibbonacci number very quick. approximate O(n) The algorithm use dynamic programming. Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be a positive integer' listResults = [0, 1] for i in range(2, n+1): listResults.append(listResults[i-1] + listResults[i-2]) return listResults[n]
def cf_or(a, b): """The OR of two certainty factors.""" if a > 0 and b > 0: return a + b - a * b elif a < 0 and b < 0: return a + b + a * b else: return (a + b) / (1 - min(abs(a), abs(b)))
def _clean_html(html): """Returns the py3Dmol.view._make_html with 100% height and width""" start = html.find("width:") end = html.find('px">') + 2 size_str = html[start:end] html = html.replace(size_str, "width: 100%; height: 100%") return html
def is_tandem_repeat(start, stop, unitlength, sequence): """ :param start: the start (inclusive) of a tandem repeat sequence :param stop: the stop (exclusive) of a tandem repeat sequence :param unitlength: the unit length of the repeat sequence :param sequence: the sequence to which the coordinates refer :return: boolean True or False if the tandem repeat is in the sequence. """ subseq = sequence[start:stop] first_unit = subseq[:unitlength] subseq = subseq[unitlength:] while subseq: thisunit = subseq[:unitlength] subseq = subseq[unitlength:] if not first_unit.startswith(thisunit): return False return True
def get_axis_num_from_str(axes_string): """ u,v,w correspond to 0,1,2 in the trailing axis of adcpy velocity arrays. This method returns a list of 0,1, and 2s corresponding to an input string composed u,v, and ws. Inputs: axes_string = string composed of u v or w only [str] Returns: ax_list = python list containing the integers 0,1, or 2 """ if type(axes_string) is not str: ValueError("axes_string argument must be a string") raise ax_list = [] for char in axes_string: if char in 'UVW': char = char.lower() if char not in 'uvw': ValueError("axes_string letters must be u,v, or w only") raise if char == 'u': ax_list.append(0) elif char == 'v': ax_list.append(1) elif char == 'w': ax_list.append(2) return ax_list
def one_bounce(a1, x0, xp0, x1, z1, z2): """ Calculates the x position of the beam after bouncing off one flat mirror. Parameters ---------- a1 : float Pitch of first mirror in radians x0 : float x position of the source in meters xp0 : float Pitch of source in radians x1 : float x position of the first mirror in meters z1 : float z position of the first mirror in meters z2 : float z position of the imager """ result = -2*a1*z1 + 2*a1*z2 - z2*xp0 + 2*x1 - x0 return result
def busquedaBinaria(numero, lista): """ Esta busqueda no me devuelve la posisicion en el array original pero me devuelve un entero positivo si es que el valor se encuentra y -1 caso contrario """ listaTemp = lista medio = len(lista) while medio >0: n = len(listaTemp) medio = n//2 if listaTemp[medio] == numero: return medio elif listaTemp[medio]> numero: listaTemp = listaTemp[0:medio] continue else: listaTemp = listaTemp[medio:n] continue return -1
def get_method_acronym(method): """Gets pretty acronym for specified ResponseGraphUCB method.""" if method == 'uniform-exhaustive': return r'$\mathcal{S}$: UE' elif method == 'uniform': return r'$\mathcal{S}$: U' elif method == 'valence-weighted': return r'$\mathcal{S}$: VW' elif method == 'count-weighted': return r'$\mathcal{S}$: CW' elif method == 'ucb-standard': return r'$\mathcal{C}(\delta)$: UCB' elif method == 'ucb-standard-relaxed': return r'$\mathcal{C}(\delta)$: R-UCB' elif method == 'clopper-pearson-ucb': return r'$\mathcal{C}(\delta)$: CP-UCB' elif method == 'clopper-pearson-ucb-relaxed': return r'$\mathcal{C}(\delta)$: R-CP-UCB' elif method == 'fixedbudget-uniform': return r'$\mathcal{S}$: U, $\mathcal{C}(\delta)$: FB' else: raise ValueError('Unknown sampler method: {}!'.format(method))
def coor_to_int(coor): """ Convert the latitude/longitute from float to integer by multiplying to 1e6, then rounding off """ return round(coor * 1000000)
def hex_to_rgb(rgb_string): """ Takes #112233 and returns the RGB values in decimal """ if rgb_string.startswith("#"): rgb_string = rgb_string[1:] red = int(rgb_string[0:2], 16) green = int(rgb_string[2:4], 16) blue = int(rgb_string[4:6], 16) return (red, green, blue)
def smart_repr(obj, object_list=None, depth=1): """Return a repr of the object, using the object's __repr__ method. Be smart and pass the depth value if and only if it's accepted. """ # If this object's `__repr__` method has a `__code__` object *and* # the function signature contains `object_list` and `depth`, then # include the object list. # Otherwise, just call the stock repr. if hasattr(obj.__repr__, '__code__'): if all([x in obj.__repr__.__code__.co_varnames for x in ('object_list', 'depth')]): return obj.__repr__(object_list=object_list, depth=depth) return repr(obj)
def get_p2p_ssqr_diff_over_var(model): """ Get sum of squared differences of consecutive values as a fraction of the variance of the data. """ return model['ssqr_diff_over_var']
def con_str(strarr, k): """.""" n = len(strarr) res = "" if n == 0 or k > n or k <= 0: return "" for el in strarr: if len(el) > len(res): res = el for idx, el in enumerate(strarr): if el == res: if len(strarr[idx:idx + k]) > len(strarr[:k - idx]): return ''.join(strarr[idx: idx + k]) else: return ''.join(strarr[:idx - k])
def divide(a,b): """THIS IS A DOC STRING THAT ONLY SHOWS WHEN USING HELP COMMAND""" if type(a) is int and type(b) is int: return a/b return "A and B must be ints!"
def derive_tenant(url): """Derive tenant ID from host We consider the standard `subdomain.domain.com` structure to be the `tenant_id`. There might be multiple applications that are hosted for the subdomain, and they may have additional application identifiers at the beginning, like 'customers.subdomain.domain.com' or 'backoffice.subdomain.domain.com'. In all such cases, we still consider the 3 part structure, `subdomain.domain.com`, to be the `tenant_id`. """ from urllib.parse import urlparse host = urlparse(url).hostname return host
def validate_form(form, required): """funkcija ki sprejme formo in vsebine, ki ne smejo biti prazne (required)""" messages = [] for vsebina in required: value = form.get(vsebina) if value is "" or value is None: messages.append("%s" % vsebina) return messages
def answer_check(n:int, table_number:str, target_number:str, H:int, B:int) -> bool: """ answer check. """ check_H, check_B = 0, 0 for col in range(0, n): if target_number[col] == table_number[col]: check_H += 1 if check_H != H: return False for i in range(0, n): for j in range(0, n): if i != j and target_number[i] == table_number[j]: check_B += 1 if check_B != B: return False return True
def disease_related(row): """ Determine whether the cause of death was disease related or not from the value for Last Known Vital Status """ last_vital = row.get("Last Known Vital Status", "Unknown") or "Unknown" if "deceased by disease" in last_vital.lower(): ret = True elif "unknown" in last_vital.lower(): ret = False else: ret = None return ret
def coverage(a1,b1,a2,b2):#{{{ """ return the coverage of two intervals a1, b1, a2, b2 are integers when the return value <=0, it means there is no coverage """ return (min(b1,b2)-max(a1,a2))
def eh_peca(peca): """ Reconhece peca. :param peca: universal :return: bool Recebe um argumento de qualquer tipo e devolve True se o seu argumento corresponde a uma peca e False caso contrario. """ return peca in ("X", "O", " ")
def _get_frames(d, cross = False, mask = None): """gets two frames (or one frame and NoneType) from dual (or single) frame data""" if cross == True: x1,x2 = d if mask is not None: x1,x2 = x1[mask],x2[mask] else: if len(d) == 1 and isinstance(d, tuple): x1, = d else: x1 = d if mask is not None: x1 = x1[mask] x2 = None return x1, x2
def parseLineForExpression(line): """Return parsed SPDX expression if tag found in line, or None otherwise.""" p = line.partition("SPDX-License-Identifier:") if p[2] == "": return None # strip away trailing comment marks and whitespace, if any expression = p[2].strip() expression = expression.rstrip("/*") expression = expression.strip() return expression
def in_circle(x, y, a=0, b=0, r=25): """Check if 2D coordinates are within a circle Optional arguments offset the circle's centre and specify radius returns True if x,y is in circle of position a,b and radius r """ return (x - a)*(x - a) + (y - b)*(y - b) < r**2
def convert_int_to_rgb_string(rgb_int): """ This function converts a RGB-Int value to a Standard RGB-String The Alpha Value is fixed. :param rgb_int: the RGB-Value as Integer :return: Standard RGB-Values as String """ red = rgb_int & 255 green = (rgb_int >> 8) & 255 blue = (rgb_int >> 16) & 255 result = "{},{},{},255".format(str(red), str(green), str(blue)) try: return result except (ValueError, Exception): return "255, 255, 255, 255"
def integers(sequence_of_sequences): """ Returns a new list that contains all the integers in the subsequences of the given sequence, in the order that they appear in the subsequences. For example, if the argument is: [(3, 1, 4), (10, 'hi', 10), [1, 2.5, 3, 4], 'hello', [], ['oops'], [[55], [44]], [30, -4] ] then this function returns: [3, 1, 4, 10, 10, 1, 3, 4, 30, -4] Type hints: :type sequence_of_sequences: (list|tuple) of (list|tuple|string) :rtype: list of int """ # ------------------------------------------------------------------------- # DONE: 3. Implement and test this function. # Note that you should write its TEST function first (above). # ------------------------------------------------------------------------- ########################################################################### # HINT: The # type # function can be used to determine the type of # its argument (and hence to see if it is an integer). # For example, you can write expressions like: # -- if type(34) is int: ... # -- if type(4.6) is float: ... # -- if type('three') is str: ... # -- if type([1, 2, 3]) is list: ... # Note that the returned values do NOT have quotes. # Also, the is operator tests for equality (like ==) # but is more appropriate than == in this situation. # ------------------------------------------------------------------------- ########################################################################### # ------------------------------------------------------------------------- # DIFFICULTY AND TIME RATINGS (see top of this file for explanation) # DIFFICULTY: 6 # TIME ESTIMATE: 10 minutes. # ------------------------------------------------------------------------- s = [] for k in range(len(sequence_of_sequences)): for j in range(len(sequence_of_sequences[k])): if type(sequence_of_sequences[k][j]) == int: s = s + [sequence_of_sequences[k][j]] return s
def _swap_bytes(data): """swaps bytes for 16 bit, leaves remaining trailing bytes alone""" a, b = data[1::2], data[::2] data = bytearray().join(bytearray(x) for x in zip(a, b)) if len(b) > len(a): data += b[-1:] return bytes(data)
def _parse_dimensions(metric_name): """ Parse out existing dimensions from the metric name """ try: metric_name, dims = metric_name.split("|", 1) except ValueError: dims = "" return ( metric_name, dict(dim_pair.split("=") for dim_pair in dims.split(",") if dim_pair), )
def quick_sort(alist): """Implement a sorted in order by value list.""" if len(alist) < 2: return alist if len(alist) == 2: if alist[0] > alist[1]: alist[0], alist[1] = alist[1], alist[0] return alist pivot = alist[0] less = [] greater = [] for num in alist: if num < pivot: less.append(num) if num > pivot: greater.append(num) return quick_sort(less) + [pivot] + quick_sort(greater)
def _create_name_mapping(all_nodes): """ helper function to creates the name of the nodes within a GraphPipeline model - if no ambiguities, name of node will be name of model - otherwise, name of node will be '%s_%s' % (name_of_step,name_of_model) Parameters ---------- all_nodes : list of 2-uple nodes of graph : (step_name, model_name) Returns ------- dictionnary with key = node, and value : string corresponding to the node """ count_by_model_name = dict() mapping = {} done = set() for step_name, model_name in all_nodes: if (step_name, model_name) in done: raise ValueError("I have a duplicate node %s" % str((step_name, model_name))) done.add((step_name, model_name)) count_by_model_name[model_name[1]] = count_by_model_name.get(model_name[1], 0) + 1 for step_name, model_name in all_nodes: if count_by_model_name[model_name[1]] > 1: mapping[(step_name, model_name)] = "%s_%s" % (model_name[0], model_name[1]) else: mapping[(step_name, model_name)] = model_name[1] count_by_name = dict() for k, v in mapping.items(): count_by_name[k] = count_by_model_name.get(k, 0) + 1 for k, v in count_by_name.items(): if v > 1: raise ValueError("I have duplicate name for node %s" % str(k)) return mapping
def add_quotes_to_strings(strings): """ Add double quotes strings in a list then join with commas. Args: strings (list(str)): List of strings to add parentheses to. Returns: str: The strings with quotes added and joined with commas. """ quote_strings = [] for _string in strings: quote_strings.append("\"{string}\"".format(string=_string)) pretty_strings = ", ".join(quote_strings) return pretty_strings
def get_metricx_list(type, features): """ Function: get_metricx_list Description: Return an instance of a MetricX for each feature name on a list. Input: - type,class: The MetricX object to instance. - features,list: List of feature names. Output: List of MetricX objects, one per feature. """ return [ type(None, feature = f) for f in features ]
def get_currency_from_checkout(currency): """Convert Checkout's currency format to Saleor's currency format. Checkout's currency is using lowercase while Saleor is using uppercase. """ return currency.upper()
def slice_to_range(sl: slice, n): """ Turn a slice into a range :param sl: slice object :param n: total number of items :return: range object, if the slice is not supported an exception is raised """ if sl.start is None and sl.step is None and sl.start is None: # (:) return range(n) elif sl.start is not None and sl.step is None and sl.start is None: # (a:) return range(sl.start, n) elif sl.start is not None and sl.step is not None and sl.start is None: # (?) raise Exception('Invalid slice') elif sl.start is not None and sl.step is None and sl.start is not None: # (a:b) return range(sl.start, sl.stop) elif sl.start is not None and sl.step is not None and sl.start is not None: # (a:s:b) return range(sl.start, sl.stop, sl.step) elif sl.start is None and sl.step is None and sl.start is not None: # (:b) return range(sl.stop) else: raise Exception('Invalid slice')
def overlap1(a0, a1, b0, b1): """Check if two 1-based intervals overlap.""" return int(a0) <= int(b1) and int(a1) >= int(b0)