text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get(self, res, pk): "Get a resource instance by primary key (id)" B = get_backend() return B.get_object(B.get_concrete(res), pk)
[ "def", "get", "(", "self", ",", "res", ",", "pk", ")", ":", "B", "=", "get_backend", "(", ")", "return", "B", ".", "get_object", "(", "B", ".", "get_concrete", "(", "res", ")", ",", "pk", ")" ]
38.25
0.012821
def dump(self, raw=False): ''' Dump all output currently in the arm's output queue. ''' raw_out = self.ser.read(self.ser.in_waiting) if raw: return raw_out return raw_out.decode(OUTPUT_ENCODING)
[ "def", "dump", "(", "self", ",", "raw", "=", "False", ")", ":", "raw_out", "=", "self", ".", "ser", ".", "read", "(", "self", ".", "ser", ".", "in_waiting", ")", "if", "raw", ":", "return", "raw_out", "return", "raw_out", ".", "decode", "(", "OUTPU...
38.833333
0.008403
def soil_data(self, polygon): """ Retrieves the latest soil data on the specified polygon :param polygon: the reference polygon you want soil data for :type polygon: `pyowm.agro10.polygon.Polygon` instance :returns: a `pyowm.agro10.soil.Soil` instance """ assert...
[ "def", "soil_data", "(", "self", ",", "polygon", ")", ":", "assert", "polygon", "is", "not", "None", "assert", "isinstance", "(", "polygon", ",", "Polygon", ")", "polyd", "=", "polygon", ".", "id", "status", ",", "data", "=", "self", ".", "http_client", ...
37.166667
0.002186
def parse_keys_and_ranges(i_str, keyfunc, rangefunc): '''Parse the :class:`from_kvlayer` input string. This accepts two formats. In the textual format, it accepts any number of stream IDs in timestamp-docid format, separated by ``,`` or ``;``, and processes those as individual stream IDs. In the ...
[ "def", "parse_keys_and_ranges", "(", "i_str", ",", "keyfunc", ",", "rangefunc", ")", ":", "while", "i_str", ":", "m", "=", "_STREAM_ID_RE", ".", "match", "(", "i_str", ")", "if", "m", ":", "# old style text stream_id", "for", "retval", "in", "keyfunc", "(", ...
36.764706
0.000519
def run(): """Execute the Cauldron container command""" command = sys.argv[1].strip().lower() print('[COMMAND]:', command) if command == 'test': return run_test() elif command == 'build': return run_build() elif command == 'up': return run_container() elif command =...
[ "def", "run", "(", ")", ":", "command", "=", "sys", ".", "argv", "[", "1", "]", ".", "strip", "(", ")", ".", "lower", "(", ")", "print", "(", "'[COMMAND]:'", ",", "command", ")", "if", "command", "==", "'test'", ":", "return", "run_test", "(", ")...
26.133333
0.002463
def _strongly_connected_subgraph(counts, weight=1, verbose=True): """Trim a transition count matrix down to its maximal strongly ergodic subgraph. From the counts matrix, we define a graph where there exists a directed edge between two nodes, `i` and `j` if `counts[i][j] > weight`. We then find the...
[ "def", "_strongly_connected_subgraph", "(", "counts", ",", "weight", "=", "1", ",", "verbose", "=", "True", ")", ":", "n_states_input", "=", "counts", ".", "shape", "[", "0", "]", "n_components", ",", "component_assignments", "=", "csgraph", ".", "connected_co...
43.308824
0.00166
def process( hw_num: int, problems_to_do: Optional[Iterable[int]] = None, prefix: Optional[Path] = None, by_hand: Optional[Iterable[int]] = None, ) -> None: """Process the homework problems in ``prefix`` folder. Arguments --------- hw_num The number of this homework problems...
[ "def", "process", "(", "hw_num", ":", "int", ",", "problems_to_do", ":", "Optional", "[", "Iterable", "[", "int", "]", "]", "=", "None", ",", "prefix", ":", "Optional", "[", "Path", "]", "=", "None", ",", "by_hand", ":", "Optional", "[", "Iterable", ...
36.030303
0.001364
def weighted_1d_gaussian_kde(x, samples, weights): """Gaussian kde with weighted samples (1d only). Uses Scott bandwidth factor. When all the sample weights are equal, this is equivalent to kde = scipy.stats.gaussian_kde(theta) return kde(x) When the weights are not all equal, we compute the ...
[ "def", "weighted_1d_gaussian_kde", "(", "x", ",", "samples", ",", "weights", ")", ":", "assert", "x", ".", "ndim", "==", "1", "assert", "samples", ".", "ndim", "==", "1", "assert", "samples", ".", "shape", "==", "weights", ".", "shape", "# normalise weight...
35.929825
0.000475
def extant_item(arg, arg_type): """Determine if parser argument is an existing file or directory. This technique comes from http://stackoverflow.com/a/11541450/95592 and from http://stackoverflow.com/a/11541495/95592 Args: arg: parser argument containing filename to be checked arg_type...
[ "def", "extant_item", "(", "arg", ",", "arg_type", ")", ":", "if", "arg_type", "==", "\"file\"", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "arg", ")", ":", "raise", "argparse", ".", "ArgumentError", "(", "None", ",", "\"The file {arg} does...
33.25
0.000913
def get_paths(self, user_ids=None, startup_ids=None, direction=None): """ user_ids: paths between you and these users startup_ids: paths between you and these startups direction: 'following' or 'followed' """ if user_ids is None and startup_ids is None and direction is None: raise Exceptio...
[ "def", "get_paths", "(", "self", ",", "user_ids", "=", "None", ",", "startup_ids", "=", "None", ",", "direction", "=", "None", ")", ":", "if", "user_ids", "is", "None", "and", "startup_ids", "is", "None", "and", "direction", "is", "None", ":", "raise", ...
47.25
0.011236
def coordinator_dead(self, error): """Mark the current coordinator as dead.""" if self.coordinator_id is not None: log.warning("Marking the coordinator dead (node %s) for group %s: %s.", self.coordinator_id, self.group_id, error) self.coordinator_id = None
[ "def", "coordinator_dead", "(", "self", ",", "error", ")", ":", "if", "self", ".", "coordinator_id", "is", "not", "None", ":", "log", ".", "warning", "(", "\"Marking the coordinator dead (node %s) for group %s: %s.\"", ",", "self", ".", "coordinator_id", ",", "sel...
52.5
0.009375
def ungeometrize_shapes(geo_shapes) -> DataFrame: """ The inverse of :func:`geometrize_shapes`. Produces the columns: - ``'shape_id'`` - ``'shape_pt_sequence'`` - ``'shape_pt_lon'`` - ``'shape_pt_lat'`` If ``geo_shapes`` is in UTM coordinates (has a UTM CRS property), then convert ...
[ "def", "ungeometrize_shapes", "(", "geo_shapes", ")", "->", "DataFrame", ":", "geo_shapes", "=", "geo_shapes", ".", "to_crs", "(", "cs", ".", "WGS84", ")", "F", "=", "[", "]", "for", "index", ",", "row", "in", "geo_shapes", ".", "iterrows", "(", ")", "...
24.911765
0.001136
def crypto_pwhash_str_alg(passwd, opslimit, memlimit, alg): """ Derive a cryptographic key using the ``passwd`` given as input and a random ``salt``, returning a string representation which includes the salt, the tuning parameters and the used algorithm. :param passwd: The input password :type ...
[ "def", "crypto_pwhash_str_alg", "(", "passwd", ",", "opslimit", ",", "memlimit", ",", "alg", ")", ":", "ensure", "(", "isinstance", "(", "opslimit", ",", "integer_types", ")", ",", "raising", "=", "TypeError", ")", "ensure", "(", "isinstance", "(", "memlimit...
32.171429
0.000862
def http_signature(message, key_id, signature): """Return a tuple (message signature, HTTP header message signature).""" template = ('Signature keyId="%(keyId)s",algorithm="hmac-sha256",' 'headers="%(headers)s",signature="%(signature)s"') headers = ['(request-target)', 'host', 'accept', 'dat...
[ "def", "http_signature", "(", "message", ",", "key_id", ",", "signature", ")", ":", "template", "=", "(", "'Signature keyId=\"%(keyId)s\",algorithm=\"hmac-sha256\",'", "'headers=\"%(headers)s\",signature=\"%(signature)s\"'", ")", "headers", "=", "[", "'(request-target)'", ","...
43.9
0.002232
def _ExtractDataFromShowHtml(self, html): """ Extracts csv show data from epguides html source. Parameters ---------- html : string Block of html text Returns ---------- string Show data extracted from html text in csv format. """ htmlLines = html.splitline...
[ "def", "_ExtractDataFromShowHtml", "(", "self", ",", "html", ")", ":", "htmlLines", "=", "html", ".", "splitlines", "(", ")", "for", "count", ",", "line", "in", "enumerate", "(", "htmlLines", ")", ":", "if", "line", ".", "strip", "(", ")", "==", "r'<pr...
25.37037
0.012658
def com_google_fonts_check_metadata_parses(family_directory): """ Check METADATA.pb parse correctly. """ from google.protobuf import text_format from fontbakery.utils import get_FamilyProto_Message try: pb_file = os.path.join(family_directory, "METADATA.pb") get_FamilyProto_Message(pb_file) yield PA...
[ "def", "com_google_fonts_check_metadata_parses", "(", "family_directory", ")", ":", "from", "google", ".", "protobuf", "import", "text_format", "from", "fontbakery", ".", "utils", "import", "get_FamilyProto_Message", "try", ":", "pb_file", "=", "os", ".", "path", "....
46.615385
0.012945
def get_callable_fq_for_code(code, locals_dict = None): """Determines the function belonging to a given code object in a fully qualified fashion. Returns a tuple consisting of - the callable - a list of classes and inner classes, locating the callable (like a fully qualified name) - a boolean indica...
[ "def", "get_callable_fq_for_code", "(", "code", ",", "locals_dict", "=", "None", ")", ":", "if", "code", "in", "_code_callable_dict", ":", "res", "=", "_code_callable_dict", "[", "code", "]", "if", "not", "res", "[", "0", "]", "is", "None", "or", "locals_d...
41.782609
0.009156
def vectorize_utterance(self, utterance): """ Take in a tokenized utterance and transform it into a sequence of indices """ for i, word in enumerate(utterance): if not word in self.vocab_list: utterance[i] = '<unk>' return self.swap_pad_and_zero(self....
[ "def", "vectorize_utterance", "(", "self", ",", "utterance", ")", ":", "for", "i", ",", "word", "in", "enumerate", "(", "utterance", ")", ":", "if", "not", "word", "in", "self", ".", "vocab_list", ":", "utterance", "[", "i", "]", "=", "'<unk>'", "retur...
37.333333
0.011628
def template(tem, queue=False, **kwargs): ''' Execute the information stored in a template file on the minion. This function does not ask a master for a SLS file to render but instead directly processes the file at the provided path on the minion. CLI Example: .. code-block:: bash sa...
[ "def", "template", "(", "tem", ",", "queue", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "'env'", "in", "kwargs", ":", "# \"env\" is not supported; Use \"saltenv\".", "kwargs", ".", "pop", "(", "'env'", ")", "conflict", "=", "_check_queue", "(", ...
36.34
0.001072
def GetArtifactPathDependencies(rdf_artifact): """Return a set of knowledgebase path dependencies. Args: rdf_artifact: RDF artifact object. Returns: A set of strings for the required kb objects e.g. ["users.appdata", "systemroot"] """ deps = set() for source in rdf_artifact.sources: for ar...
[ "def", "GetArtifactPathDependencies", "(", "rdf_artifact", ")", ":", "deps", "=", "set", "(", ")", "for", "source", "in", "rdf_artifact", ".", "sources", ":", "for", "arg", ",", "value", "in", "iteritems", "(", "source", ".", "attributes", ")", ":", "paths...
34.115385
0.013158
def _split_line(s, parts): """ Parameters ---------- s: string Fixed-length string to split parts: list of (name, length) pairs Used to break up string, name '_' will be filtered from output. Returns ------- Dict of name:contents of string at given location. """ ...
[ "def", "_split_line", "(", "s", ",", "parts", ")", ":", "out", "=", "{", "}", "start", "=", "0", "for", "name", ",", "length", "in", "parts", ":", "out", "[", "name", "]", "=", "s", "[", "start", ":", "start", "+", "length", "]", ".", "strip", ...
23.1
0.002079
def analysis_search(self, query): """ Lists the webids of the analyses that match the given query. Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id. """ response = self._post(self.apiurl + "/v2/analysis/search", data={'apikey': self.apikey, 'q':...
[ "def", "analysis_search", "(", "self", ",", "query", ")", ":", "response", "=", "self", ".", "_post", "(", "self", ".", "apiurl", "+", "\"/v2/analysis/search\"", ",", "data", "=", "{", "'apikey'", ":", "self", ".", "apikey", ",", "'q'", ":", "query", "...
41
0.01061
def do_down(self, arg): """Run down migration with name or numeric id matching arg""" print "running down migration" self.manager.run_one(arg, Direction.DOWN)
[ "def", "do_down", "(", "self", ",", "arg", ")", ":", "print", "\"running down migration\"", "self", ".", "manager", ".", "run_one", "(", "arg", ",", "Direction", ".", "DOWN", ")" ]
44.75
0.010989
def phi_vector(self): """property decorated method to get a vector of L2 norm (phi) for the realizations. The ObservationEnsemble.pst.weights can be updated prior to calling this method to evaluate new weighting strategies Return ------ pandas.DataFrame : pandas.DataFra...
[ "def", "phi_vector", "(", "self", ")", ":", "weights", "=", "self", ".", "pst", ".", "observation_data", ".", "loc", "[", "self", ".", "names", ",", "\"weight\"", "]", "obsval", "=", "self", ".", "pst", ".", "observation_data", ".", "loc", "[", "self",...
40.473684
0.010165
def save(self, *args, **kwargs): """ Custom save does the following: * determine link type if not specified * automatically fill 'node_a' and 'node_b' fields if necessary * draw line between two nodes * fill shortcut properties node_a_name and node_b_name ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "type", ":", "if", "self", ".", "interface_a", ".", "type", "==", "INTERFACE_TYPES", ".", "get", "(", "'wireless'", ")", ":", "self", ".", ...
40.888889
0.001327
def sorted_query_paths(self): """ RETURN A LIST OF ALL SCHEMA'S IN DEPTH-FIRST TOPOLOGICAL ORDER """ return list(reversed(sorted(p[0] for p in self.namespace.alias_to_query_paths.get(self.name))))
[ "def", "sorted_query_paths", "(", "self", ")", ":", "return", "list", "(", "reversed", "(", "sorted", "(", "p", "[", "0", "]", "for", "p", "in", "self", ".", "namespace", ".", "alias_to_query_paths", ".", "get", "(", "self", ".", "name", ")", ")", ")...
44.8
0.013158
def strengths_und_sign(W): ''' Node strength is the sum of weights of links connected to the node. Parameters ---------- W : NxN np.ndarray undirected connection matrix with positive and negative weights Returns ------- Spos : Nx1 np.ndarray nodal strength of positive w...
[ "def", "strengths_und_sign", "(", "W", ")", ":", "W", "=", "W", ".", "copy", "(", ")", "n", "=", "len", "(", "W", ")", "np", ".", "fill_diagonal", "(", "W", ",", "0", ")", "# clear diagonal", "Spos", "=", "np", ".", "sum", "(", "W", "*", "(", ...
27.448276
0.002427
def get_crawler(self, crawler, url): """ Checks if a crawler supports a website (the website offers e.g. RSS or sitemap) and falls back to the fallbacks defined in the config if the site is not supported. :param str crawler: Crawler-string (from the crawler-module) :para...
[ "def", "get_crawler", "(", "self", ",", "crawler", ",", "url", ")", ":", "checked_crawlers", "=", "[", "]", "while", "crawler", "is", "not", "None", "and", "crawler", "not", "in", "checked_crawlers", ":", "checked_crawlers", ".", "append", "(", "crawler", ...
51.72973
0.002051
def retry(exception_to_check, tries=5, delay=5, multiplier=2): '''Tries to call the wrapped function again, after an incremental delay :param exception_to_check: Exception(s) to check for, before retrying. :type exception_to_check: Exception :param tries: Number of time to retry before failling. :t...
[ "def", "retry", "(", "exception_to_check", ",", "tries", "=", "5", ",", "delay", "=", "5", ",", "multiplier", "=", "2", ")", ":", "def", "deco_retry", "(", "func", ")", ":", "'''Creates the retry decorator'''", "@", "wraps", "(", "func", ")", "def", "fun...
35.825
0.000679
def select_next(self): """ Selects the next occurrence. :return: True in case of success, false if no occurrence could be selected. """ current_occurence = self._current_occurrence() occurrences = self.get_occurences() if not occurrences: ...
[ "def", "select_next", "(", "self", ")", ":", "current_occurence", "=", "self", ".", "_current_occurrence", "(", ")", "occurrences", "=", "self", ".", "get_occurences", "(", ")", "if", "not", "occurrences", ":", "return", "current", "=", "self", ".", "_occurr...
38.675676
0.001363
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the string abbreviation of the team, such as 'KAN'. """ fields_to_include = { 'abbreviation': self.abbreviation, 'd...
[ "def", "dataframe", "(", "self", ")", ":", "fields_to_include", "=", "{", "'abbreviation'", ":", "self", ".", "abbreviation", ",", "'defensive_simple_rating_system'", ":", "self", ".", "defensive_simple_rating_system", ",", "'first_downs'", ":", "self", ".", "first_...
46.461538
0.000811
def run(self, inputs): """Run many steps of the simulation. The argument is a list of input mappings for each step, and its length is the number of steps to be executed. """ steps = len(inputs) # create i/o arrays of the appropriate length ibuf_type = ctypes.c_ui...
[ "def", "run", "(", "self", ",", "inputs", ")", ":", "steps", "=", "len", "(", "inputs", ")", "# create i/o arrays of the appropriate length", "ibuf_type", "=", "ctypes", ".", "c_uint64", "*", "(", "steps", "*", "self", ".", "_ibufsz", ")", "obuf_type", "=", ...
37.603448
0.000894
def exponentialMovingAverage(requestContext, seriesList, windowSize): """ Takes a series of values and a window size and produces an exponential moving average utilizing the following formula: ema(current) = constant * (Current Value) + (1 - constant) * ema(previous) The Constant is calculated as:...
[ "def", "exponentialMovingAverage", "(", "requestContext", ",", "seriesList", ",", "windowSize", ")", ":", "# EMA = C * (current_value) + (1 - C) + EMA", "# C = 2 / (windowSize + 1)", "# The following was copied from movingAverage, and altered for ema", "if", "not", "seriesList", ":",...
34.506024
0.000339
def noise3d(self, x, y, z): """ Generate 3D OpenSimplex noise from X,Y,Z coordinates. """ # Place input coordinates on simplectic honeycomb. stretch_offset = (x + y + z) * STRETCH_CONSTANT_3D xs = x + stretch_offset ys = y + stretch_offset zs = z + stretch...
[ "def", "noise3d", "(", "self", ",", "x", ",", "y", ",", "z", ")", ":", "# Place input coordinates on simplectic honeycomb.", "stretch_offset", "=", "(", "x", "+", "y", "+", "z", ")", "*", "STRETCH_CONSTANT_3D", "xs", "=", "x", "+", "stretch_offset", "ys", ...
41.172065
0.002448
def is_scipy_sparse(arr): """ Check whether an array-like is a scipy.sparse.spmatrix instance. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a scipy.sparse.spmatrix instance. Notes -----...
[ "def", "is_scipy_sparse", "(", "arr", ")", ":", "global", "_is_scipy_sparse", "if", "_is_scipy_sparse", "is", "None", ":", "try", ":", "from", "scipy", ".", "sparse", "import", "issparse", "as", "_is_scipy_sparse", "except", "ImportError", ":", "_is_scipy_sparse",...
22.710526
0.002222
def _init_attr_config(attr_cfg): """Helper function to initialize attribute config objects""" attr_cfg.name = '' attr_cfg.writable = AttrWriteType.READ attr_cfg.data_format = AttrDataFormat.SCALAR attr_cfg.data_type = 0 attr_cfg.max_dim_x = 0 attr_cfg.max_dim_y = 0 attr_cfg.description =...
[ "def", "_init_attr_config", "(", "attr_cfg", ")", ":", "attr_cfg", ".", "name", "=", "''", "attr_cfg", ".", "writable", "=", "AttrWriteType", ".", "READ", "attr_cfg", ".", "data_format", "=", "AttrDataFormat", ".", "SCALAR", "attr_cfg", ".", "data_type", "=", ...
31.277778
0.001724
def _position_for_aspirate(self, location=None, clearance=1.0): """ Position this :any:`Pipette` for an aspiration, given it's current state """ placeable = None if location: placeable, _ = unpack_location(location) # go to top of source, if not a...
[ "def", "_position_for_aspirate", "(", "self", ",", "location", "=", "None", ",", "clearance", "=", "1.0", ")", ":", "placeable", "=", "None", "if", "location", ":", "placeable", ",", "_", "=", "unpack_location", "(", "location", ")", "# go to top of source, if...
40.2
0.001388
def build_gtapp(appname, dry_run, **kwargs): """Build an object that can run ScienceTools application Parameters ---------- appname : str Name of the application (e.g., gtbin) dry_run : bool Print command but do not run it kwargs : arguments used to invoke the application ...
[ "def", "build_gtapp", "(", "appname", ",", "dry_run", ",", "*", "*", "kwargs", ")", ":", "pfiles_orig", "=", "_set_pfiles", "(", "dry_run", ",", "*", "*", "kwargs", ")", "gtapp", "=", "GtApp", ".", "GtApp", "(", "appname", ")", "update_gtapp", "(", "gt...
27.2
0.001776
def _gen_md5_filehash(fname, *args): ''' helper function to generate a md5 hash of the swagger definition file any extra argument passed to the function is converted to a string and participates in the hash calculation ''' _hash = hashlib.md5() with salt.utils.files.fopen(fname, 'rb') as f: ...
[ "def", "_gen_md5_filehash", "(", "fname", ",", "*", "args", ")", ":", "_hash", "=", "hashlib", ".", "md5", "(", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "fname", ",", "'rb'", ")", "as", "f", ":", "for", "chunk", "in", "...
35.214286
0.001976
def gen_scripts( file_name, file_name_ext, obj_name, obj_ext_name, output, output_ext, field=1, notexplicit=None, ascii_props=False, append=False, prefix="" ): """Generate `script` property.""" obj = {} obj2 = {} aliases = {} with codecs.open(os.path.join(HOME, 'unicodedata', UNIVERSION, 'P...
[ "def", "gen_scripts", "(", "file_name", ",", "file_name_ext", ",", "obj_name", ",", "obj_ext_name", ",", "output", ",", "output_ext", ",", "field", "=", "1", ",", "notexplicit", "=", "None", ",", "ascii_props", "=", "False", ",", "append", "=", "False", ",...
35.136842
0.002331
def save(self): """ Save environment settings into environment directory, overwriting any existing configuration and discarding site config """ task.save_new_environment(self.name, self.datadir, self.target, self.ckan_version, self.deploy_target, self.always_prod)
[ "def", "save", "(", "self", ")", ":", "task", ".", "save_new_environment", "(", "self", ".", "name", ",", "self", ".", "datadir", ",", "self", ".", "target", ",", "self", ".", "ckan_version", ",", "self", ".", "deploy_target", ",", "self", ".", "always...
44.285714
0.009494
def sendLocalImage( self, image_path, message=None, thread_id=None, thread_type=ThreadType.USER ): """ Deprecated. Use :func:`fbchat.Client.sendLocalFiles` instead """ return self.sendLocalFiles( file_paths=[image_path], message=message, th...
[ "def", "sendLocalImage", "(", "self", ",", "image_path", ",", "message", "=", "None", ",", "thread_id", "=", "None", ",", "thread_type", "=", "ThreadType", ".", "USER", ")", ":", "return", "self", ".", "sendLocalFiles", "(", "file_paths", "=", "[", "image_...
31.166667
0.01039
async def close(self): """Close pyodbc connection""" if not self._conn: return c = await self._execute(self._conn.close) self._conn = None return c
[ "async", "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_conn", ":", "return", "c", "=", "await", "self", ".", "_execute", "(", "self", ".", "_conn", ".", "close", ")", "self", ".", "_conn", "=", "None", "return", "c" ]
27.571429
0.01005
def update(self, pointvol): """Update the N-sphere radii using the current set of live points.""" # Initialize a K-D Tree to assist nearest neighbor searches. if self.use_kdtree: kdtree = spatial.KDTree(self.live_u) else: kdtree = None # Check if we shou...
[ "def", "update", "(", "self", ",", "pointvol", ")", ":", "# Initialize a K-D Tree to assist nearest neighbor searches.", "if", "self", ".", "use_kdtree", ":", "kdtree", "=", "spatial", ".", "KDTree", "(", "self", ".", "live_u", ")", "else", ":", "kdtree", "=", ...
36.083333
0.00225
def parse_source_file(source_file): """Parses a source file thing and returns the file name Example: >>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06') 'js/src/jit/MIR.h' :arg str source_file: the source file ("file") from a stack frame :returns: the fil...
[ "def", "parse_source_file", "(", "source_file", ")", ":", "if", "not", "source_file", ":", "return", "None", "vcsinfo", "=", "source_file", ".", "split", "(", "':'", ")", "if", "len", "(", "vcsinfo", ")", "==", "4", ":", "# These are repositories or cloud file...
30
0.001899
def phisheye(self, query, days_back=None, **kwargs): """Returns domain results for the specified term for today or the specified number of days_back. Terms must be setup for monitoring via the web interface: https://research.domaintools.com/phisheye. NOTE: Properties of a domain are only ...
[ "def", "phisheye", "(", "self", ",", "query", ",", "days_back", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_results", "(", "'phisheye'", ",", "'/v1/phisheye'", ",", "query", "=", "query", ",", "days_back", "=", "days_back", ...
72.6
0.010884
def _create_pipeline_command(self, args, workdir_path, config_path): """ Creates and returns a list that represents a command for running the pipeline. """ return ([self._name, 'run', os.path.join(workdir_path, 'jobStore'), '--config', config_path, '--wo...
[ "def", "_create_pipeline_command", "(", "self", ",", "args", ",", "workdir_path", ",", "config_path", ")", ":", "return", "(", "[", "self", ".", "_name", ",", "'run'", ",", "os", ".", "path", ".", "join", "(", "workdir_path", ",", "'jobStore'", ")", ",",...
51.875
0.009479
def update_all(recommended=False, restart=True): ''' Install all available updates. Returns a dictionary containing the name of the update and the status of its installation. :param bool recommended: If set to True, only install the recommended updates. If set to False (default) all updates are...
[ "def", "update_all", "(", "recommended", "=", "False", ",", "restart", "=", "True", ")", ":", "to_update", "=", "_get_available", "(", "recommended", ",", "restart", ")", "if", "not", "to_update", ":", "return", "{", "}", "for", "_update", "in", "to_update...
28.820513
0.001721
def get_magic_guesses(fullpath): """ Return all the possible guesses from the magic library about the content of the file. @param fullpath: location of the file @type fullpath: string @return: guesses about content of the file @rtype: tuple """ if CFG_HAS_MAGIC == 1: magic_c...
[ "def", "get_magic_guesses", "(", "fullpath", ")", ":", "if", "CFG_HAS_MAGIC", "==", "1", ":", "magic_cookies", "=", "_get_magic_cookies", "(", ")", "magic_result", "=", "[", "]", "for", "key", "in", "magic_cookies", ".", "keys", "(", ")", ":", "magic_result"...
36.217391
0.00117
def openFile(filename, mode="r", create_dir=False): '''open file in *filename* with mode *mode*. If *create* is set, the directory containing filename will be created if it does not exist. gzip - compressed files are recognized by the suffix ``.gz`` and opened transparently. Note that there a...
[ "def", "openFile", "(", "filename", ",", "mode", "=", "\"r\"", ",", "create_dir", "=", "False", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "create_dir", ":", "dirname", "=", "os", ".", "path", "....
33.205128
0.00075
def set_config(config): """Set bigchaindb.config equal to the default config dict, then update that with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default co...
[ "def", "set_config", "(", "config", ")", ":", "# Deep copy the default config into bigchaindb.config", "bigchaindb", ".", "config", "=", "copy", ".", "deepcopy", "(", "bigchaindb", ".", "_config", ")", "# Update the default config with whatever is in the passed config", "upda...
41.176471
0.001397
def launch(url, wait=False, locate=False): """This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0...
[ "def", "launch", "(", "url", ",", "wait", "=", "False", ",", "locate", "=", "False", ")", ":", "from", ".", "_termui_impl", "import", "open_url", "return", "open_url", "(", "url", ",", "wait", "=", "wait", ",", "locate", "=", "locate", ")" ]
42.125
0.000967
def show(ctx, component): """Show the stored, active configuration of a component.""" col = ctx.obj['col'] if col.count({'name': component}) > 1: log('More than one component configuration of this name! Try ' 'one of the uuids as argument. Get a list with "config ' 'list"')...
[ "def", "show", "(", "ctx", ",", "component", ")", ":", "col", "=", "ctx", ".", "obj", "[", "'col'", "]", "if", "col", ".", "count", "(", "{", "'name'", ":", "component", "}", ")", ">", "1", ":", "log", "(", "'More than one component configuration of th...
32.464286
0.001068
def from_entrypoint_output(json_encoder, handler_output): """Given a handler output's type, generates a response towards the processor""" response = { 'body': '', 'content_type': 'text/plain', 'headers': {}, 'status_code': 200, 'body_e...
[ "def", "from_entrypoint_output", "(", "json_encoder", ",", "handler_output", ")", ":", "response", "=", "{", "'body'", ":", "''", ",", "'content_type'", ":", "'text/plain'", ",", "'headers'", ":", "{", "}", ",", "'status_code'", ":", "200", ",", "'body_encodin...
40.52
0.001928
def step_a_file_named_filename_and_encoding_with(context, filename, encoding): """Creates a textual file with the content provided as docstring.""" __encoding_is_valid = True assert context.text is not None, "ENSURE: multiline text is provided." assert not os.path.isabs(filename) assert __encoding_i...
[ "def", "step_a_file_named_filename_and_encoding_with", "(", "context", ",", "filename", ",", "encoding", ")", ":", "__encoding_is_valid", "=", "True", "assert", "context", ".", "text", "is", "not", "None", ",", "\"ENSURE: multiline text is provided.\"", "assert", "not",...
55.666667
0.001965
def register_listener(self, member_uuid, listener): """ Register a listener for audio group changes of cast uuid. On update will call: listener.added_to_multizone(group_uuid) The cast has been added to group uuid listener.removed_from_multizone(group_uuid) ...
[ "def", "register_listener", "(", "self", ",", "member_uuid", ",", "listener", ")", ":", "member_uuid", "=", "str", "(", "member_uuid", ")", "if", "member_uuid", "not", "in", "self", ".", "_casts", ":", "self", ".", "_casts", "[", "member_uuid", "]", "=", ...
54.764706
0.002112
def make_data(): """creates example data set""" a = { (1,1):.25, (1,2):.15, (1,3):.2, (2,1):.3, (2,2):.3, (2,3):.1, (3,1):.15, (3,2):.65, (3,3):.05, (4,1):.1, (4,2):.05, (4,3):.8 } epsilon = 0.01 I,p = multidict({1:5, 2:6, 3:8, 4:20}) K,LB = multidict({1:....
[ "def", "make_data", "(", ")", ":", "a", "=", "{", "(", "1", ",", "1", ")", ":", ".25", ",", "(", "1", ",", "2", ")", ":", ".15", ",", "(", "1", ",", "3", ")", ":", ".2", ",", "(", "2", ",", "1", ")", ":", ".3", ",", "(", "2", ",", ...
32.272727
0.109589
def convert_to_label_chars(s): """Turn the specified name and value into a valid Google label.""" # We want the results to be user-friendly, not just functional. # So we can't base-64 encode it. # * If upper-case: lower-case it # * If the char is not a standard letter or digit. make it a dash # March ...
[ "def", "convert_to_label_chars", "(", "s", ")", ":", "# We want the results to be user-friendly, not just functional.", "# So we can't base-64 encode it.", "# * If upper-case: lower-case it", "# * If the char is not a standard letter or digit. make it a dash", "# March 2019 note: underscores...
39.08
0.016983
def to_escpos(self): """ converts the current style to an escpos command string """ cmd = '' ordered_cmds = self.cmds.keys() ordered_cmds.sort(lambda x,y: cmp(self.cmds[x]['_order'], self.cmds[y]['_order'])) for style in ordered_cmds: cmd += self.cmds[style][self.get(...
[ "def", "to_escpos", "(", "self", ")", ":", "cmd", "=", "''", "ordered_cmds", "=", "self", ".", "cmds", ".", "keys", "(", ")", "ordered_cmds", ".", "sort", "(", "lambda", "x", ",", "y", ":", "cmp", "(", "self", ".", "cmds", "[", "x", "]", "[", "...
42.375
0.011561
def close(self): """ Close the SExtractor file. """ if self._file: if not(self._file.closed): self._file.close() self.closed = True
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_file", ":", "if", "not", "(", "self", ".", "_file", ".", "closed", ")", ":", "self", ".", "_file", ".", "close", "(", ")", "self", ".", "closed", "=", "True" ]
24
0.01005
def set_mtu(self, name, value=None, default=False, disable=False): """ Configures the interface IP MTU Args: name (string): The interface identifier to apply the interface config to value (integer): The MTU value to set the interface to. Accepted ...
[ "def", "set_mtu", "(", "self", ",", "name", ",", "value", "=", "None", ",", "default", "=", "False", ",", "disable", "=", "False", ")", ":", "if", "value", "is", "not", "None", ":", "value", "=", "int", "(", "value", ")", "if", "not", "68", "<=",...
35.212121
0.001675
def _get_draw_cache_key(self, grid, key, drawn_rect, is_selected): """Returns key for the screen draw cache""" row, col, tab = key cell_attributes = grid.code_array.cell_attributes zoomed_width = drawn_rect.width / self.zoom zoomed_height = drawn_rect.height / self.zoom ...
[ "def", "_get_draw_cache_key", "(", "self", ",", "grid", ",", "key", ",", "drawn_rect", ",", "is_selected", ")", ":", "row", ",", "col", ",", "tab", "=", "key", "cell_attributes", "=", "grid", ".", "code_array", ".", "cell_attributes", "zoomed_width", "=", ...
40.921053
0.001256
def elide_sequence(s, flank=5, elision="..."): """trim a sequence to include the left and right flanking sequences of size `flank`, with the intervening sequence elided by `elision`. >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ") 'ABCDE...VWXYZ' >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", f...
[ "def", "elide_sequence", "(", "s", ",", "flank", "=", "5", ",", "elision", "=", "\"...\"", ")", ":", "elided_sequence_len", "=", "flank", "+", "flank", "+", "len", "(", "elision", ")", "if", "len", "(", "s", ")", "<=", "elided_sequence_len", ":", "retu...
31.04
0.00125
def utc_to_localtime( date_str, fmt="%Y-%m-%d %H:%M:%S", input_fmt="%Y-%m-%dT%H:%M:%SZ"): """ Convert UTC to localtime Reference: - (1) http://www.openarchives.org/OAI/openarchivesprotocol.html#Dates - (2) http://www.w3.org/TR/NOTE-datetime This function works only wi...
[ "def", "utc_to_localtime", "(", "date_str", ",", "fmt", "=", "\"%Y-%m-%d %H:%M:%S\"", ",", "input_fmt", "=", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", ":", "date_struct", "=", "datetime", ".", "strptime", "(", "date_str", ",", "input_fmt", ")", "date_struct", "+=", "timedelt...
32.619048
0.001418
def _trees_feature_weights(clf, X, feature_names, num_targets): """ Return feature weights for a tree or a tree ensemble. """ feature_weights = np.zeros([len(feature_names), num_targets]) if hasattr(clf, 'tree_'): _update_tree_feature_weights(X, feature_names, clf, feature_weights) else: ...
[ "def", "_trees_feature_weights", "(", "clf", ",", "X", ",", "feature_names", ",", "num_targets", ")", ":", "feature_weights", "=", "np", ".", "zeros", "(", "[", "len", "(", "feature_names", ")", ",", "num_targets", "]", ")", "if", "hasattr", "(", "clf", ...
43.307692
0.000869
def check_update(): """ Check for app updates and print/log them. """ logging.info('Check for app updates.') try: update = updater.check_for_app_updates() except Exception: logging.exception('Check for updates failed.') return if update: print("!!! UPDATE AVAI...
[ "def", "check_update", "(", ")", ":", "logging", ".", "info", "(", "'Check for app updates.'", ")", "try", ":", "update", "=", "updater", ".", "check_for_app_updates", "(", ")", "except", "Exception", ":", "logging", ".", "exception", "(", "'Check for updates fa...
30.875
0.001965
def _convert_hashes(values): """Convert Pipfile.lock hash lines into InstallRequirement option format. The option format uses a str-list mapping. Keys are hash algorithms, and the list contains all values of that algorithm. """ hashes = {} if not values: return hashes for value in v...
[ "def", "_convert_hashes", "(", "values", ")", ":", "hashes", "=", "{", "}", "if", "not", "values", ":", "return", "hashes", "for", "value", "in", "values", ":", "try", ":", "name", ",", "value", "=", "value", ".", "split", "(", "\":\"", ",", "1", "...
29.833333
0.001805
def fill_subparser(subparser): """Sets up a subparser to convert the MNIST dataset files. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `mnist` command. """ subparser.add_argument( "--dtype", help="dtype to save to; by default, images...
[ "def", "fill_subparser", "(", "subparser", ")", ":", "subparser", ".", "add_argument", "(", "\"--dtype\"", ",", "help", "=", "\"dtype to save to; by default, images will be \"", "+", "\"returned in their original unsigned byte format\"", ",", "choices", "=", "(", "'float32'...
33.928571
0.002049
def get_tags(filesystemid, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Return the tags associated with an EFS instance. filesystemid (string) - ID of the file system whose tags to list returns (list) -...
[ "def", "get_tags", "(", "filesystemid", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_conn", "(", "key", "=", "key", ",", "keyid"...
26.741935
0.001164
def custom_parser(cards: list, parser: Optional[Callable[[list], Optional[list]]]=None) -> Optional[list]: '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: return parser(cards)
[ "def", "custom_parser", "(", "cards", ":", "list", ",", "parser", ":", "Optional", "[", "Callable", "[", "[", "list", "]", ",", "Optional", "[", "list", "]", "]", "]", "=", "None", ")", "->", "Optional", "[", "list", "]", ":", "if", "not", "parser"...
30.333333
0.014235
def show_images(self, size="small"): """Shows preview images using the Jupyter notebook HTML display. Parameters ========== size : {'small', 'med', 'thumb', 'full'} Determines the size of the preview image to be shown. """ d = dict(small=256, med=512, thumb=1...
[ "def", "show_images", "(", "self", ",", "size", "=", "\"small\"", ")", ":", "d", "=", "dict", "(", "small", "=", "256", ",", "med", "=", "512", ",", "thumb", "=", "100", ",", "full", "=", "1024", ")", "try", ":", "width", "=", "d", "[", "size",...
33.5
0.002418
def participate(self): """Finish reading and send text""" try: logger.info("Entering participate method") ready = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.ID, "finish-reading")) ) stimulus = self.driver.find_elem...
[ "def", "participate", "(", "self", ")", ":", "try", ":", "logger", ".", "info", "(", "\"Entering participate method\"", ")", "ready", "=", "WebDriverWait", "(", "self", ".", "driver", ",", "10", ")", ".", "until", "(", "EC", ".", "element_to_be_clickable", ...
39.25
0.001776
def iter_content(self, chunk_size=1024, decode_unicode=False): """Get request body as iterator content (stream). :param int chunk_size: :param bool decode_unicode: """ return self.response.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode)
[ "def", "iter_content", "(", "self", ",", "chunk_size", "=", "1024", ",", "decode_unicode", "=", "False", ")", ":", "return", "self", ".", "response", ".", "iter_content", "(", "chunk_size", "=", "chunk_size", ",", "decode_unicode", "=", "decode_unicode", ")" ]
41.428571
0.010135
def write_tile_if_changed(store, tile_data, coord, format): """ Only write tile data if different from existing. Try to read the tile data from the store first. If the existing data matches, don't write. Returns whether the tile was written. """ existing_data = store.read_tile(coord, format) ...
[ "def", "write_tile_if_changed", "(", "store", ",", "tile_data", ",", "coord", ",", "format", ")", ":", "existing_data", "=", "store", ".", "read_tile", "(", "coord", ",", "format", ")", "if", "not", "existing_data", "or", "not", "tiles_are_equal", "(", "exis...
33.2
0.001953
def get_next_family(self): """Gets the next ``Family`` in this list. return: (osid.relationship.Family) - the next ``Family`` in this list. The ``has_next()`` method should be used to test that a next ``Family`` is available before calling this method. ...
[ "def", "get_next_family", "(", "self", ")", ":", "try", ":", "next_object", "=", "next", "(", "self", ")", "except", "StopIteration", ":", "raise", "IllegalState", "(", "'no more elements available in this list'", ")", "except", "Exception", ":", "# Need to specify ...
40.4
0.002418
async def send_request(self): """Coroutine to send request headers with metadata to the server. New HTTP/2 stream will be created during this coroutine call. .. note:: This coroutine will be called implicitly during first :py:meth:`send_message` coroutine call, if not called before...
[ "async", "def", "send_request", "(", "self", ")", ":", "if", "self", ".", "_send_request_done", ":", "raise", "ProtocolError", "(", "'Request is already sent'", ")", "with", "self", ".", "_wrapper", ":", "protocol", "=", "await", "self", ".", "_channel", ".", ...
39.891304
0.001064
def exec_cmd(cmd, role, taskid, pass_env): """Execute the command line command.""" if cmd[0].find('/') == -1 and os.path.exists(cmd[0]) and os.name != 'nt': cmd[0] = './' + cmd[0] cmd = ' '.join(cmd) env = os.environ.copy() for k, v in pass_env.items(): env[k] = str(v) env['DMLC...
[ "def", "exec_cmd", "(", "cmd", ",", "role", ",", "taskid", ",", "pass_env", ")", ":", "if", "cmd", "[", "0", "]", ".", "find", "(", "'/'", ")", "==", "-", "1", "and", "os", ".", "path", ".", "exists", "(", "cmd", "[", "0", "]", ")", "and", ...
31.46875
0.000963
def terminate_instances(self, xml_bytes): """Parse the XML returned by the C{TerminateInstances} function. @param xml_bytes: XML bytes with a C{TerminateInstancesResponse} root element. @return: An iterable of C{tuple} of (instanceId, previousState, currentState) for the...
[ "def", "terminate_instances", "(", "self", ",", "xml_bytes", ")", ":", "root", "=", "XML", "(", "xml_bytes", ")", "result", "=", "[", "]", "# May be a more elegant way to do this:", "instances", "=", "root", ".", "find", "(", "\"instancesSet\"", ")", "if", "in...
43.904762
0.002123
def _read_mplain(self, lines): """ Read text fragments from a multilevel format text file. :param list lines: the lines of the subtitles text file """ self.log(u"Parsing fragments from subtitles text format") word_separator = self._mplain_word_separator() self.lo...
[ "def", "_read_mplain", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Parsing fragments from subtitles text format\"", ")", "word_separator", "=", "self", ".", "_mplain_word_separator", "(", ")", "self", ".", "log", "(", "[", "u\"Word separator ...
40.808219
0.000983
def filepaths(path, exclude=(), hidden=True, empty=True): """ Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if p...
[ "def", "filepaths", "(", "path", ",", "exclude", "=", "(", ")", ",", "hidden", "=", "True", ",", "empty", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "error", ".", "PathNotFoundError", "(", ...
34.853659
0.001361
def all_selectors(Class, fn): """return a sorted list of selectors that occur in the stylesheet""" selectors = [] cssparser = cssutils.CSSParser(validate=False) css = cssparser.parseFile(fn) for rule in [r for r in css.cssRules if type(r)==cssutils.css.CSSStyleRule]: ...
[ "def", "all_selectors", "(", "Class", ",", "fn", ")", ":", "selectors", "=", "[", "]", "cssparser", "=", "cssutils", ".", "CSSParser", "(", "validate", "=", "False", ")", "css", "=", "cssparser", ".", "parseFile", "(", "fn", ")", "for", "rule", "in", ...
50.444444
0.008658
def from_bulk_and_miller(cls, structure, miller_index, min_slab_size=8.0, min_vacuum_size=10.0, max_normal_search=None, center_slab=True, selective_dynamics=False, undercoord_threshold=0.09): """ This method construct...
[ "def", "from_bulk_and_miller", "(", "cls", ",", "structure", ",", "miller_index", ",", "min_slab_size", "=", "8.0", ",", "min_vacuum_size", "=", "10.0", ",", "max_normal_search", "=", "None", ",", "center_slab", "=", "True", ",", "selective_dynamics", "=", "Fals...
52.34375
0.001758
def _extract_ajax_endpoints(self): ''' make a GET request to freeproxylists.com/elite.html ''' url = '/'.join([DOC_ROOT, ELITE_PAGE]) response = requests.get(url) ''' extract the raw HTML doc from the response ''' raw_html = response.text ''' convert raw ht...
[ "def", "_extract_ajax_endpoints", "(", "self", ")", ":", "url", "=", "'/'", ".", "join", "(", "[", "DOC_ROOT", ",", "ELITE_PAGE", "]", ")", "response", "=", "requests", ".", "get", "(", "url", ")", "''' extract the raw HTML doc from the response '''", "raw_html"...
38
0.010274
def validate(message, gpg_home=None, **config): """ Return true or false if the message is signed appropriately. Two things must be true: 1) The signature must be valid (obviously) 2) The signing key must be in the local keyring as defined by the `gpg_home` config value. """ ...
[ "def", "validate", "(", "message", ",", "gpg_home", "=", "None", ",", "*", "*", "config", ")", ":", "if", "gpg_home", "is", "None", ":", "raise", "ValueError", "(", "\"You must set the gpg_home keyword argument.\"", ")", "try", ":", "_ctx", ".", "verify", "(...
33.333333
0.001389
def render(gpg_data, saltenv='base', sls='', argline='', **kwargs): ''' Create a gpg object given a gpg_keydir, and then use it to try to decrypt the data to be rendered. ''' if not _get_gpg_exec(): raise SaltRenderError('GPG unavailable') log.debug('Reading GPG keys from: %s', _get_key_...
[ "def", "render", "(", "gpg_data", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "argline", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_get_gpg_exec", "(", ")", ":", "raise", "SaltRenderError", "(", "'GPG unavailable'", ")"...
41.636364
0.002137
def identify_and_tag_collaborations(line, collaborations_kb): """Given a line where Authors have been tagged, and all other tags and content has been replaced with underscores, go through and try to identify extra items of data which should be placed into 'h' subfields. Later on, these t...
[ "def", "identify_and_tag_collaborations", "(", "line", ",", "collaborations_kb", ")", ":", "for", "dummy_collab", ",", "re_collab", "in", "collaborations_kb", ".", "iteritems", "(", ")", ":", "matches", "=", "re_collab", ".", "finditer", "(", "strip_tags", "(", ...
48.863636
0.000912
def load_soups(config): """Generate BeautifulSoup AST for each page listed in config.""" soups = {} for page, path in config['sources'].items(): with open(path, 'r') as orig_file: soups[page] = beautiful_soup(orig_file.read(), features='html.parser') return soups
[ "def", "load_soups", "(", "config", ")", ":", "soups", "=", "{", "}", "for", "page", ",", "path", "in", "config", "[", "'sources'", "]", ".", "items", "(", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "orig_file", ":", "soups", "...
39.285714
0.021352
def fit_results_to_dict(fit_results, min_bound=None, max_bound=None): '''Create a JSON-comparable dict from a FitResults object Parameters: fit_results (FitResults): object containing fit parameters,\ errors and type min_bound: optional min value to add to dictionary if min isn't\ ...
[ "def", "fit_results_to_dict", "(", "fit_results", ",", "min_bound", "=", "None", ",", "max_bound", "=", "None", ")", ":", "type_map", "=", "{", "'norm'", ":", "'normal'", ",", "'expon'", ":", "'exponential'", ",", "'uniform'", ":", "'uniform'", "}", "param_m...
35.59375
0.000855
def buffer(self, geometries, inSR, distances, units, outSR=None, bufferSR=None, unionResults=True, geodesic=True ): """ The buffer operation is performed on a geometr...
[ "def", "buffer", "(", "self", ",", "geometries", ",", "inSR", ",", "distances", ",", "units", ",", "outSR", "=", "None", ",", "bufferSR", "=", "None", ",", "unionResults", "=", "True", ",", "geodesic", "=", "True", ")", ":", "url", "=", "self", ".", ...
46.4
0.010714
def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): cache = caches[cache_name] result = cache.get(cache_key) if...
[ "def", "cache_result", "(", "cache_key", ",", "timeout", ")", ":", "def", "decorator", "(", "f", ")", ":", "cache_name", "=", "settings", ".", "WAFER_CACHE", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", ...
29.666667
0.001555
def replies(self, tweet, recursive=False, prune=()): """ replies returns a generator of tweets that are replies for a given tweet. It includes the original tweet. If you would like to fetch the replies to the replies use recursive=True which will do a depth-first recursive walk o...
[ "def", "replies", "(", "self", ",", "tweet", ",", "recursive", "=", "False", ",", "prune", "=", "(", ")", ")", ":", "yield", "tweet", "# get replies to the tweet", "screen_name", "=", "tweet", "[", "'user'", "]", "[", "'screen_name'", "]", "tweet_id", "=",...
39.5
0.000823
def get(method, hmc, uri, uri_parms, logon_required): """Operation: List Virtual Switches of a CPC (empty result if not in DPM mode).""" cpc_oid = uri_parms[0] query_str = uri_parms[1] try: cpc = hmc.cpcs.lookup_by_oid(cpc_oid) except KeyError: rai...
[ "def", "get", "(", "method", ",", "hmc", ",", "uri", ",", "uri_parms", ",", "logon_required", ")", ":", "cpc_oid", "=", "uri_parms", "[", "0", "]", "query_str", "=", "uri_parms", "[", "1", "]", "try", ":", "cpc", "=", "hmc", ".", "cpcs", ".", "look...
45.263158
0.002278
def masked(a, b): """Return a numpy array with values from a where elements in b are not False. Populate with numpy.nan where b is False. When plotting, those elements look like missing, which can be a desired result. """ if np.any([a.dtype.kind.startswith(c) for c in ['i', 'u', 'f', 'c']]): ...
[ "def", "masked", "(", "a", ",", "b", ")", ":", "if", "np", ".", "any", "(", "[", "a", ".", "dtype", ".", "kind", ".", "startswith", "(", "c", ")", "for", "c", "in", "[", "'i'", ",", "'u'", ",", "'f'", ",", "'c'", "]", "]", ")", ":", "n", ...
36.769231
0.002041
def ported_string(raw_data, encoding='utf-8', errors='ignore'): """ Give as input raw data and output a str in Python 3 and unicode in Python 2. Args: raw_data: Python 2 str, Python 3 bytes or str to porting encoding: string giving the name of an encoding errors: his specifies t...
[ "def", "ported_string", "(", "raw_data", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'ignore'", ")", ":", "if", "not", "raw_data", ":", "return", "six", ".", "text_type", "(", ")", "if", "isinstance", "(", "raw_data", ",", "six", ".", "text_typ...
30.25
0.001001
def postcode(self): """ :example '101-1212' """ return "%03d-%04d" % (self.generator.random.randint(0, 999), self.generator.random.randint(0, 9999))
[ "def", "postcode", "(", "self", ")", ":", "return", "\"%03d-%04d\"", "%", "(", "self", ".", "generator", ".", "random", ".", "randint", "(", "0", ",", "999", ")", ",", "self", ".", "generator", ".", "random", ".", "randint", "(", "0", ",", "9999", ...
34.166667
0.009524
def _braket_fmt(self, expr_type): """Return a format string for printing an `expr_type` ket/bra/ketbra/braket""" mapping = { 'bra': { True: '<{label}|^({space})', 'subscript': '<{label}|_({space})', False: '<{label}|'}, 'ke...
[ "def", "_braket_fmt", "(", "self", ",", "expr_type", ")", ":", "mapping", "=", "{", "'bra'", ":", "{", "True", ":", "'<{label}|^({space})'", ",", "'subscript'", ":", "'<{label}|_({space})'", ",", "False", ":", "'<{label}|'", "}", ",", "'ket'", ":", "{", "T...
41.6
0.00188
def cap_list(caps): """Given a cap string, return a list of cap, value.""" out = [] caps = caps.split() for cap in caps: # turn modifier chars into named modifiers mods = [] while len(cap) > 0 and cap[0] in cap_modifiers: attr = cap[0] cap = cap[1:] ...
[ "def", "cap_list", "(", "caps", ")", ":", "out", "=", "[", "]", "caps", "=", "caps", ".", "split", "(", ")", "for", "cap", "in", "caps", ":", "# turn modifier chars into named modifiers", "mods", "=", "[", "]", "while", "len", "(", "cap", ")", ">", "...
25.923077
0.001431
def section(self, section, skip=['type', 'order']): """ Return section items, skip selected (type/order by default) """ return [(key, val) for key, val in self.parser.items(section) if key not in skip]
[ "def", "section", "(", "self", ",", "section", ",", "skip", "=", "[", "'type'", ",", "'order'", "]", ")", ":", "return", "[", "(", "key", ",", "val", ")", "for", "key", ",", "val", "in", "self", ".", "parser", ".", "items", "(", "section", ")", ...
57.5
0.008584
def FD(self): """ Set-up for the finite difference solution method """ if self.Verbose: print("Finite Difference Solution Technique") # Used to check for coeff_matrix here, but now doing so in self.bc_check() # called by f1d and f2d at the start # # Define a stress-based qs = q0 ...
[ "def", "FD", "(", "self", ")", ":", "if", "self", ".", "Verbose", ":", "print", "(", "\"Finite Difference Solution Technique\"", ")", "# Used to check for coeff_matrix here, but now doing so in self.bc_check()", "# called by f1d and f2d at the start", "# ", "# Define a stress-bas...
40.609756
0.015831
def create(input_block: ModelFactory, rnn_type: str, output_dim: int, rnn_layers: typing.List[int], rnn_dropout: float=0.0, bidirectional: bool=False, linear_layers: typing.List[int]=None, linear_dropout: float=0.0): """ Vel factory function """ if linear_layers is None: linear_lay...
[ "def", "create", "(", "input_block", ":", "ModelFactory", ",", "rnn_type", ":", "str", ",", "output_dim", ":", "int", ",", "rnn_layers", ":", "typing", ".", "List", "[", "int", "]", ",", "rnn_dropout", ":", "float", "=", "0.0", ",", "bidirectional", ":",...
46.8
0.01676