content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def suzuki_trotter(trotter_order, trotter_steps): """ Generate trotterization coefficients for a given number of Trotter steps. U = exp(A + B) is approximated as exp(w1*o1)exp(w2*o2)... This method returns a list [(w1, o1), (w2, o2), ... , (wm, om)] of tuples where o=0 corresponds to the A operator, o=1 corresponds to the B operator, and w is the coefficient in the exponential. For example, a second order Suzuki-Trotter approximation to exp(A + B) results in the following [(0.5/trotter_steps, 0), (1/trotteri_steps, 1), (0.5/trotter_steps, 0)] * trotter_steps. :param int trotter_order: order of Suzuki-Trotter approximation :param int trotter_steps: number of steps in the approximation :returns: List of tuples corresponding to the coefficient and operator type: o=0 is A and o=1 is B. :rtype: list """ p1 = p2 = p4 = p5 = 1.0 / (4 - (4 ** (1. / 3))) p3 = 1 - 4 * p1 trotter_dict = {1: [(1, 0), (1, 1)], 2: [(0.5, 0), (1, 1), (0.5, 0)], 3: [(7.0 / 24, 0), (2.0 / 3.0, 1), (3.0 / 4.0, 0), (-2.0 / 3.0, 1), (-1.0 / 24, 0), (1.0, 1)], 4: [(p5 / 2, 0), (p5, 1), (p5 / 2, 0), (p4 / 2, 0), (p4, 1), (p4 / 2, 0), (p3 / 2, 0), (p3, 1), (p3 / 2, 0), (p2 / 2, 0), (p2, 1), (p2 / 2, 0), (p1 / 2, 0), (p1, 1), (p1 / 2, 0)]} order_slices = [(x0 / trotter_steps, x1) for x0, x1 in trotter_dict[trotter_order]] order_slices = order_slices * trotter_steps return order_slices
0d17a992e769eddaa52de3ce54dfabc2071581cb
289,241
def reverseComplement(read): """ Returns the reverse complemnt of read :param read: a string consisting of only 'A', 'T', 'C', 'G's """ complementDict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} return ''.join([complementDict[c] for c in read[::-1]])
d77836b5f75a70189303a1118a4c45493a9a2181
620,351
import importlib def get_trainer(name, **trainer_args): """ Factory function for retrieving a trainer. """ module = importlib.import_module('.' + name, 'mldas.trainers') return module.get_trainer(**trainer_args)
74542656c6f1f3a91c428aec77d575c8c6f57f7d
612,176
def get_text_by_tag(start, tagname, default=None): """Returns a text node from a tag""" node_back = start.getElementsByTagName(tagname)[0] for node in node_back.childNodes: if node.nodeType == node.TEXT_NODE: return node.data return default
6763e94172fb06f117cd105dcf21c19132e85ead
183,008
def rhombus_area(diagonal_1, diagonal_2): """Returns the area of a rhombus""" # You have to code here # REMEMBER: Tests first!!! return (diagonal_1 * diagonal_2)/2
4f424d4651d577609102fbcc0a7ab08c9b70e6e2
343,546
def Statsmodels_Std_Error_Params(name, results, Explanatory, NumDecimal): """ This function gives the Std Error of the of the Params from a statsmodels model results. Arguments: ---------- - results: statsmodels result object of the model The results object of the model - Explanatory: Pandas DataFrame The DataFrame with the explanatory series - NumDecimal: int Number of decimals for the numbers calculated Return: ---------- - StErrParams: str The Std Error of the Params """ StErrParams = results.bse StErrParams = [str(round(item, NumDecimal)) for item in StErrParams] for item in range(0, len(Explanatory.columns)): StErrParams[item + 1] = str(StErrParams[item + 1]) + ' ' + str(Explanatory.columns[item]) StErrParams[0] = str(StErrParams[0]) StErrParams = ', '.join(StErrParams) return StErrParams
514452cf0656654e2561199f51a4b02c9976c7df
278,223
def quat_real(x): """ real component of the quaternion """ return x[..., 3]
c59bc3bdea62b007626b7ed1ed52a798455fff0c
317,276
def format_url(df): """ Replace index column values with html anchor pointing at URL in URL column then drop URL column Parameters ---------- df : DataFrame Data frame on which to perform replacment Returns ------- df : DataFrame Data Frame with index column values turned into URLs """ ix_col = df.index.name df = df.reset_index() df[ix_col] = df.apply( lambda x: f'<a href="{x["URL"]}">{x[ix_col]}</a>', axis=1 ) df = df.drop("URL", axis=1) df = df.set_index(ix_col) return df
ddd7fac090b16df4ba6eec899811b07a5f2bb2b7
260,170
def is_same(text0: str, text1: str, ignored: list): """Compare the content of two text. If there are different words in text0 and text1 and the word in text0 does not contain ignored substring, return False. Else return True.""" def should_ignore(word): for w in ignored: if w in word: return True return False words0, words1 = text0.split(), text1.split() if len(words0) != len(words1): return False for word0, word1 in zip(words0, words1): if not should_ignore(word0) and word0 != word1: return False return True
870453a917f8e3a1eff3918f5c69662fde6b65d1
73,999
def show_hidden_word(secret_word, old_letters_guessed): """ this function shows the player his progress in the game :param secret_word: the word the player has to guess :param old_letters_guessed: all the characters the player has already guessed :type secret_word: str :type old_letters_guessed: list :return: a string which consists of letters and underlines the string displays the letters from the old_letters_guessed list that are in the secret_word string in their appropriate position, and the rest of the letters in the string (which the player has not yet guessed) as underlines :rtype: str """ returned_string = "" for char in secret_word: if char in old_letters_guessed: returned_string += char else: returned_string += "_" return " ".join(returned_string)
32ae301bf70bde235642c34898e32b1e31f46992
93,824
def init_wiki(args): """ Initialize a WikiFetcher object according to arguments :param args: Argument object from command line :return: A dictionary of all arguments for WikiFetcher """ return {"lang": args.lang[0], "limit": args.nb_resp[0]}
f522d13ddab6f0e4f527cb00d39ccefd5080a7fc
592,044
from itertools import islice def head(filename, lines=5): """ Returns the first few lines of a file. filename: the name of the file to open lines: the number of lines to include return: A list of the first few lines from the file. """ with open(filename, "r") as f: return list(islice(f, lines))
b81baad4ce9d0f6c7aa1dc50bc5222870176ea53
298,679
def identity(x): """Return exactly what was provided.""" return x
ee6152b046b55e2044b67c4afed07ccc7c6cc471
668,841
def send_to_device(tensor, device): """ Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device. Args: tensor (nested list/tuple/dictionary of :obj:`torch.Tensor`): The data to send to a given device. device (:obj:`torch.device`): The device to send the data to Returns: The same data structure as :obj:`tensor` with all tensors sent to the proper device. """ if isinstance(tensor, (list, tuple)): return type(tensor)(send_to_device(t, device) for t in tensor) elif isinstance(tensor, dict): return type(tensor)({k: send_to_device(v, device) for k, v in tensor.items()}) elif not hasattr(tensor, "to"): # hasattr() 函数用于判断对象是否包含对应的属性 return tensor return tensor.to(device)
e82f9caaccaa0ef19335b1ed2216cbf8b2f5cded
339,120
def count_subset_sum_dp(arr, total): """Count subsets given sum by bottom-up dynamic programming. Time complexity: O(nm). Space complexity: O(nm). """ n = len(arr) - 1 T = [[0] * (total + 1) for _ in range(n + 1)] for a in range(n + 1): T[a][0] = 1 for a in range(n + 1): for t in range(1, total + 1): if t < arr[a]: T[a][t] = T[a - 1][t] else: T[a][t] = T[a - 1][t] + T[a - 1][t - arr[a]] return T[-1][-1]
fbcd618152b65f0e456a8f5ade8680e9a08d1d4e
81,014
def nodes(tree): """ Return a list of values at every node of a tree. Parameters ---------- tree : BinaryTree BinaryTree to extract nodes from. Returns ------- nodelist : list List of values at tree nodes. """ nodelist = [] def _get_nodes(tree): """ Build up a list of nodes. Parameters ---------- tree : BinaryTree BinaryTree to extract nodes from. Returns ------- None """ nodelist.append(tree.val) try: _get_nodes(tree.left) except AttributeError: nodelist.append(tree.left) try: _get_nodes(tree.right) except AttributeError: nodelist.append(tree.right) _get_nodes(tree) return nodelist
c2d1ee03c9208bbb2cbdbc403f16376ad744ff71
260,427
def imc(peso: float, estatura: float) -> float: """Devuele el IMC :param peso: Peso en kg :peso type: float :param estatura: Estatura en cm :estatura type: float :return: IMC :rtype: float >>> imc(78, 1.83) 23.29 """ return round(peso/(estatura**2), 2)
19c3423342239831205ba234a9e0bc8045582a36
576,751
def asdf_version(request): """ The (old) version of the asdf library under test. """ return request.param
4bb1dfb8f0fc1882c93bd278e607fae46706852f
539,012
def hr_time(seconds): """Formats a given time interval for human readability.""" s = '' if seconds >= 86400: d = seconds // 86400 seconds -= d * 86400 s += f'{int(d)}d' if seconds >= 3600: h = seconds // 3600 seconds -= h * 3600 s += f'{int(h)}h' if seconds >= 60: m = seconds // 60 seconds -= m * 60 if 'd' not in s: s += f'{int(m)}m' if 'h' not in s and 'd' not in s: s += f'{int(seconds)}s' return s
5e852331df6db8b9aaa43fa49d709d2f93b68907
81,880
def _path_to_levels(path): """Convert distribcell path to list of levels Parameters ---------- path : str Distribcell path Returns ------- list List of levels in path """ # Split path into universes/cells/lattices path_items = path.split('->') # Pair together universe and cell information from the same level idx = [i for i, item in enumerate(path_items) if item.startswith('u')] for i in reversed(idx): univ_id = int(path_items.pop(i)[1:]) cell_id = int(path_items.pop(i)[1:]) path_items.insert(i, ('universe', univ_id, cell_id)) # Reformat lattice into tuple idx = [i for i, item in enumerate(path_items) if isinstance(item, str)] for i in idx: item = path_items.pop(i)[1:-1] lat_id, lat_xyz = item.split('(') lat_id = int(lat_id) lat_xyz = tuple(int(x) for x in lat_xyz.split(',')) path_items.insert(i, ('lattice', lat_id, lat_xyz)) return path_items
8f2c3c6bf17a307acafeb91dd9e25ae9a8d045eb
148,328
import re def single_re_sub(text, repl_chars): """Replace specific characters with another character using a single regex.""" repl = re.compile("[{}]".format(repl_chars)) return repl.sub("a", text)
665dd75364ce2ac0cb03a0ef6f856ab0c03ce351
389,087
def NoShifter(*args, **kwargs): """ Dummy function to create an object that returns None Args: *args: will be ignored *kwargs: will be ignored Returns: None """ return None
87c18ef0b4c0b4a17005c707ad17cd193ccd97b7
669,890
def construct_html(search_term, results): """ Given a list of results, construct the HTML page. """ link_format = '<a href="{0.img_url}"><img src="{0.thumb_url}" alt="{0.name}" title="{0.name}"></a>' html_links = '\n'.join([link_format.format(result) for result in results]) html_output = ( '<html>' '<head><title>{search_term} pictures</title></head>' '<body>' '<h1>&ldquo;{search_term}&rdquo; pictures</h1>' '{html_links}' '</body>' '</html>' ).format(search_term=search_term, html_links=html_links) return html_output
8e77abdf3d18fc8eeb9795847d5565c951762e24
676,137
def nueva_bodega(s:str) -> bool: """ Descripcion: Dado un string no vacio, devuelve True si y solo si dentro de esos string se encuentran las palabras "nueva", "bodega", o "vino" Pre: len(s) != 0 Post: Si "nueva", "bodega", o "vino" se encuentran en s devuelve True, de lo contrario False """ vr:bool = "nueva" in s or "bodega" in s or "vino" in s or "Nueva" in s or "Bodega" in s or "Vino" in s return vr
040473e6ea4429516687649bab9dc130bd04e8e0
528,188
import json def _(value: dict) -> str: """Convert ``dict`` to JSON string""" return json.dumps(value)
e9e06adf99899c7d6991a74bf50fec4fbb7fd57f
527,074
def get_slice_name(index): """Gets the name of slice. Args: index: An int representing the index of the slice. Returns: A string representing the name of the slice. """ filename = 's{}.csv'.format(index) return filename
4ad9e077d99fcfef99034376d0094aa8bdf5c3a7
430,498
def translate_coord_to_move(row, column): """ Translates a pair of board indices to a move on a board. For example: (0,0) ==> {'Row':A,'Column':1} :param row: 1st index :param column: 2nd index :return: dict of the row and column. """ return {"Row": chr(row + 65), "Column": (column + 1)}
de2f0bba20549d5b480fa2552180caaaf26e36d1
146,657
from typing import Type def _all_subclasses(cls: Type): """Get all explicit and implicit subclasses of a type.""" return set(cls.__subclasses__()).union([s for c in cls.__subclasses__() for s in _all_subclasses(c)])
1573cf26f4cac57f42fe946988f24fb270f6abba
384,422
def rgb2hex(tup, max=1): """ convert an rgb tuple into a hex color string representation Args: tup: tuple: tuple of length 3 representing the color max=1: the maximum value for the values in the tuple. This will be used to scale the tuple values as integers between 0 and 255. Returns: color: str: hex color string representation (format "aaaaaa" - no "#") """ tup = [int(c * 255 / max) for c in tup] color = "" for c in tup: if c < 16: c = "0" + hex(c)[-1:] else: c = hex(c)[-2:] color += c return color.upper()
b8be88b335847218c469e26da2e73bf302428ed5
443,123
def table_col_info(c, table_name, print_out=False): """ Returns a list of tuples with column informations: (id, name, type, notnull, default_value, primary_key) """ c.execute('PRAGMA TABLE_INFO({})'.format(table_name)) info = c.fetchall() if print_out: print("\nColumn Info:\nID, Name, Type, NotNull, DefaultVal, PrimaryKey") for col in info: print(col) return info
10b8cc09e490fdb47b07957a6f020e0f8c2d667b
392,160
def boolean(truth): """Convert truth to boolean.""" if str(truth).lower() in ['true', 'yes', '1', 'none']: return True else: return False
4288efdfd92140d16ac01bc0291d627dcb1ed416
567,503
def following_mention_ids(api, ids): """ This function has the mention_ids and make sure if the account follow them if not ... don't make sense to unfollow them returns the ids list only with the ones that the account follow """ ids = list(set(ids)) following_mention_ids = [] for idt in ids: if api.show_friendship(source_id=idt, target_id=api.me().id)[0].followed_by: following_mention_ids.append(idt) return following_mention_ids
508032d92b563e8776c736404d6465d76c20a4a8
673,897
def cli(ctx, name, owner): """Returns the ordered list of changeset revision hash strings that are associated with installable revisions. As in the changelog, the list is ordered oldest to newest. Output: List of changeset revision hash strings from oldest to newest """ return ctx.ti.repositories.get_ordered_installable_revisions(name, owner)
eb718c34e65ba38bb991c8e816d41312a5928ac6
68,537
def polyschedule(max_epochs, gamma=0.9): """Poly-learning rate policy popularised by DeepLab-v2: https://arxiv.org/abs/1606.00915 Args: max_epochs (int): maximum number of epochs, at which the multiplier becomes zero. gamma (float): decay factor. Returns: Callable that takes the current epoch as an argument and returns the learning rate multiplier. """ def polypolicy(epoch): return (1.0 - 1.0 * epoch / max_epochs) ** gamma return polypolicy
bb2fed780f69d83ff0a96cbe38361458e62ccaa8
112,978
def get_n_features(matrix, min_=2): """Get the number of features in a matrix. Args: matrix : ndarray A numeric numpy array. Features are assumed to be the columns. min_ : int The smallest number of features that `matrix` is permitted to have. Returns n_features : int The number of features in `matrix`. Raises: * if `matrix.shape[1] < min_` """ _, n_features = matrix.shape if n_features < min_: raise IndexError( "less than {} features present.".format(min_) ) return n_features
1d3a251d35a47fcf9148d340e05509966bf50398
399,290
def prefix_attrs(source, keys, prefix): """Rename some of the keys of a dictionary by adding a prefix. Parameters ---------- source : dict Source dictionary, for example data attributes. keys : sequence Names of keys to prefix. prefix : str Prefix to prepend to keys. Returns ------- dict Dictionary of attributes with some keys prefixed. """ out = {} for key, val in source.items(): if key in keys: out[f"{prefix}{key}"] = val else: out[key] = val return out
e1c8102fddf51cd7af620f9158419bff4b3f0c57
2,165
def zeroPad(n, l): """ Add leading 0.""" return str(n).zfill(l)
2f8c6a9baf0dab2f41cad8d1c2bebb3d9166491e
276,928
def is_draft(request): """Check if the request is a draft (neither open nor closed).""" return not request.is_open and not request.is_closed
bd6e30836a72f21426ca2430cb405cca96495c33
112,952
def override_arg(argname,value,args,kwargs,argspec): """overrides the given argname=value in args or kwargs as appropriate, returning (args, kwargs)""" if argname in kwargs: kwargs[argname] = value return (args, kwargs) regargs, varargs, varkwargs, defaults = argspec if argname in regargs: if isinstance(args, tuple): args = list(args) args[regargs.index(argname)] = value else: kwargs[argname] = value return (args, kwargs)
c91ecef7e421ad86b9e4ffa4837d8cbb5783c667
491,945
import re def remove_type_spaces(part): """ Trims whitespace from types that can have it. This will alter types, so the resulting strings shoudln't be used to deduce types. The results are intended to make it easier to parse out param names. """ ret = re.sub(r"func\(.*\)\s+", "func()_", part) ret = re.sub(r"chan\s+", "chan_", ret) return ret
9cc1bfe97ab97432475ce37beec3cd0da8d9ba94
600,396
def int_to_string(ints, inv_vocab): """ Output a machine readable list of characters based on a list of indexes in the machine's vocabulary Arguments: ints -- list of integers representing indexes in the machine's vocabulary inv_vocab -- dictionary mapping machine readable indexes to machine readable characters Returns: l -- list of characters corresponding to the indexes of ints thanks to the inv_vocab mapping """ l = [inv_vocab[i] for i in ints] return l
d4bc78b1aef35aeae5396b644d63c3ac71e41c02
408,663
def tuple_width(tup): """Returns the lengths of all the strings in a tuple.""" return tuple(len(i) for i in tup)
5770247f8692ca45b72b82d5ec39a5bbb583f952
214,336
def format_seconds(seconds): """Convert seconds to a formatted string Convert seconds: 3661 To formatted: " 1:01:01" """ # ensure to show negative time frames correctly hour_factor = 1 if seconds < 0 : hour_factor = -1 seconds = - seconds hours = seconds // 3600 minutes = seconds % 3600 // 60 seconds = seconds % 60 return "{:4d}:{:02d}:{:02d}".format(hour_factor * hours, minutes, seconds)
813f85919c1cab97425ee184f9fa610c8a8c008e
464,088
import re def convert_to_tsquery(query): """ Converts multi-word phrases into AND boolean queries for postgresql. Examples: >>> convert_to_tsquery('interpretation') 'interpretation:*' >>> convert_to_tsquery('interpretation services') 'interpretation:* & services:*' """ # remove all non-alphanumeric or whitespace chars pattern = re.compile('[^a-zA-Z\s]') query = pattern.sub('', query) query_parts = query.split() # remove empty strings and add :* to use prefix matching on each chunk query_parts = ["%s:*" % s for s in query_parts if s] tsquery = ' & '.join(query_parts) return tsquery
41e4503e7f38cc122cebb80534e45b1cc1e6d6c9
529,939
def seq_encode(number, symbols): """ Encode a number using a sequence of symbols. :param int number: number to encode :param symbols: sequence key :type symbols: str or list[char] :returns: encoded value :rtype: str """ d, m = divmod(number, len(symbols)) if d > 0: return seq_encode(d, symbols) + symbols[m] return symbols[m]
7ea12330ded9dd115f3c8f5d7bec838bad05852a
184,202
import binascii def enhex(d, separator=''): """ Convert bytes to their hexadecimal representation, optionally joined by a given separator. Args: d(bytes): The data to convert to hexadecimal representation. separator(str): The separator to insert between hexadecimal tuples. Returns: str: The hexadecimal representation of ``d``. Examples: >>> from pwny import * >>> enhex(b'pwnypack') '70776e797061636b' >>> enhex(b'pwnypack', separator=' ') '70 77 6e 79 70 61 63 6b' """ v = binascii.hexlify(d).decode('ascii') if separator: return separator.join( v[i:i+2] for i in range(0, len(v), 2) ) else: return v
5516b306973719a1fd5c406a0bf7b7f5affa2a55
496,304
from datetime import datetime def parse_due_date(line): """Parses due date from line. :param line: Line string. :type line: str :return: datetime.date if successful, None otherwise. :rtype: datetime.date or None """ try: return datetime.strptime(line, '%d.%m.%Y').date() except ValueError: return None
6ffb4d275b0e4856478fd068468b5203c9c21d13
167,506
def shape(t): """Returns shape of tensor as list of ints.""" return [-1 if x is None else x for x in t.get_shape().as_list()]
01cb58d5b037a4275f50fc3a02b17b41b7d1cf11
418,542
def list_to_string(lst, det, det_type="a"): """ Convert a list to a natural language string. """ string = "" if len(lst) == 1: return "{}{}".format(det_type + " " if det else "", lst[0]) for i in range(len(lst)): if i >= (len(lst) - 1): string = "{} and {}{}".format(string[:-2], "{} ".format(det_type) if det else "", lst[i]) else: string += "{}{}, ".format("{} ".format(det_type) if det else "", lst[i]) return string
56de38dee6c5372e222fe95bc8325b65754d13ce
134,132
def row_col_indices_from_flattened_indices(indices, num_cols): """Computes row and column indices from flattened indices. Args: indices: An integer tensor of any shape holding the indices in the flattened space. num_cols: Number of columns in the image (width). Returns: row_indices: The row indices corresponding to each of the input indices. Same shape as indices. col_indices: The column indices corresponding to each of the input indices. Same shape as indices. """ # Avoid using mod operator to make the ops more easy to be compatible with # different environments, e.g. WASM. row_indices = indices // num_cols col_indices = indices - row_indices * num_cols return row_indices, col_indices
8b56ab9a63a4edb929d5ba0a6bc0d52da61939f8
692,614
def is_palindrome(string): """ Checks the string for palindrome :param string: string to check :return: true if string is a palindrome false if not """ if string == string[::-1]: return True return False
fa891dbca523d9c257178356ba09d52d87777d1d
498,750
def stdlib(toolchain): """ Extract standard library file list and file path from toolchain """ stdlib = toolchain.ocaml_stdlib.files.to_list() stdlib_path = stdlib[0].dirname return (stdlib, stdlib_path)
59f75d3b220caa8d6ab5bc5d7e5f02b52c0d20b5
553,960
def boolean(obj): """ Convert obj to a boolean value. If obj is string, obj will converted by case-insensitive way: * convert `yes`, `y`, `on`, `true`, `t`, `1` to True * convert `no`, `n`, `off`, `false`, `f`, `0` to False * raising TypeError if other values passed If obj is non-string, obj will converted by bool(obj). """ try: text = obj.strip().lower() except AttributeError: return bool(obj) if text in ('yes', 'y', 'on', 'true', 't', '1'): return True elif text in ('no', 'n', 'off', 'false', 'f', '0'): return False else: raise ValueError("Unable to convert {!r} to a boolean value.".format(text))
f2172b0d4c5794425a11a28705de81871a6fbe36
629,111
def is_vertex_cover(G, vertex_cover): """Determines whether the given set of vertices is a vertex cover of graph G. A vertex cover is a set of vertices such that each edge of the graph is incident with at least one vertex in the set. Parameters ---------- G : NetworkX graph The graph on which to check the vertex cover. vertex_cover : Iterable of nodes. Returns ------- is_cover : bool True if the given iterable forms a vertex cover. Examples -------- This example checks two covers for a graph, G, of a single Chimera unit cell. The first uses the set of the four horizontal qubits, which do constitute a cover; the second set removes one node. >>> import dwave_networkx as dnx >>> G = dnx.chimera_graph(1, 1, 4) >>> cover = [0, 1, 2, 3] >>> dnx.is_vertex_cover(G,cover) True >>> cover = [0, 1, 2] >>> dnx.is_vertex_cover(G,cover) False """ cover = set(vertex_cover) return all(u in cover or v in cover for u, v in G.edges)
4213db1953ec976b1606c3756fa73ff0cae9f578
4,549
def assert_allclose(x, y, rtol=1.e-5, atol=1.e-5): """ Asserts if all numeric values from two arrays are close. Parameters ---------- x: ndarray Expected value. y: ndarray Actual value. rtol: float (optional) Relative tolerance on the error. Default is 1.e-5. atol: float (optional) Absolut tolerance on the error. Default is 1.e-5. Returns ------- None """ return (abs(x - y) <= atol + rtol * abs(y)).all()
ebf5191d3430e515c7ad1c0c63032ae38e92a509
582,719
def get_valid_messages(log, expiry): """ Return only the messages that haven't expired. """ valid = [] for message in log: try: timestamp = int(message.get('timestamp', 0)) if timestamp > expiry: valid.append(message) except ValueError: continue return valid
d24e9bc5e6d0a2c0efd9442f0d36f6e248b51137
15,750
from typing import Callable from typing import Tuple from typing import Any from typing import Dict from warnings import warn def format_errwarn(func: Callable[[], Tuple[Any, Dict, Dict]]): """ Wraps a function returning some result with dictionaries for errors and warnings, then formats those errors and warnings as grouped warnings. Used for analytical functions to skip errors (and warnings) while providing Args: func (function): any function returning a tuple of format: (result, error_dictionary, warning_dictionary). Note that dictionaries should be of form {<column or id>:<message>} Returns: Any (result): the first member of the tuple returned by func """ def format_info(dict): info_dict = {} for colname, err_wrn in dict.items(): _ew = list(set(err_wrn)) if isinstance(err_wrn, list) else [err_wrn] for m in _ew: m = getattr(m, "message") if "message" in dir(m) else str(m) if m in info_dict.keys(): info_dict[m].append(colname) else: info_dict[m] = [colname] info_dict = {ew: list(set(c)) for ew, c in info_dict.items()} return info_dict def wrapper(*args, **kwargs): res, errs, warns = func(*args, **kwargs) if any(errs): err_dict = format_info(errs) for er, cols in err_dict.items(): warn(f"Error processing column(s) {cols}. {er}\n") if any(warns): warn_dict = format_info(warns) for wr, cols in warn_dict.items(): warn(f"Possible error in column(s) {cols}. {wr}\n") return res return wrapper
d8dd854ca3ce3a45c07432a51a69ff78758a3da9
660,488
import requests def get_response_json(url: str): """ Function get response json dictionary from url. :param url: url address to get response json :type url: str :return: dictionary data :rtype: json :usage: function calling .. code:: python get_response_json(url) """ response = requests.get(url) response.raise_for_status() return response.json()
dd209b1dba7f4320cd91addb1e49fa98bab0ae2b
10,124
def get_in(obj, lookup, default=None): """ Walk obj via __getitem__ for each lookup, returning the final value of the lookup or default. """ tmp = obj for l in lookup: try: # pragma: no cover tmp = tmp[l] except (KeyError, IndexError, TypeError): # pragma: no cover return default return tmp
73dfcaadb6936304baa3471f1d1e980f815a7057
708,346
def hk_accentuation(hk_syllab): """ Map accentuation of HK entry. """ hk_acc = [] hk_syllab_list = hk_syllab.split(".") for syllabe in hk_syllab_list: if "/" in syllabe: hk_acc.append("U") else: hk_acc.append("B") return "".join(hk_acc)
3347872f227e449b3cccdb4100f474f6e5d579b6
212,994
def evaluator_options_from_eval_config(eval_config): """Produces a dictionary of evaluation options for each eval metric. Args: eval_config: An `eval_pb2.EvalConfig`. Returns: evaluator_options: A dictionary of metric names (see EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization keyword arguments. For example: evalator_options = { 'coco_detection_metrics': {'include_metrics_per_category': True} } """ eval_metric_fn_keys = eval_config.metrics_set evaluator_options = {} for eval_metric_fn_key in eval_metric_fn_keys: if eval_metric_fn_key in ( 'coco_detection_metrics', 'coco_mask_metrics', 'lvis_mask_metrics'): evaluator_options[eval_metric_fn_key] = { 'include_metrics_per_category': ( eval_config.include_metrics_per_category) } # For coco detection eval, if the eval_config proto contains the # "skip_predictions_for_unlabeled_class" field, include this field in # evaluator_options. if eval_metric_fn_key == 'coco_detection_metrics' and hasattr( eval_config, 'skip_predictions_for_unlabeled_class'): evaluator_options[eval_metric_fn_key].update({ 'skip_predictions_for_unlabeled_class': (eval_config.skip_predictions_for_unlabeled_class) }) for super_category in eval_config.super_categories: if 'super_categories' not in evaluator_options[eval_metric_fn_key]: evaluator_options[eval_metric_fn_key]['super_categories'] = {} key = super_category value = eval_config.super_categories[key].split(',') evaluator_options[eval_metric_fn_key]['super_categories'][key] = value elif eval_metric_fn_key == 'precision_at_recall_detection_metrics': evaluator_options[eval_metric_fn_key] = { 'recall_lower_bound': (eval_config.recall_lower_bound), 'recall_upper_bound': (eval_config.recall_upper_bound) } return evaluator_options
7a1f184427830c460d7a1909297e39e2cb56bb58
507,780
def is_legal_input(row): """ :param row: (string) input string from user :return: (boolean) if legal input """ # check if over 4 char if len(row.split()) != 4: print('Illegal input') return False # check if each element only one character else: for char in row.split(): if len(char) != 1: print('Illegal input') return False return True
ca9c79bb11a426bb604a10daf5755b30ad2a2adb
537,632
def get_ratings(labeled_df): """Returns list of possible ratings.""" return labeled_df.RATING.unique()
2b88b1703ad5b5b0a074ed7bc4591f0e88d97f92
706,048
def _remove_scripts(document_tree): """Removes any script tag from the tree""" script_elements = document_tree.xpath('//script') for script in script_elements: script.getparent().remove(script) return document_tree
21932697913fa7cd3ccc6b3841aaf9f430621f07
558,749
def sort_graded(task): """Sorts all tasks in the tasks_graded list, where tasks with the highest score is placed last in the list """ return task['score']
0f962c87b1440a5fdc51b72de4ea546b64a6be08
259,983
from typing import Dict from datetime import datetime def inject_now() -> Dict: """Inject current datetime into request context.""" return dict(request_datetime=datetime.now())
e186d4b478a5da5bcdf83e2e34cd381de8d039be
697,860
def sanitize_line(line, commenter='#'): """Clean up input line.""" return line.split(commenter, 1)[0].strip()
ea537e479438058379bb4e1517e848252be9e408
468,972
import re def spdx_search(searchstr,sbom, want_json = False): """ Return array of names and versions for matching entries in SPDX JSON file. """ if not 'packages' in sbom: return False rets=[] prog=re.compile(searchstr) for entry in sbom['packages']: if prog.match(entry['name']): if want_json: rets.append(entry) else: rets.append({'name': entry['name'], 'version': entry['versionInfo']}) if 'checksums' in entry: for hash_entry in entry['checksums']: if prog.match(hash_entry['checksumValue']): if want_json: rets.append(entry) else: rets.append({'name': entry['name'], 'version': entry['versionInfo']}) return rets
5e63c4b2502bc92cb9ee6f3dbb96516d949fb233
159,755
import crypt def crypt_password(password): """Return hashed password, compatible with the vhost database.""" return crypt.crypt(password, salt=crypt.METHOD_SHA512)
f9c73b8a1ce908a6bf6d86c5d9e373362dfb2074
160,935
import torch def count_conv_layer(model): """Count the number of Convolution layers exist in this model""" conv_cnt = 0 for module in model.modules(): if type(module) == torch.nn.Conv2d: conv_cnt += 1 return conv_cnt
e192772b891f1179deb0e765a4b1bea40c21a46f
441,983
def get_data_set_specs(data_set): """ Get the OpenAPI specifications of a SED data set Args: data_set (:obj:`DataSet`): data set Returns: :obj:`dict` with schema `SedDataSet` """ specs = { '_type': 'SedDataSet', 'id': data_set.id, 'dataGenerator': data_set.data_generator.id, } if data_set.name: specs['name'] = data_set.name if data_set.label: specs['label'] = data_set.label return specs
2e1f596e8d6fe29920a148a94aefeac8626f06e2
481,591
def chop(array, abs_tol=1E-12): """ Set to zero numerical zeros (values below abs_tol) in a np.array. Acts in-place. """ array[abs(array) < abs_tol] = 0 return array
e06009d596ac9e510f41bf54553eb3bf87eda697
257,182
def FinishTarget_to_c(self): """Syntax for a target of a break.""" return f"break_{self.targetID}: break;"
2c05a3ec819cddf34c422301e25296074fbf534b
410,558
def question_3(df): """ This functions determines the average Medicare payments per DRG per facility. Parameters ------------ df : `pandas.DataFrame` DataFrame containing the original information about DRG. Returns -------- medicare_pd : `pandas.DataFrame` DataFrame containing information about the average Medicare payments per DRG per facility """ # Columns to keep disch_col = 'total_discharges' prov_col = 'provider_name' drg_col = 'drg_definition' medi_col = 'average_medicare_payments' cols_keep = [prov_col, disch_col, drg_col, medi_col] # Creating sub-DataFrame med_main_df = df.loc[:, cols_keep] # Grouping by DRG and facility medicare_pd = (med_main_df.groupby([drg_col, prov_col]) .mean()).drop(disch_col, axis=1) return medicare_pd
8e510c9def715cbaa3d98f80b017626a8a8f1290
409,240
def create_dict(keys_list): """ Creates a dictionary from a given list of keys """ dict_ = {} for key_ in keys_list: dict_[key_] = [] return dict_
33c4d0fbf389d4b968e68ad76406a169010b3db6
632,870
def false(*ignore, **everything): """Give False regardless of the input.""" return False
6cf9de4f3512723874614e01b0c68e3a618c36ac
154,697
from typing import Mapping def make_dict(*args): """Combine all key/vals in *args into one dict with later values taking precedence Yanked from prom.utils on 6-7-2021 https://docs.python.org/3/library/stdtypes.html#dict :params *args: dictionaries, or tuples (key, val) or lists of tuples to be combined into one dictionary :returns: dict """ ret = {} for d in args: if isinstance(d, Mapping): ret.update(d) else: try: ret.update(dict(d)) except ValueError: ret.update(dict([d])) return ret
92b7e9cca75eea6154fc486abcf53c6165a8a8dc
500,610
def import_book(book_file, lowercase=True): """ Reads a text file (and optionally converts to lowercase), returning a string with all the content. """ try: with open(book_file, 'r') as book: text = book.read() text = text.lower() return text except (FileNotFoundError, PermissionError): message = 'There was a problem importing the book.\n' message += 'Please, check the path and permissions.' raise UserWarning(message)
064ddf5e3a605be7692375d5b98893bd0ef36de8
536,662
def get_crop(mask_image, scale_ratio=1.2): """ Get bounding box of square encompassing all positive values of the mask, with a margin according to scale_ratio Args: scale_ratio: final crop is obtained by taking the square centered around the center of the tight bounding box around the masked values, with a square size of scale_ratio * size of largest bounding box dimension """ mask_image = mask_image.numpy() xs, ys = (mask_image[:, :, ::3].sum(2) > 0).nonzero() x_min = xs.min() x_max = xs.max() y_min = ys.min() y_max = ys.max() radius = max((x_max - x_min), (y_max - y_min)) // 2 * scale_ratio x_c = (x_max + x_min) / 2 y_c = (y_max + y_min) / 2 x_min = max(int((x_c - radius).item()), 0) y_min = max(int((y_c - radius).item()), 0) x_max = int((x_c + radius).item()) y_max = int((y_c + radius).item()) return x_min, y_min, x_max, y_max
00c882abfb5ff0a461dc1d3b930471fc4c5ad2fe
56,612
def get_conditions(worksheet): """ Get the conditions displayed on a worksheet. args: worksheet (seeq.spy.workbooks._worksheet.AnalysisWorksheet): Worksheet returns: conditions (pandas.DataFrame): Displayed Conditions """ display_items = worksheet.display_items if len(display_items) == 0: raise ValueError('No items (signals, conditions, etc) are displayed in this worksheet.') return display_items.query("Type == 'Condition'")
f3fe0bd58f9a0344f047e3ae6eef6bdefa325c21
29,534
def firstof(seq): """Return the first item that is truthy in a sequence. Equivalent to Djangos' firstof. Args: seq (list): A list of values. Returns: value (mixed): The output, depending on the truthiness of the input. """ if not any(seq): return '' if all(seq): return seq[0] while seq: item = seq.pop(0) if item: return item return ''
539058665f4a9a2691b1cc3edec819e127857c04
247,738
def fib(n): """Returns a Fibonacii element by its index Arguments: n {integer} -- An index number Returns: integer -- A Fibonacci number at given index """ if n > 1: return fib(n - 1) + fib(n - 2) return n
9abc6497f29b8e9f3bfda5c6a613caa90d0da0ab
149,202
def fill_fuel_array_from_patch(fuelarray, patchmask, propertyvector, np, nx, ny): """Fill fuel array considering a mask Parameters ---------- fuelarray : numpy.ndarray Array to modify according to `propertyvector` and `patchmask`. patchmask : numpy.ndarray Mask array. propertyvector : numpy.ndarray Vector of properties to fill in the fuel array. np : int Property vector size nx : int Fire mesh size on x axis ny : int Fire mesh size on y axis Returns ------- fuelarray : numpy.ndarray Modified array according to `propertyvector` and `patchmask`. """ # property loop for k in range(np): # y axis loop for j in range(ny): # x axis loop for i in range(nx): # check mask value if patchmask[j, i] == 1: fuelarray[k, j, i] = propertyvector[k] return fuelarray
c77b9451fcdc4cd74dbd53ce45f8c89fdf1a0fb1
250,801
def text_objects(self, text, color, size): """Render font based on a choice of four different sizes. Parameters for Render are: (text, antialias, color). Args: self (class App): Main game class. text (str): Text to be rendered. color (tuple): Color of text. size (str): Size of text. Returns: tuple: [0]=Font to be blit to display; [1]=rectangle for button. """ text_surface = self.xs_font.render(text, True, color) if size == "xs": text_surface = self.xs_font.render(text, True, color) elif size == "s": text_surface = self.s_font.render(text, True, color) elif size == "m": text_surface = self.m_font.render(text, True, color) elif size == "l": text_surface = self.l_font.render(text, True, color) return text_surface, text_surface.get_rect()
1aa96b708bb112f7fbf16f368608807efcd57611
252,499
def file_extensions_valid(ext_list): """Checks if file list contains only valid files Notes: Assumes all file extensions are equal! Only checks first file Args: ext_list (list): file extensions, eg ['.csv','.csv'] Returns: bool: first element in list is one of ['.csv','.txt','.xls','.xlsx']? """ ext_list_valid = ['.csv','.txt','.xls','.xlsx'] return ext_list[0] in ext_list_valid
f1b131b3326e695422ad7c8df744f7cbb3ee8d9b
358,068
import time def wait_for_joystick_or_menu(hardware, sleep_time=1 / 30): """Waits for either the joystick or the menu. Returns the buttons""" while True: buttons = hardware.get_buttons() if buttons.menu_button or buttons.joy_button: return buttons time.sleep(sleep_time)
97c31991944ef098aa71c2ea249a3a46b35a1f80
395,898
def _proto_dataset_info(dataset): """Return information about proto dataset as a dict.""" # Analogous to dtool_info.inventory._dataset_info info = {} info['type'] = 'dtool-proto' info['uri'] = dataset.uri info['uuid'] = dataset.uuid info["size_int"] = None info["size_str"] = 'unknown' info['creator'] = dataset._admin_metadata['creator_username'] info['name'] = dataset._admin_metadata['name'] info["date"] = 'not yet frozen' info['readme_content'] = dataset.get_readme_content() return info
6072f5f9222f88ea1e33971036bd13d65754f39a
686,420
def validate_string(string, min_len=5): """ Validates a string. Returns False if the string is less than 'min_len' long. """ string = string.strip() if len(string) < min_len: return False return True
4e424c1f1e8119f8d76582a1fc3d25b6f3854798
457,695
import itertools def _expand(the_set, expand_fn): """Returns a concatenation of the expanded sets. I.e. Returns a set of all elements returned by the expand_fn function for all elements in the_set. E.g. With expand_fn = lambda x: (10*x, 100*x) and the_set = set([1, 2, 3]) this function returns set([10, 100, 20, 200, 30, 300]) Args: the_set: A set of elements. expand_fn: Function returning an interable given some element in the_set. Returns: a concatenation of the expanded sets. """ return set(itertools.chain(*[expand_fn(x) for x in the_set]))
694661c0cc6d2d09d72d65ea63cc1241fc32d4d5
22,198
def not_list_tuple(obj): """return False if obj is a list or a tuple""" return not isinstance(obj, (list, tuple))
1d34f7eb53577277311d0afbc80a680da9f366fa
369,098
def next_generation(state,rules): """ Return the string that results from applying RULES to STATE. """ next_state = '' for i in range(2,len(state) - 2): pattern = state[i - 2:i + 3] if pattern in rules: next_state += rules[pattern] else: next_state += '.' return '..' + next_state + '..'
4e533079250bb2c812041cff27365dd014697cb1
553,863
def percentageDecrease(x, y): """Return the percentage decrease from x towards y Args: x: original value y: changed value Returns: percentage decrease from x towards y. """ return (float(x)-float(y))/float(x)
9c613f9d5f034b0448866580ac34f9fe989e6645
303,834
def _pretty_state_identifier(state): """ returns 'off' for False and 'on' for True """ if state: return 'on' else: return 'off'
a4383b7061e2da73a6faab4819b848bc1375e884
661,838
import logging def threshold() : """Get current global threshold """ return logging.root.manager.disable
2b1c1abcd9cc22c4f5262f319c175e13bffd4263
383,118
import copy def isolate_and_merge_station(inv, network_id, station_id): """ Takes an inventory object, isolates the given station and merged them. Merging is sometimes necessary as many files have the same station multiple times. Returns the processed inventory object. The original one will not be changed. :param inv: The inventory. :type inv: :class:`~obspy.core.inventory.inventory.Inventory` :param network_id: The network id. :type network_id: str :param station_id: The station id. :type station_id: str """ inv = copy.deepcopy(inv.select(network=network_id, station=station_id, keep_empty=True)) # Merge networks if necessary. if len(inv.networks) != 1: network = inv.networks[0] for other_network in inv.networks[1:]: # Merge the stations. network.stations.extend(other_network.stations) # Update the times if necessary. if other_network.start_date is not None: if network.start_date is None or \ network.start_date > other_network.start_date: network.start_date = other_network.start_date # None is the "biggest" end_date. if network.end_date is not None and other_network.end_date is \ not None: if other_network.end_date > network.end_date: network.end_date = other_network.end_date elif other_network.end_date is None: network.end_date = None # Update comments. network.comments = list( set(network.comments).union(set(other_network.comments))) # Update the number of stations. if other_network.total_number_of_stations: if network.total_number_of_stations or \ network.total_number_of_stations < \ other_network.total_number_of_stations: network.total_number_of_stations = \ other_network.total_number_of_stations # Update the other elements network.alternate_code = (network.alternate_code or other_network.alternate_code) or None network.description = (network.description or other_network.description) or None network.historical_code = (network.historical_code or other_network.historical_code) or None network.restricted_status = network.restricted_status or \ other_network.restricted_status inv.networks = [network] # Merge stations if necessary. if len(inv.networks[0].stations) != 1: station = inv.networks[0].stations[0] for other_station in inv.networks[0].stations[1:]: # Merge the channels. station.channels.extend(other_station.channels) # Update the times if necessary. if other_station.start_date is not None: if station.start_date is None or \ station.start_date > other_station.start_date: station.start_date = other_station.start_date # None is the "biggest" end_date. if station.end_date is not None and other_station.end_date is \ not None: if other_station.end_date > station.end_date: station.end_date = other_station.end_date elif other_station.end_date is None: station.end_date = None # Update comments. station.comments = list( set(station.comments).union(set(other_station.comments))) # Update the number of channels. if other_station.total_number_of_channels: if station.total_number_of_channels or \ station.total_number_of_channels < \ other_station.total_number_of_channels: station.total_number_of_channels = \ other_station.total_number_of_channels # Update the other elements station.alternate_code = (station.alternate_code or other_station.alternate_code) or None station.description = (station.description or other_station.description) or None station.historical_code = (station.historical_code or other_station.historical_code) or None station.restricted_status = station.restricted_status or \ other_station.restricted_status inv.networks[0].stations = [station] # Last but not least, remove duplicate channels. This is done on the # location and channel id, and the times, nothing else. unique_channels = [] available_channel_hashes = [] for channel in inv[0][0]: c_hash = hash((str(channel.start_date), str(channel.end_date), channel.code, channel.location_code)) if c_hash in available_channel_hashes: continue else: unique_channels.append(channel) available_channel_hashes.append(c_hash) inv[0][0].channels = unique_channels # Update the selected number of stations and channels. inv[0].selected_number_of_stations = 1 inv[0][0].selected_number_of_channels = len(inv[0][0].channels) return inv
ce7756535f0fe95d411639e8e824975b384cbe9c
88,258
import six def python_2_unicode_compatible(klass): """Fix __str__, __unicode__ and __repr__ methods under Python 2.""" if six.PY2: if '__str__' not in klass.__dict__: raise ValueError("Define __str__() on %s to use @python_2_unicode_compatible" % klass.__name__) if '__repr__' not in klass.__dict__: raise ValueError("Define __repr__() on %s to use @python_2_unicode_compatible" % klass.__name__) klass.__unicode__ = klass.__str__ klass._unicode_repr = klass.__repr__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') klass.__repr__ = lambda self: self._unicode_repr().encode('ascii', errors='backslashreplace') return klass
89a928893a45b358f17d9a953aeb47ae7576e710
206,722
def get_isbn10_checksum(isbn): """ Args: isbn (str/list): ISBN number as string or list of digits Warning: Function expects that `isbn` is only 9 digits long. Returns: int: Last (checksum) digit for given `isbn`. """ return sum([(i + 1) * x for i, x in enumerate(isbn)]) % 11
c57ca34d85b197cc7b94038259fd8c5df74efffe
264,251
from typing import Callable from typing import List import inspect def get_arg_names(func: Callable) -> List[str]: """Get a list of all named arguments of a function (regular, keyword-only). func (Callable): The function RETURNS (List[str]): The argument names. """ argspec = inspect.getfullargspec(func) return list(set([*argspec.args, *argspec.kwonlyargs]))
2156c25ccdc9d325b2bad60311be5c1ecc726d3f
373,435
def server(app): """Return a test client to `app`.""" client = app.test_client() return client
aeef67904f95d28356989ddbde49a43378fa096f
20,920
import re def strip_spaces(string): """Remove white-space from a string Parameters ---------- string: str Returns ------- str """ pattern = re.compile(r'\s+') return re.sub(pattern, '', string)
d3f2767371b49e3c8adc64eac3f61aa790e3a430
683,541