text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def reorderbydf(df2,df1): """ Reorder rows of a dataframe by other dataframe :param df2: input dataframe :param df1: template dataframe """ df3=pd.DataFrame() for idx,row in df1.iterrows(): df3=df3.append(df2.loc[idx,:]) return df3
[ "def", "reorderbydf", "(", "df2", ",", "df1", ")", ":", "df3", "=", "pd", ".", "DataFrame", "(", ")", "for", "idx", ",", "row", "in", "df1", ".", "iterrows", "(", ")", ":", "df3", "=", "df3", ".", "append", "(", "df2", ".", "loc", "[", "idx", ...
23.909091
11.909091
def _create_descriptor_from_property_definition(self, class_name, property_definition, class_name_to_definition): """Return a PropertyDescriptor corresponding to the given OrientDB property definition.""" name = property_definition['name'] type...
[ "def", "_create_descriptor_from_property_definition", "(", "self", ",", "class_name", ",", "property_definition", ",", "class_name_to_definition", ")", ":", "name", "=", "property_definition", "[", "'name'", "]", "type_id", "=", "property_definition", "[", "'type'", "]"...
58.869565
32.115942
def save_anonymous_gist(title, files): """ October 21, 2015 title = the gist title files = { 'spam.txt' : { 'content': 'What... is the air-speed velocity of an unladen swallow?' } # ..etc... } works also in blocks eg from https://gist.github.c...
[ "def", "save_anonymous_gist", "(", "title", ",", "files", ")", ":", "try", ":", "from", "github3", "import", "create_gist", "except", ":", "print", "(", "\"github3 library not found (pip install github3)\"", ")", "raise", "SystemExit", "(", "1", ")", "gist", "=", ...
23.184211
23.552632
def sort_flavor_list(request, flavors, with_menu_label=True): """Utility method to sort a list of flavors. By default, returns the available flavors, sorted by RAM usage (ascending). Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict in ``local_settings.py``. """ def get_key(...
[ "def", "sort_flavor_list", "(", "request", ",", "flavors", ",", "with_menu_label", "=", "True", ")", ":", "def", "get_key", "(", "flavor", ",", "sort_key", ")", ":", "try", ":", "return", "getattr", "(", "flavor", ",", "sort_key", ")", "except", "Attribute...
38.558824
18.588235
def tf_step(self, x, iteration, conjugate, residual, squared_residual): """ Iteration loop body of the conjugate gradient algorithm. Args: x: Current solution estimate $x_t$. iteration: Current iteration counter $t$. conjugate: Current conjugate $c_t$. ...
[ "def", "tf_step", "(", "self", ",", "x", ",", "iteration", ",", "conjugate", ",", "residual", ",", "squared_residual", ")", ":", "x", ",", "next_iteration", ",", "conjugate", ",", "residual", ",", "squared_residual", "=", "super", "(", "ConjugateGradient", "...
39.530612
27.816327
def transform(self, X): """ Return this basis applied to X. Parameters ---------- X: ndarray of shape (N, d) of observations where N is the number of samples, and d is the dimensionality of X. Returns ------- ndarray: ...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "N", ",", "D", "=", "X", ".", "shape", "return", "np", ".", "hstack", "(", "(", "np", ".", "ones", "(", "(", "N", ",", "1", ")", ")", ",", "X", ")", ")", "if", "self", ".", "onescol", "...
27
20.529412
def _build_authorization_request_url( self, response_type, state=None ): """Form URL to request an auth code or access token. Parameters response_type (str) Only 'code' (Authorization Code Grant) supported at this time state (str) ...
[ "def", "_build_authorization_request_url", "(", "self", ",", "response_type", ",", "state", "=", "None", ")", ":", "if", "response_type", "not", "in", "auth", ".", "VALID_RESPONSE_TYPES", ":", "message", "=", "'{} is not a valid response type.'", "raise", "LyftIllegal...
34.433333
18.733333
def publish(self, **kwargs): r""" Publishes state information. :Keyword Arguments: * *topic* (``string``) -- [REQUIRED] The name of the MQTT topic. * *payload* (``bytes or seekable file-like object``) -- The state information, in...
[ "def", "publish", "(", "self", ",", "*", "*", "kwargs", ")", ":", "topic", "=", "self", ".", "_get_required_parameter", "(", "'topic'", ",", "*", "*", "kwargs", ")", "# payload is an optional parameter", "payload", "=", "kwargs", ".", "get", "(", "'payload'"...
29.121212
19.272727
def destroy(self, request, project, pk=None): """ Delete a note entry """ try: note = JobNote.objects.get(id=pk) note.delete() return Response({"message": "Note deleted"}) except JobNote.DoesNotExist: return Response("No note with i...
[ "def", "destroy", "(", "self", ",", "request", ",", "project", ",", "pk", "=", "None", ")", ":", "try", ":", "note", "=", "JobNote", ".", "objects", ".", "get", "(", "id", "=", "pk", ")", "note", ".", "delete", "(", ")", "return", "Response", "("...
34.909091
11.090909
def hook(self, addr, hook=None, length=0, kwargs=None, replace=False): """ Hook a section of code with a custom function. This is used internally to provide symbolic summaries of library functions, and can be used to instrument execution or to modify control flow. When hook is n...
[ "def", "hook", "(", "self", ",", "addr", ",", "hook", "=", "None", ",", "length", "=", "0", ",", "kwargs", "=", "None", ",", "replace", "=", "False", ")", ":", "if", "hook", "is", "None", ":", "# if we haven't been passed a thing to hook with, assume we're b...
50.884615
33.038462
def ProcessNewBlock(self, block): """ Processes a block on the blockchain. This should be done in a sequential order, ie block 4 should be only processed after block 3. Args: block: (neo.Core.Block) a block on the blockchain. """ added = set() change...
[ "def", "ProcessNewBlock", "(", "self", ",", "block", ")", ":", "added", "=", "set", "(", ")", "changed", "=", "set", "(", ")", "deleted", "=", "set", "(", ")", "try", ":", "# go through the list of transactions in the block and enumerate", "# over their outputs", ...
41.320988
24.432099
def readline(self, size=-1): """Read one line delimited by '\n' from the file. A trailing newline character is kept in the string. It may be absent when a file ends with an incomplete line. If the size argument is non-negative, it specifies the maximum string size (counting the newline) to return. ...
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "self", ".", "_check_open", "(", ")", "if", "size", "==", "0", "or", "not", "self", ".", "_remaining", "(", ")", ":", "return", "''", "data_list", "=", "[", "]", "newline_offset"...
31.829268
20.02439
def inverse(self, name=None): """Returns a `sonnet` module to compute inverse affine transforms. The function first assembles a network that given the constraints of the current AffineGridWarper and a set of input parameters, retrieves the coefficients of the corresponding inverse affine transfor...
[ "def", "inverse", "(", "self", ",", "name", "=", "None", ")", ":", "if", "self", ".", "_num_coeff", "!=", "6", ":", "raise", "tf", ".", "errors", ".", "UnimplementedError", "(", "'AffineGridWarper currently supports'", "'inversion only for the 2D case.'", ")", "...
32.520408
24.153061
def upload_dir(bucket_name, path_prefix, source_dir, upload_dir_redirect_objects=True, surrogate_key=None, surrogate_control=None, cache_control=None, acl=None, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None)...
[ "def", "upload_dir", "(", "bucket_name", ",", "path_prefix", ",", "source_dir", ",", "upload_dir_redirect_objects", "=", "True", ",", "surrogate_key", "=", "None", ",", "surrogate_control", "=", "None", ",", "cache_control", "=", "None", ",", "acl", "=", "None",...
44.547945
20.534247
def addobject(bunchdt, data, commdct, key, theidf, aname=None, **kwargs): """add an object to the eplus model""" obj = newrawobject(data, commdct, key) abunch = obj2bunch(data, commdct, obj) if aname: namebunch(abunch, aname) data.dt[key].append(obj) bunchdt[key].append(abunch) for k...
[ "def", "addobject", "(", "bunchdt", ",", "data", ",", "commdct", ",", "key", ",", "theidf", ",", "aname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "newrawobject", "(", "data", ",", "commdct", ",", "key", ")", "abunch", "=", "obj2...
35.454545
12
def classical(group, src_filter, gsims, param, monitor=Monitor()): """ Compute the hazard curves for a set of sources belonging to the same tectonic region type for all the GSIMs associated to that TRT. The arguments are the same as in :func:`calc_hazard_curves`, except for ``gsims``, which is a lis...
[ "def", "classical", "(", "group", ",", "src_filter", ",", "gsims", ",", "param", ",", "monitor", "=", "Monitor", "(", ")", ")", ":", "if", "not", "hasattr", "(", "src_filter", ",", "'sitecol'", ")", ":", "# a sitecol was passed", "src_filter", "=", "Source...
44.578313
17.180723
def get_fields_class(self, class_name): """ Return all fields of a specific class :param class_name: the class name :type class_name: string :rtype: a list with :class:`EncodedField` objects """ l = [] for i in self.get_classes(): for j in i....
[ "def", "get_fields_class", "(", "self", ",", "class_name", ")", ":", "l", "=", "[", "]", "for", "i", "in", "self", ".", "get_classes", "(", ")", ":", "for", "j", "in", "i", ".", "get_fields", "(", ")", ":", "if", "class_name", "==", "j", ".", "ge...
26.3125
14.4375
def create_args(line, namespace): """ Expand any meta-variable references in the argument list. """ args = [] # Using shlex.split handles quotes args and escape characters. for arg in shlex.split(line): if not arg: continue if arg[0] == '$': var_name = arg[1:] if var...
[ "def", "create_args", "(", "line", ",", "namespace", ")", ":", "args", "=", "[", "]", "# Using shlex.split handles quotes args and escape characters.", "for", "arg", "in", "shlex", ".", "split", "(", "line", ")", ":", "if", "not", "arg", ":", "continue", "if",...
32.5625
18.5
def ilx_conv(graph, prefix, ilx_start): """ convert a set of temporary identifiers to ilx and modify the graph in place """ to_sub = set() for subject in graph.subjects(rdflib.RDF.type, rdflib.OWL.Class): if PREFIXES[prefix] in subject: to_sub.add(subject) ilx_base = 'ilx_{:0>7}' ...
[ "def", "ilx_conv", "(", "graph", ",", "prefix", ",", "ilx_start", ")", ":", "to_sub", "=", "set", "(", ")", "for", "subject", "in", "graph", ".", "subjects", "(", "rdflib", ".", "RDF", ".", "type", ",", "rdflib", ".", "OWL", ".", "Class", ")", ":",...
35.34375
15.6875
def _load_data(path): """ Loads data from a directory. Returns tuple (config_dict, wordlists). Raises Exception on failure (e.g. if data is corrupted). """ path = os.path.abspath(path) if not os.path.isdir(path): raise InitializationError('Directory not found: {0}'.format(path)) ...
[ "def", "_load_data", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "raise", "InitializationError", "(", "'Directory not found: {0}'", ".", "...
40.363636
15.818182
def _replace_series_name(seriesname, replacements): """Performs replacement of series name. Allow specified replacements of series names in cases where default filenames match the wrong series, e.g. missing year gives wrong answer, or vice versa. This helps the TVDB query get the right match. """ ...
[ "def", "_replace_series_name", "(", "seriesname", ",", "replacements", ")", ":", "for", "pat", ",", "replacement", "in", "six", ".", "iteritems", "(", "replacements", ")", ":", "if", "re", ".", "match", "(", "pat", ",", "seriesname", ",", "re", ".", "IGN...
44
19.272727
def embed_code_links(app, exception): """Embed hyperlinks to documentation into example code""" if exception is not None: return # No need to waste time embedding hyperlinks when not running the examples # XXX: also at the time of writing this fixes make html-noplot # for some reason I don'...
[ "def", "embed_code_links", "(", "app", ",", "exception", ")", ":", "if", "exception", "is", "not", "None", ":", "return", "# No need to waste time embedding hyperlinks when not running the examples", "# XXX: also at the time of writing this fixes make html-noplot", "# for some reas...
37.689655
20.344828
def isprime(n): """Check the number is prime value. if prime value returns True, not False.""" n = abs(int(n)) if n < 2: return False if n == 2: return True if not n & 1: return False # 在一般领域, 对正整数n, 如果用2 到 sqrt(n) 之间所有整数去除, 均无法整除, 则n为质数. for x in range(3, int(n ** ...
[ "def", "isprime", "(", "n", ")", ":", "n", "=", "abs", "(", "int", "(", "n", ")", ")", "if", "n", "<", "2", ":", "return", "False", "if", "n", "==", "2", ":", "return", "True", "if", "not", "n", "&", "1", ":", "return", "False", "# 在一般领域, 对正整...
22.352941
22.470588
def get_user(self, request): """ return active user or ``None`` """ try: return User.objects.get(username=request.data.get('username'), is_active=True) except User.DoesNotExist: return None
[ "def", "get_user", "(", "self", ",", "request", ")", ":", "try", ":", "return", "User", ".", "objects", ".", "get", "(", "username", "=", "request", ".", "data", ".", "get", "(", "'username'", ")", ",", "is_active", "=", "True", ")", "except", "User"...
31.222222
12.333333
def synonym(name): """ Utility function mimicking the behavior of the old SA synonym function with the new hybrid property semantics. """ return hybrid_property(lambda inst: getattr(inst, name), lambda inst, value: setattr(inst, name, value), exp...
[ "def", "synonym", "(", "name", ")", ":", "return", "hybrid_property", "(", "lambda", "inst", ":", "getattr", "(", "inst", ",", "name", ")", ",", "lambda", "inst", ",", "value", ":", "setattr", "(", "inst", ",", "name", ",", "value", ")", ",", "expr",...
43.25
17
def get_all_client_tags(self, params=None): """ Get all client tags This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param params: search params :return: list """ ...
[ "def", "get_all_client_tags", "(", "self", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_iterate_through_pages", "(", "get_function", "=", "self", ".", "get_client_tags_per_page", ",", "resource", "=", "CLIENT_TAGS", ",", "*", "*", "{", "'para...
34.142857
15.714286
def _get_dataset(dataset_name, dataset_prefix=None, data_dir=None, default_paths=None, verbose=1): """ Create if necessary and returns data directory of given dataset. data_dir: str Path of the data directory. Used to force data storage in a specified location. ...
[ "def", "_get_dataset", "(", "dataset_name", ",", "dataset_prefix", "=", "None", ",", "data_dir", "=", "None", ",", "default_paths", "=", "None", ",", "verbose", "=", "1", ")", ":", "dataset_folder", "=", "dataset_name", "if", "not", "dataset_prefix", "else", ...
35.230769
20.326923
def bulk_insert_extras(dialect_name: str, fileobj: TextIO, start: bool) -> None: """ Writes bulk ``INSERT`` preamble (start=True) or end (start=False). For MySQL, this temporarily switches off autocommit behaviour and index/FK checks, for speed, then re-ena...
[ "def", "bulk_insert_extras", "(", "dialect_name", ":", "str", ",", "fileobj", ":", "TextIO", ",", "start", ":", "bool", ")", "->", "None", ":", "lines", "=", "[", "]", "if", "dialect_name", "==", "SqlaDialectName", ".", "MYSQL", ":", "if", "start", ":", ...
33.37931
16.827586
def _make_event(self, event_type, code, value): """Make a new event and send it to the character device.""" secs, msecs = convert_timeval(time.time()) data = struct.pack(EVENT_FORMAT, secs, msecs, event_type, ...
[ "def", "_make_event", "(", "self", ",", "event_type", ",", "code", ",", "value", ")", ":", "secs", ",", "msecs", "=", "convert_timeval", "(", "time", ".", "time", "(", ")", ")", "data", "=", "struct", ".", "pack", "(", "EVENT_FORMAT", ",", "secs", ",...
40.363636
5.181818
def from_samples_bqm(cls, samples_like, bqm, **kwargs): """Build a SampleSet from raw samples using a BinaryQuadraticModel to get energies and vartype. Args: samples_like: A collection of raw samples. 'samples_like' is an extension of NumPy's array_like. See ...
[ "def", "from_samples_bqm", "(", "cls", ",", "samples_like", ",", "bqm", ",", "*", "*", "kwargs", ")", ":", "# more performant to do this once, here rather than again in bqm.energies", "# and in cls.from_samples", "samples_like", "=", "as_samples", "(", "samples_like", ")", ...
39.333333
27.2
def run_webhook(self, webhook_url, **options): """ Convenience method for running bots in webhook mode :Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken") Additional documentation on https://core.telegram....
[ "def", "run_webhook", "(", "self", ",", "webhook_url", ",", "*", "*", "options", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "loop", ".", "run_until_complete", "(", "self", ".", "set_webhook", "(", "webhook_url", ",", "*", "*", "op...
36.16
21.28
def dump(self, id, path): """ Dump the profile into path, id is the RDD id """ if not os.path.exists(path): os.makedirs(path) stats = self.stats() if stats: p = os.path.join(path, "rdd_%d.pstats" % id) stats.dump_stats(p)
[ "def", "dump", "(", "self", ",", "id", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "stats", "=", "self", ".", "stats", "(", ")", "if", "stats", ":", "p"...
35.25
11.25
def append(self, filename_in_zip, file_contents): ''' Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip. ''' # Set the file pointer to the end of the file self.in_memory_zip.seek(-1, io.SEEK_END) # Get a handle to the in-...
[ "def", "append", "(", "self", ",", "filename_in_zip", ",", "file_contents", ")", ":", "# Set the file pointer to the end of the file", "self", ".", "in_memory_zip", ".", "seek", "(", "-", "1", ",", "io", ".", "SEEK_END", ")", "# Get a handle to the in-memory zip in ap...
31.653846
21.423077
def plain(self, markup): """ Strips Wikipedia markup from given text. This creates a "plain" version of the markup, stripping images and references and the like. Does some commonsense maintenance as well, like collapsing multiple spaces. If you specified...
[ "def", "plain", "(", "self", ",", "markup", ")", ":", "# Strip bold and italic.", "if", "self", ".", "full_strip", ":", "markup", "=", "markup", ".", "replace", "(", "\"'''\"", ",", "\"\"", ")", "markup", "=", "markup", ".", "replace", "(", "\"''\"", ","...
43.913978
18.333333
def resolve_resource_refs(self, input_dict, supported_resource_refs): """ Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId.Property", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of ...
[ "def", "resolve_resource_refs", "(", "self", ",", "input_dict", ",", "supported_resource_refs", ")", ":", "if", "not", "self", ".", "can_handle", "(", "input_dict", ")", ":", "return", "input_dict", "key", "=", "self", ".", "intrinsic_name", "value", "=", "inp...
51.677966
36.423729
def _on_text_changed(self): """ Adjust dirty flag depending on editor's content """ if not self._cleaning: ln = TextHelper(self).cursor_position()[0] self._modified_lines.add(ln)
[ "def", "_on_text_changed", "(", "self", ")", ":", "if", "not", "self", ".", "_cleaning", ":", "ln", "=", "TextHelper", "(", "self", ")", ".", "cursor_position", "(", ")", "[", "0", "]", "self", ".", "_modified_lines", ".", "add", "(", "ln", ")" ]
42.8
7.4
def find(self, other): """Return an interable of elements that overlap other in the tree.""" iset = self._iset l = binsearch_left_start(iset, other[0] - self._maxlen, 0, len(iset)) r = binsearch_right_end(iset, other[1], 0, len(iset)) iopts = iset[l:r] iiter = (s for s in...
[ "def", "find", "(", "self", ",", "other", ")", ":", "iset", "=", "self", ".", "_iset", "l", "=", "binsearch_left_start", "(", "iset", ",", "other", "[", "0", "]", "-", "self", ".", "_maxlen", ",", "0", ",", "len", "(", "iset", ")", ")", "r", "=...
49.125
18.75
def from_iso(cls, iso): """Retrieve the first datacenter id associated to an ISO.""" result = cls.list({'sort_by': 'id ASC'}) dc_isos = {} for dc in result: if dc['iso'] not in dc_isos: dc_isos[dc['iso']] = dc['id'] return dc_isos.get(iso)
[ "def", "from_iso", "(", "cls", ",", "iso", ")", ":", "result", "=", "cls", ".", "list", "(", "{", "'sort_by'", ":", "'id ASC'", "}", ")", "dc_isos", "=", "{", "}", "for", "dc", "in", "result", ":", "if", "dc", "[", "'iso'", "]", "not", "in", "d...
33.333333
12.666667
def main(arguments, output=None, testing_mode=None): """ Entry point parses command-line arguments, runs the specified EC2 API method and prints the response to the screen. @param arguments: Command-line arguments, typically retrieved from C{sys.argv}. @param output: Optionally, a stream to...
[ "def", "main", "(", "arguments", ",", "output", "=", "None", ",", "testing_mode", "=", "None", ")", ":", "def", "run_command", "(", "arguments", ",", "output", ",", "reactor", ")", ":", "if", "output", "is", "None", ":", "output", "=", "sys", ".", "s...
37
18.513514
def planetType(temperature, mass, radius): """ Returns the planet type as 'temperatureType massType' """ if mass is not np.nan: sizeType = planetMassType(mass) elif radius is not np.nan: sizeType = planetRadiusType(radius) else: return None return '{0} {1}'.format(plane...
[ "def", "planetType", "(", "temperature", ",", "mass", ",", "radius", ")", ":", "if", "mass", "is", "not", "np", ".", "nan", ":", "sizeType", "=", "planetMassType", "(", "mass", ")", "elif", "radius", "is", "not", "np", ".", "nan", ":", "sizeType", "=...
28.5
15.666667
def _registerUnit(self, uName, unit): """ Register unit object on interface level object """ nameAvailabilityCheck(self, uName, unit) assert unit._parent is None unit._parent = self unit._name = uName self._units.append(unit)
[ "def", "_registerUnit", "(", "self", ",", "uName", ",", "unit", ")", ":", "nameAvailabilityCheck", "(", "self", ",", "uName", ",", "unit", ")", "assert", "unit", ".", "_parent", "is", "None", "unit", ".", "_parent", "=", "self", "unit", ".", "_name", "...
31.222222
7.222222
def format_args(self): """Get the arguments formatted as string. :returns: The formatted arguments. :rtype: str """ result = [] if self.args: result.append( _format_args( self.args, self.defaults, getattr(self, "annotations...
[ "def", "format_args", "(", "self", ")", ":", "result", "=", "[", "]", "if", "self", ".", "args", ":", "result", ".", "append", "(", "_format_args", "(", "self", ".", "args", ",", "self", ".", "defaults", ",", "getattr", "(", "self", ",", "\"annotatio...
29.846154
16.769231
def Filter(self): """Filter parsed data to create derived fields.""" if not self.desc: self.short_desc = '' return for i in range(len(self.desc)): # replace full path with name if self.desc[i].find(self.executable) >= 0: self.desc[i] = self.desc[i].replace(self.executable, self....
[ "def", "Filter", "(", "self", ")", ":", "if", "not", "self", ".", "desc", ":", "self", ".", "short_desc", "=", "''", "return", "for", "i", "in", "range", "(", "len", "(", "self", ".", "desc", ")", ")", ":", "# replace full path with name", "if", "sel...
39.333333
17.142857
def getParameter(self, paramName): """Get parameter value""" (setter, getter) = self._getParameterMethods(paramName) if getter is None: import exceptions raise exceptions.Exception( "getParameter -- parameter name '%s' does not exist in region %s of type %s" % (paramName, sel...
[ "def", "getParameter", "(", "self", ",", "paramName", ")", ":", "(", "setter", ",", "getter", ")", "=", "self", ".", "_getParameterMethods", "(", "paramName", ")", "if", "getter", "is", "None", ":", "import", "exceptions", "raise", "exceptions", ".", "Exce...
40
14.555556
def _make_context_immutable(context): """Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType....
[ "def", "_make_context_immutable", "(", "context", ")", ":", "def", "make_immutable", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "Mapping", ")", ":", "return", "MappingProxyType", "(", "val", ")", "else", ":", "return", "val", "if", "not", ...
34.25
17.4
def _time_regex_match(regex: str, utterance: str, char_offset_to_token_index: Dict[int, int], map_match_to_query_value: Callable[[str], List[int]], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: r""" Given ...
[ "def", "_time_regex_match", "(", "regex", ":", "str", ",", "utterance", ":", "str", ",", "char_offset_to_token_index", ":", "Dict", "[", "int", ",", "int", "]", ",", "map_match_to_query_value", ":", "Callable", "[", "[", "str", "]", ",", "List", "[", "int"...
62.257143
30.628571
def html(self): """ Render those properties as html :return: """ return """ <div class="property"><i>{name}</i><br/> <pre>{value}</pre></div> """.format(name=tag.text(self.name), value=tag.text(self.value))
[ "def", "html", "(", "self", ")", ":", "return", "\"\"\"\n <div class=\"property\"><i>{name}</i><br/>\n <pre>{value}</pre></div>\n \"\"\"", ".", "format", "(", "name", "=", "tag", ".", "text", "(", "self", ".", "name", ")", ",", "value", "=", "tag"...
28.777778
7.555556
def spread(symbol, token='', version=''): '''This returns an array of effective spread, eligible volume, and price improvement of a stock, by market. Unlike volume-by-venue, this will only return a venue if effective spread is not ‘N/A’. Values are sorted in descending order by effectiveSpread. Lower effect...
[ "def", "spread", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "_raiseIfNotStr", "(", "symbol", ")", "return", "_getJson", "(", "'stock/'", "+", "symbol", "+", "'/effective-spread'", ",", "token", ",", "version", ")" ]
48.423077
39.115385
def hydrate_spawned_files(self, exported_files_mapper, filename, data_id): """Pop the given file's map from the exported files mapping. :param exported_files_mapper: The dict of file mappings this process produced. :param filename: The filename to format and remove from the ...
[ "def", "hydrate_spawned_files", "(", "self", ",", "exported_files_mapper", ",", "filename", ",", "data_id", ")", ":", "# JSON only has string dictionary keys, so the Data object id", "# needs to be stringified first.", "data_id", "=", "str", "(", "data_id", ")", "if", "file...
41.5
22.384615
def should_include_node(ctx, directives): # type: (ExecutionContext, Optional[List[Directive]]) -> bool """Determines if a field should be included based on the @include and @skip directives, where @skip has higher precidence than @include.""" # TODO: Refactor based on latest code if directives: ...
[ "def", "should_include_node", "(", "ctx", ",", "directives", ")", ":", "# type: (ExecutionContext, Optional[List[Directive]]) -> bool", "# TODO: Refactor based on latest code", "if", "directives", ":", "skip_ast", "=", "None", "for", "directive", "in", "directives", ":", "i...
31.861111
19.416667
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]: """ Takes gold and predicted answer sets and first finds a greedy 1-1 alignment between them and gets maximum metric values over all the answers """ f1_scores = [] for gold_index, gold_item in enumerate(gold): ...
[ "def", "_align_bags", "(", "predicted", ":", "List", "[", "Set", "[", "str", "]", "]", ",", "gold", ":", "List", "[", "Set", "[", "str", "]", "]", ")", "->", "List", "[", "float", "]", ":", "f1_scores", "=", "[", "]", "for", "gold_index", ",", ...
39
15.888889
def add_tk_widget(self, tk_widget, grid=None, align=None, visible=True, enabled=None, width=None, height=None): """ Adds a tk widget into a guizero container. :param tkinter.Widget tk_widget: The Container (App, Box, etc) the tk widget will belong too. :param List grid: ...
[ "def", "add_tk_widget", "(", "self", ",", "tk_widget", ",", "grid", "=", "None", ",", "align", "=", "None", ",", "visible", "=", "True", ",", "enabled", "=", "None", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "return", "Widget",...
37.3
26.3
def load_words(self, words): """ Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded """ self._dictionary.update([word.lower() for word in words]) self._update_dictionary()
[ "def", "load_words", "(", "self", ",", "words", ")", ":", "self", ".", "_dictionary", ".", "update", "(", "[", "word", ".", "lower", "(", ")", "for", "word", "in", "words", "]", ")", "self", ".", "_update_dictionary", "(", ")" ]
40.571429
15.285714
def _get_basic_term(self, C, rup, dists): """ Compute and return basic form, see page 1030. """ # Fictitious depth calculation if rup.mag > 5.: c4m = C['c4'] elif rup.mag > 4.: c4m = C['c4'] - (C['c4']-1.) * (5. - rup.mag) else: ...
[ "def", "_get_basic_term", "(", "self", ",", "C", ",", "rup", ",", "dists", ")", ":", "# Fictitious depth calculation", "if", "rup", ".", "mag", ">", "5.", ":", "c4m", "=", "C", "[", "'c4'", "]", "elif", "rup", ".", "mag", ">", "4.", ":", "c4m", "="...
43.30303
16.333333
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10): """This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are ...
[ "def", "assets", "(", "self", ",", "asset_code", "=", "None", ",", "asset_issuer", "=", "None", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/assets'", "params", "=", "self", ".", "__qu...
48.56
28.48
def getOutput(self): """ Returns the combined output of stdout and stderr """ output = self.stdout if self.stdout: output += '\r\n' output += self.stderr return output
[ "def", "getOutput", "(", "self", ")", ":", "output", "=", "self", ".", "stdout", "if", "self", ".", "stdout", ":", "output", "+=", "'\\r\\n'", "output", "+=", "self", ".", "stderr", "return", "output" ]
25.222222
11.888889
def add_new_resource(self): """Handle add new resource requests. """ parameters_widget = [ self.parameters_scrollarea.layout().itemAt(i) for i in range(self.parameters_scrollarea.layout().count())][0].widget() parameter_widgets = [ parameters_widget.ve...
[ "def", "add_new_resource", "(", "self", ")", ":", "parameters_widget", "=", "[", "self", ".", "parameters_scrollarea", ".", "layout", "(", ")", ".", "itemAt", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "parameters_scrollarea", ".", "layout...
48.444444
13.638889
def get_query_parameters(config_parameters, date_time=datetime.datetime.now()): """ Merge the given parameters with the airflow macros. Enables macros (like '@_ds') in sql. Args: config_parameters: The user-specified list of parameters in the cell-body. date_time: The timestamp at which the paramet...
[ "def", "get_query_parameters", "(", "config_parameters", ",", "date_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", ":", "merged_parameters", "=", "Query", ".", "merge_parameters", "(", "config_parameters", ",", "date_time", "=", "date_time", ...
43.111111
27.518519
def p_user_add_link(self): ''' user add link. ''' if self.check_post_role()['ADD']: pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.get_current_user() cur_uid = tools.get_uudd(2) whil...
[ "def", "p_user_add_link", "(", "self", ")", ":", "if", "self", ".", "check_post_role", "(", ")", "[", "'ADD'", "]", ":", "pass", "else", ":", "return", "False", "post_data", "=", "self", ".", "get_post_data", "(", ")", "post_data", "[", "'user_name'", "]...
24.16
17.92
def render(self, display): """Renders the bar on the display""" # the bar bar_rect = pygame.Rect(0, 0, self.width, self.height // 3) bar_rect.center = self.center display.fill(self.bg_color, bar_rect) # the cursor circle(display, (self.value_px, self.centery), s...
[ "def", "render", "(", "self", ",", "display", ")", ":", "# the bar", "bar_rect", "=", "pygame", ".", "Rect", "(", "0", ",", "0", ",", "self", ".", "width", ",", "self", ".", "height", "//", "3", ")", "bar_rect", ".", "center", "=", "self", ".", "...
30.285714
20.857143
def leave(self): """ Leave the MUC. """ fut = self.on_exit.future() def cb(**kwargs): fut.set_result(None) return True # disconnect self.on_exit.connect(cb) presence = aioxmpp.stanza.Presence( type_=aioxmpp.structs.PresenceT...
[ "def", "leave", "(", "self", ")", ":", "fut", "=", "self", ".", "on_exit", ".", "future", "(", ")", "def", "cb", "(", "*", "*", "kwargs", ")", ":", "fut", ".", "set_result", "(", "None", ")", "return", "True", "# disconnect", "self", ".", "on_exit"...
22.842105
17.789474
def present(name, acl_type, acl_name='', perms='', recurse=False, force=False): ''' Ensure a Linux ACL is present name The acl path acl_type The type of the acl is used for it can be 'user' or 'group' acl_name The user or group perms Set the permissions eg.: ...
[ "def", "present", "(", "name", ",", "acl_type", ",", "acl_name", "=", "''", ",", "perms", "=", "''", ",", "recurse", "=", "False", ",", "force", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'...
39.007246
24.369565
def subject_name(self): """ Get the subject name consistently :rtype str :return: The Subject ID for the subject .. note:: * If the `SubjectKeyType` is `SubjectUUID` then the subject name lives in the `mdsol:SubjectName` attribute * If the `SubjectKeyType` is...
[ "def", "subject_name", "(", "self", ")", ":", "if", "self", ".", "subjectkeytype", "and", "self", ".", "subjectkeytype", "==", "\"SubjectUUID\"", ".", "lower", "(", ")", ":", "# if the SubjectKeyType is \"SubjectUUID\", then return the SubjectName", "return", "self", ...
42.533333
25.066667
def from_array(array): """ Deserialize a new PreCheckoutQuery from a given dictionary. :return: new PreCheckoutQuery instance. :rtype: PreCheckoutQuery """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, p...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "from", "pytgbot", ".", "api...
43.608696
22.304348
def act(self): """ Power on action """ g = get_root(self).globals g.clog.debug('Power on pressed') if execCommand(g, 'online'): g.clog.info('ESO server online') g.cpars['eso_server_online'] = True if not isPoweredOn(g): ...
[ "def", "act", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "g", ".", "clog", ".", "debug", "(", "'Power on pressed'", ")", "if", "execCommand", "(", "g", ",", "'online'", ")", ":", "g", ".", "clog", ".", "info", ...
32.054054
15.837838
def add_tandems(mcscanfile, tandemfile): """ add tandem genes to anchor genes in mcscan file """ tandems = [f.strip().split(",") for f in file(tandemfile)] fw = must_open(mcscanfile+".withtandems", "w") fp = must_open(mcscanfile) seen =set() for i, row in enumerate(fp): if row[0]...
[ "def", "add_tandems", "(", "mcscanfile", ",", "tandemfile", ")", ":", "tandems", "=", "[", "f", ".", "strip", "(", ")", ".", "split", "(", "\",\"", ")", "for", "f", "in", "file", "(", "tandemfile", ")", "]", "fw", "=", "must_open", "(", "mcscanfile",...
30.302326
15.418605
def load_data_and_labels(): """Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. """ # download dataset get_chinese_text() # Load data from files positive_examples = list(codecs.open("./data/pos.txt", "r", "utf-8").readli...
[ "def", "load_data_and_labels", "(", ")", ":", "# download dataset", "get_chinese_text", "(", ")", "# Load data from files", "positive_examples", "=", "list", "(", "codecs", ".", "open", "(", "\"./data/pos.txt\"", ",", "\"r\"", ",", "\"utf-8\"", ")", ".", "readlines"...
43.75
19.958333
def remove_listener(self, listener): """Remove the given listener from the wrapped client. :param listener: A listener previously passed to :meth:`add_listener`. """ internal_listener = self._internal_listeners.pop(listener) return self._client.remove_listener(internal_listener)
[ "def", "remove_listener", "(", "self", ",", "listener", ")", ":", "internal_listener", "=", "self", ".", "_internal_listeners", ".", "pop", "(", "listener", ")", "return", "self", ".", "_client", ".", "remove_listener", "(", "internal_listener", ")" ]
44.857143
18.571429
def parse_document(graph: BELGraph, enumerated_lines: Iterable[Tuple[int, str]], metadata_parser: MetadataParser, ) -> None: """Parse the lines in the document section of a BEL script.""" parse_document_start_time = time.time() for line_number, line ...
[ "def", "parse_document", "(", "graph", ":", "BELGraph", ",", "enumerated_lines", ":", "Iterable", "[", "Tuple", "[", "int", ",", "str", "]", "]", ",", "metadata_parser", ":", "MetadataParser", ",", ")", "->", "None", ":", "parse_document_start_time", "=", "t...
41.65625
19.21875
def _build_pcollection(self, pipeline, folder, split): """Generate examples as dicts.""" beam = tfds.core.lazy_imports.apache_beam split_type = self.builder_config.split_type filename = os.path.join(folder, "{}.tar.gz".format(split_type)) def _extract_data(inputs): """Extracts files from th...
[ "def", "_build_pcollection", "(", "self", ",", "pipeline", ",", "folder", ",", "split", ")", ":", "beam", "=", "tfds", ".", "core", ".", "lazy_imports", ".", "apache_beam", "split_type", "=", "self", ".", "builder_config", ".", "split_type", "filename", "=",...
36.553571
16.946429
def _check_response_for_request_errors(self): """ Override this in each service module to check for errors that are specific to that module. For example, invalid tracking numbers in a Tracking request. """ if self.response.HighestSeverity == "ERROR": for noti...
[ "def", "_check_response_for_request_errors", "(", "self", ")", ":", "if", "self", ".", "response", ".", "HighestSeverity", "==", "\"ERROR\"", ":", "for", "notification", "in", "self", ".", "response", ".", "Notifications", ":", "if", "notification", ".", "Severi...
43.083333
16.75
async def step(self): """ EXPERIMENTAL: Change self._client.game_step during the step function to increase or decrease steps per second """ result = await self._execute(step=sc_pb.RequestStep(count=self.game_step)) return result
[ "async", "def", "step", "(", "self", ")", ":", "result", "=", "await", "self", ".", "_execute", "(", "step", "=", "sc_pb", ".", "RequestStep", "(", "count", "=", "self", ".", "game_step", ")", ")", "return", "result" ]
62.25
20
def clear(self) -> None: """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders( { "Server": "TornadoServer/%s" % tornado.version, "Content-Type": "text/html; charset=UTF-8", "Date": httputil.format_timesta...
[ "def", "clear", "(", "self", ")", "->", "None", ":", "self", ".", "_headers", "=", "httputil", ".", "HTTPHeaders", "(", "{", "\"Server\"", ":", "\"TornadoServer/%s\"", "%", "tornado", ".", "version", ",", "\"Content-Type\"", ":", "\"text/html; charset=UTF-8\"", ...
39.615385
15.692308
def process_object(obj): "Hook to process the object currently being displayed." invalid_options = OptsMagic.process_element(obj) if invalid_options: return invalid_options OutputMagic.info(obj)
[ "def", "process_object", "(", "obj", ")", ":", "invalid_options", "=", "OptsMagic", ".", "process_element", "(", "obj", ")", "if", "invalid_options", ":", "return", "invalid_options", "OutputMagic", ".", "info", "(", "obj", ")" ]
41.2
13.6
def use_default_iou_values(self, state): """ Sets if this device uses the default IOU image values. :param state: boolean """ self._use_default_iou_values = state if state: log.info('IOU "{name}" [{id}]: uses the default IOU image values'.format(name=self._n...
[ "def", "use_default_iou_values", "(", "self", ",", "state", ")", ":", "self", ".", "_use_default_iou_values", "=", "state", "if", "state", ":", "log", ".", "info", "(", "'IOU \"{name}\" [{id}]: uses the default IOU image values'", ".", "format", "(", "name", "=", ...
38.75
27.083333
def get_irregular_edge_by_vertex(graph, vertex): """ Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex """ for edge in graph.get_edges_by_vertex(vertex): if...
[ "def", "get_irregular_edge_by_vertex", "(", "graph", ",", "vertex", ")", ":", "for", "edge", "in", "graph", ".", "get_edges_by_vertex", "(", "vertex", ")", ":", "if", "edge", ".", "is_irregular_edge", ":", "return", "edge", "return", "None" ]
41.777778
19.777778
def cloud_add_bt_task(cookie, tokens, source_url, save_path, selected_idx, file_sha1='', vcode='', vcode_input=''): '''新建一个BT类的离线下载任务, 包括magent磁链. source_path - BT种子所在的绝对路径 save_path - 下载的文件要存放到的目录 selected_idx - BT种子中, 包含若干个文件, 这里, 来指定要下载哪些文件, 从1开始计数. f...
[ "def", "cloud_add_bt_task", "(", "cookie", ",", "tokens", ",", "source_url", ",", "save_path", ",", "selected_idx", ",", "file_sha1", "=", "''", ",", "vcode", "=", "''", ",", "vcode_input", "=", "''", ")", ":", "url", "=", "''", ".", "join", "(", "[", ...
32.510638
17.06383
def GetSecurityToken(self, username, password): """ Grabs a security Token to authenticate to Office 365 services """ url = 'https://login.microsoftonline.com/extSTS.srf' body = """ <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xm...
[ "def", "GetSecurityToken", "(", "self", ",", "username", ",", "password", ")", ":", "url", "=", "'https://login.microsoftonline.com/extSTS.srf'", "body", "=", "\"\"\"\n <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"\n xmlns:a=\"http://ww...
50.408163
24.77551
def load_blotter_args(blotter_name=None, logger=None): """ Load running blotter's settings (used by clients) :Parameters: blotter_name : str Running Blotter's name (defaults to "auto-detect") logger : object Logger to be use (defaults to Blotter's) :Returns: ...
[ "def", "load_blotter_args", "(", "blotter_name", "=", "None", ",", "logger", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "logger", "=", "tools", ".", "createLogger", "(", "__name__", ",", "logging", ".", "WARNING", ")", "# find specific name", ...
31.090909
21.363636
def EncryptPrivateKey(self, decrypted): """ Encrypt the provided plaintext with the initialized private key. Args: decrypted (byte string): the plaintext to be encrypted. Returns: bytes: the ciphertext. """ aes = AES.new(self._master_key, AES.MOD...
[ "def", "EncryptPrivateKey", "(", "self", ",", "decrypted", ")", ":", "aes", "=", "AES", ".", "new", "(", "self", ".", "_master_key", ",", "AES", ".", "MODE_CBC", ",", "self", ".", "_iv", ")", "return", "aes", ".", "encrypt", "(", "decrypted", ")" ]
30.25
18.583333
def apply_cut(self, cm): """Return a modified connectivity matrix with all connections that are severed by this cut removed. Args: cm (np.ndarray): A connectivity matrix. """ # Invert the cut matrix, creating a matrix of preserved connections inverse = np.log...
[ "def", "apply_cut", "(", "self", ",", "cm", ")", ":", "# Invert the cut matrix, creating a matrix of preserved connections", "inverse", "=", "np", ".", "logical_not", "(", "self", ".", "cut_matrix", "(", "cm", ".", "shape", "[", "0", "]", ")", ")", ".", "astyp...
38.9
18
def _handle_actiondefinefunction2(self, _): """Handle the ActionDefineFunction2 action.""" obj = _make_object("ActionDefineFunction2") obj.FunctionName = self._get_struct_string() obj.NumParams = unpack_ui16(self._src) obj.RegisterCount = unpack_ui8(self._src) bc = BitCon...
[ "def", "_handle_actiondefinefunction2", "(", "self", ",", "_", ")", ":", "obj", "=", "_make_object", "(", "\"ActionDefineFunction2\"", ")", "obj", ".", "FunctionName", "=", "self", ".", "_get_struct_string", "(", ")", "obj", ".", "NumParams", "=", "unpack_ui16",...
43.64
5.96
def _update_cache(self): """ If one of the original registries was changed. Update our merged version. """ expected_version = ( tuple(r._version for r in self.registries) + (self._extra_registry._version, )) if self._last_version != expected_versi...
[ "def", "_update_cache", "(", "self", ")", ":", "expected_version", "=", "(", "tuple", "(", "r", ".", "_version", "for", "r", "in", "self", ".", "registries", ")", "+", "(", "self", ".", "_extra_registry", ".", "_version", ",", ")", ")", "if", "self", ...
33.7
18.6
def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ if django.VERSION >= (2, 2): dest._css_lists += media._css_lists dest._js_lists += media._js_lists elif django.VERSION >= (2, 0): combined = dest + media ...
[ "def", "add_media", "(", "dest", ",", "media", ")", ":", "if", "django", ".", "VERSION", ">=", "(", "2", ",", "2", ")", ":", "dest", ".", "_css_lists", "+=", "media", ".", "_css_lists", "dest", ".", "_js_lists", "+=", "media", ".", "_js_lists", "elif...
31.642857
10.785714
def all_agents(stmts): """Return a list of all of the agents from a list of statements. Only agents that are not None and have a TEXT entry are returned. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` Returns ------- agents : list of :py:class:`indra.stat...
[ "def", "all_agents", "(", "stmts", ")", ":", "agents", "=", "[", "]", "for", "stmt", "in", "stmts", ":", "for", "agent", "in", "stmt", ".", "agent_list", "(", ")", ":", "# Agents don't always have a TEXT db_refs entry (for instance", "# in the case of Statements fro...
34.363636
23.590909
def mb_handler(self, args): '''Handler for mb command''' if len(args) == 1: raise InvalidArgument('No s3 bucketname provided') self.validate('cmd|s3', args) self.s3handler().create_bucket(args[1])
[ "def", "mb_handler", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "raise", "InvalidArgument", "(", "'No s3 bucketname provided'", ")", "self", ".", "validate", "(", "'cmd|s3'", ",", "args", ")", "self", ".", "s3handl...
30.428571
15
def flatpages_link_list(request): """ Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages. """ from django.contrib.flatpages.models import FlatPage link_list = [(page.title, page.url) for page in FlatPage.objects.all()] return render_to_link_li...
[ "def", "flatpages_link_list", "(", "request", ")", ":", "from", "django", ".", "contrib", ".", "flatpages", ".", "models", "import", "FlatPage", "link_list", "=", "[", "(", "page", ".", "title", ",", "page", ".", "url", ")", "for", "page", "in", "FlatPag...
40.75
13
def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} ttype = args['ttype'] (sim_targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(args) targets = load_yaml(sim_targets_yaml) base_config = dict(ttype=ttype, ...
[ "def", "build_job_configs", "(", "self", ",", "args", ")", ":", "job_configs", "=", "{", "}", "ttype", "=", "args", "[", "'ttype'", "]", "(", "sim_targets_yaml", ",", "sim", ")", "=", "NAME_FACTORY", ".", "resolve_targetfile", "(", "args", ")", "targets", ...
39.56
17.64
def dbmin50years(self, value=None): """ Corresponds to IDD Field `dbmin50years` 50-year return period values for minimum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmin50years` Unit: C if `value` is None it will not be ch...
[ "def", "dbmin50years", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type f...
36.428571
20.952381
def set(self, key, value, key_length=0): """Set value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) if self.k: self._...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "key_length", "=", "0", ")", ":", "if", "key_length", "<", "1", ":", "key_length", "=", "len", "(", "key", ")", "if", "self", ".", "k", ":", "self", ".", "_update", "(", "key", ",", "val...
27.571429
12.714286
def to_python(self, value): """ This assumes the value has been preprocessed into a dictionary of the form: {'type': <geometry_type>, 'geometry': <raw_geometry>} """ if not value or isinstance(value, BaseGeometry): return value geometry_type = value['type'] ...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "not", "value", "or", "isinstance", "(", "value", ",", "BaseGeometry", ")", ":", "return", "value", "geometry_type", "=", "value", "[", "'type'", "]", "geometry", "=", "value", "[", "'geometr...
41.043478
23.173913
def make_request(parameters): """Submit a getfeature request to DataBC WFS and return features """ r = requests.get(bcdata.WFS_URL, params=parameters) return r.json()["features"]
[ "def", "make_request", "(", "parameters", ")", ":", "r", "=", "requests", ".", "get", "(", "bcdata", ".", "WFS_URL", ",", "params", "=", "parameters", ")", "return", "r", ".", "json", "(", ")", "[", "\"features\"", "]" ]
38
7
def job_start(job_backend, trainer, keras_callback): """ Starts the training of a job. Needs job_prepare() first. :type job_backend: JobBackend :type trainer: Trainer :return: """ job_backend.set_status('STARTING') job_model = job_backend.get_job_model() model_provider = job_model...
[ "def", "job_start", "(", "job_backend", ",", "trainer", ",", "keras_callback", ")", ":", "job_backend", ".", "set_status", "(", "'STARTING'", ")", "job_model", "=", "job_backend", ".", "get_job_model", "(", ")", "model_provider", "=", "job_model", ".", "get_mode...
34.4
21.766667
def can_connect_passwordless(hostname): """ Ensure that current host can SSH remotely to the remote host using the ``BatchMode`` option to prevent a password prompt. That attempt will error with an exit status of 255 and a ``Permission denied`` message or a``Host key verification failed`` message. ...
[ "def", "can_connect_passwordless", "(", "hostname", ")", ":", "# Ensure we are not doing this for local hosts", "if", "not", "remoto", ".", "backends", ".", "needs_ssh", "(", "hostname", ")", ":", "return", "True", "logger", "=", "logging", ".", "getLogger", "(", ...
41.185185
19.481481
def read_config(file_name): """ Read YAML file with configuration and pointers to example data. Args: file_name (str): Name of the file, where the configuration is stored. Returns: dict: Parsed and processed data (see :func:`_process_config_item`). Example YAML file:: html...
[ "def", "read_config", "(", "file_name", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "file_name", ")", ")", "dirname", "=", "os", ".", "path", ".", "relpath", "(", "dirname", ")", "# create...
27.4
19.8
def _is_a_url(input_element): """ ----- Brief ----- Auxiliary function responsible for checking if the input is a string that contains an url. ----------- Description ----------- Some biosignalsnotebooks functions support a remote access to files. In this situation it is importa...
[ "def", "_is_a_url", "(", "input_element", ")", ":", "if", "type", "(", "input_element", ")", "is", "str", ":", "# Check if signal_handler is a url.", "# [Statements to be executed if signal_handler is a url]", "if", "any", "(", "mark", "in", "input_element", "for", "mar...
31.473684
28.578947
def pagination_data(self, max_number_of_links=7): '''Returns a generator of tuples (string, page_number, clickable), where `string` is the text of the html link, `page_number` is the number of the page the link points to, and `clickable` is a boolean indicating whether the link is clicka...
[ "def", "pagination_data", "(", "self", ",", "max_number_of_links", "=", "7", ")", ":", "div", ",", "mod", "=", "divmod", "(", "max_number_of_links", ",", "2", ")", "if", "not", "mod", "==", "1", ":", "msg", "=", "'Max number of links must be odd, was %r.'", ...
40.555556
17.822222
def render_summary(self, include_title=True): """Render the traceback for the interactive console.""" title = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: if self.is_syntax_error:...
[ "def", "render_summary", "(", "self", ",", "include_title", "=", "True", ")", ":", "title", "=", "''", "frames", "=", "[", "]", "classes", "=", "[", "'traceback'", "]", "if", "not", "self", ".", "frames", ":", "classes", ".", "append", "(", "'noframe-t...
34.83871
19
def create(cls, scheduled_analysis, tags=None, json_report_objects=None, raw_report_objects=None, additional_metadata=None, analysis_date=None): """ Create a new report. For convenience :func:`~mass_api_client.resources.scheduled_analysis.ScheduledAnalysis.create_report` of class :class...
[ "def", "create", "(", "cls", ",", "scheduled_analysis", ",", "tags", "=", "None", ",", "json_report_objects", "=", "None", ",", "raw_report_objects", "=", "None", ",", "additional_metadata", "=", "None", ",", "analysis_date", "=", "None", ")", ":", "if", "ta...
52.740741
34.222222
def builtin_lookup(name): """lookup a name into the builtin module return the list of matching statements and the astroid for the builtin module """ builtin_astroid = MANAGER.ast_from_module(builtins) if name == "__dict__": return builtin_astroid, () try: stmts = builtin_astr...
[ "def", "builtin_lookup", "(", "name", ")", ":", "builtin_astroid", "=", "MANAGER", ".", "ast_from_module", "(", "builtins", ")", "if", "name", "==", "\"__dict__\"", ":", "return", "builtin_astroid", ",", "(", ")", "try", ":", "stmts", "=", "builtin_astroid", ...
30.615385
15.307692