text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def save_keras_definition(keras_model, path): """ Save a Keras model definition to JSON with given path """ model_json = keras_model.to_json() with open(path, "w") as json_file: json_file.write(model_json)
[ "def", "save_keras_definition", "(", "keras_model", ",", "path", ")", ":", "model_json", "=", "keras_model", ".", "to_json", "(", ")", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "json_file", ":", "json_file", ".", "write", "(", "model_json", ")"...
32.428571
4.428571
def parse_stats(self, media_page): """Parses the DOM and returns media statistics attributes. :type media_page: :class:`bs4.BeautifulSoup` :param media_page: MAL media stats page's DOM :rtype: dict :return: media stats attributes. """ media_info = self.parse_sidebar(media_page) verb_p...
[ "def", "parse_stats", "(", "self", ",", "media_page", ")", ":", "media_info", "=", "self", ".", "parse_sidebar", "(", "media_page", ")", "verb_progressive", "=", "self", ".", "consuming_verb", "+", "u'ing'", "status_stats", "=", "{", "verb_progressive", ":", "...
31.544444
27.755556
def process_crs(crs): """ Parses cartopy CRS definitions defined in one of a few formats: 1. EPSG codes: Defined as string of the form "EPSG: {code}" or an integer 2. proj.4 string: Defined as string of the form "{proj.4 string}" 3. cartopy.crs.CRS instance 4. None defaults to crs.Pla...
[ "def", "process_crs", "(", "crs", ")", ":", "try", ":", "import", "cartopy", ".", "crs", "as", "ccrs", "import", "geoviews", "as", "gv", "# noqa", "import", "pyproj", "except", ":", "raise", "ImportError", "(", "'Geographic projection support requires GeoViews and...
37.764706
24.470588
def cumulative_distribution(self, X): """Computes the cumulative distribution function for the copula, :math:`C(u, v)` Args: X: `np.ndarray` Returns: np.array: cumulative probability """ self.check_fit() U, V = self.split_matrix(X) if (...
[ "def", "cumulative_distribution", "(", "self", ",", "X", ")", ":", "self", ".", "check_fit", "(", ")", "U", ",", "V", "=", "self", ".", "split_matrix", "(", "X", ")", "if", "(", "V", "==", "0", ")", ".", "all", "(", ")", "or", "(", "U", "==", ...
26.888889
19.222222
def report(args): """ Create report in html format """ logger.info("reading sequeces") data = load_data(args.json) logger.info("create profile") data = make_profile(data, os.path.join(args.out, "profiles"), args) logger.info("create database") make_database(data, "seqcluster.db", ar...
[ "def", "report", "(", "args", ")", ":", "logger", ".", "info", "(", "\"reading sequeces\"", ")", "data", "=", "load_data", "(", "args", ".", "json", ")", "logger", ".", "info", "(", "\"create profile\"", ")", "data", "=", "make_profile", "(", "data", ","...
33.307692
19.615385
def toFloat (str, default=None): """toFloat(str[, default]) -> float | default Converts the given string to a floating-point value. If the string could not be converted, default (None) is returned. NOTE: This method is *significantly* more effecient than toNumber() as it only attempts to parse fl...
[ "def", "toFloat", "(", "str", ",", "default", "=", "None", ")", ":", "value", "=", "default", "try", ":", "value", "=", "float", "(", "str", ")", "except", "ValueError", ":", "pass", "return", "value" ]
24.206897
22.068966
def _make_list(predictions, targets): """Helper: make predictions and targets lists, check they match on length.""" # Our models sometimes return predictions in lists, make it a list always. # TODO(lukaszkaiser): make abstractions for nested structures and refactor. if not isinstance(predictions, (list, tuple)...
[ "def", "_make_list", "(", "predictions", ",", "targets", ")", ":", "# Our models sometimes return predictions in lists, make it a list always.", "# TODO(lukaszkaiser): make abstractions for nested structures and refactor.", "if", "not", "isinstance", "(", "predictions", ",", "(", ...
58.090909
15.454545
def decode(self) -> Iterable: """Start of decode process. Returns final results.""" if self.data[0:1] not in (b'd', b'l'): return self.__wrap_with_tuple() return self.__parse()
[ "def", "decode", "(", "self", ")", "->", "Iterable", ":", "if", "self", ".", "data", "[", "0", ":", "1", "]", "not", "in", "(", "b'd'", ",", "b'l'", ")", ":", "return", "self", ".", "__wrap_with_tuple", "(", ")", "return", "self", ".", "__parse", ...
41.6
6.2
def add_veto(self, reason): """Adds a veto on this event. in reason of type str Reason for veto, could be null or empty string. """ if not isinstance(reason, basestring): raise TypeError("reason can only be an instance of type basestring") self._call("ad...
[ "def", "add_veto", "(", "self", ",", "reason", ")", ":", "if", "not", "isinstance", "(", "reason", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"reason can only be an instance of type basestring\"", ")", "self", ".", "_call", "(", "\"addVeto\"", ","...
32.090909
16.818182
def populate_pages(self, parent=None, child=5, depth=5): """Create a population of :class:`Page <pages.models.Page>` for testing purpose.""" User = get_user_model() from basic_cms.models import Content author = User.objects.all()[0] if depth == 0: return ...
[ "def", "populate_pages", "(", "self", ",", "parent", "=", "None", ",", "child", "=", "5", ",", "depth", "=", "5", ")", ":", "User", "=", "get_user_model", "(", ")", "from", "basic_cms", ".", "models", "import", "Content", "author", "=", "User", ".", ...
51.2
21.466667
def exif_name(self): ''' Name of file in the form {lat}_{lon}_{ca}_{datetime}_{filename}_{hash} ''' mapillary_description = json.loads(self.extract_image_description()) lat = None lon = None ca = None date_time = None if "MAPLatitude" in mapillar...
[ "def", "exif_name", "(", "self", ")", ":", "mapillary_description", "=", "json", ".", "loads", "(", "self", ".", "extract_image_description", "(", ")", ")", "lat", "=", "None", "lon", "=", "None", "ca", "=", "None", "date_time", "=", "None", "if", "\"MAP...
41.2
25.04
def remote_complete(self, failure=None): """ Called by the worker's L{buildbot_worker.base.WorkerForBuilderBase.commandComplete} to notify me the remote command has finished. @type failure: L{twisted.python.failure.Failure} or None @rtype: None """ self...
[ "def", "remote_complete", "(", "self", ",", "failure", "=", "None", ")", ":", "self", ".", "worker", ".", "messageReceivedFromWorker", "(", ")", "# call the real remoteComplete a moment later, but first return an", "# acknowledgement so the worker can retire the completion messag...
36.375
18.5
def set_mode_flag(self, flag, enable): ''' Enables/ disables MAV_MODE_FLAG @param flag The mode flag, see MAV_MODE_FLAG enum @param enable Enable the flag, (True/False) ''' if self.mavlink10(): mode = self.base_mode if (enable == True): ...
[ "def", "set_mode_flag", "(", "self", ",", "flag", ",", "enable", ")", ":", "if", "self", ".", "mavlink10", "(", ")", ":", "mode", "=", "self", ".", "base_mode", "if", "(", "enable", "==", "True", ")", ":", "mode", "=", "mode", "|", "flag", "elif", ...
38.842105
14
def get_calling_namespaces(): """Return the locals and globals for the function that called into this module in the current call stack.""" try: 1//0 except ZeroDivisionError: # Don't start iterating with the current stack-frame to # prevent creating reference cycles (f_back is safe). ...
[ "def", "get_calling_namespaces", "(", ")", ":", "try", ":", "1", "//", "0", "except", "ZeroDivisionError", ":", "# Don't start iterating with the current stack-frame to", "# prevent creating reference cycles (f_back is safe).", "frame", "=", "sys", ".", "exc_info", "(", ")"...
48.3
20.65
def render_to_response(self, context): """ When the user makes a search and there is only one result, redirect to the result's detail page rather than rendering the list. """ if self.redirect_if_one_result: if self.object_list.count() == 1 and self.form.is_bound: ...
[ "def", "render_to_response", "(", "self", ",", "context", ")", ":", "if", "self", ".", "redirect_if_one_result", ":", "if", "self", ".", "object_list", ".", "count", "(", ")", "==", "1", "and", "self", ".", "form", ".", "is_bound", ":", "return", "redire...
50
17.111111
def irfft2(a, s=None, axes=(-2, -1), norm=None): """ Compute the 2-dimensional inverse FFT of a real array. Parameters ---------- a : array_like The input array s : sequence of ints, optional Shape of the inverse FFT. axes : sequence of ints, optional The axes over w...
[ "def", "irfft2", "(", "a", ",", "s", "=", "None", ",", "axes", "=", "(", "-", "2", ",", "-", "1", ")", ",", "norm", "=", "None", ")", ":", "return", "irfftn", "(", "a", ",", "s", ",", "axes", ",", "norm", ")" ]
24.588235
20.176471
def make(parser): """provison Manila Share with HA""" s = parser.add_subparsers( title='commands', metavar='COMMAND', help='description', ) def install_f(args): install(args) install_parser = install_subparser(s) install_parser.set_defaults(func=install_f)
[ "def", "make", "(", "parser", ")", ":", "s", "=", "parser", ".", "add_subparsers", "(", "title", "=", "'commands'", ",", "metavar", "=", "'COMMAND'", ",", "help", "=", "'description'", ",", ")", "def", "install_f", "(", "args", ")", ":", "install", "("...
25.5
15.75
def ParseFileObject(self, parser_mediator, file_object): """Parses a Windows Prefetch file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. """ ...
[ "def", "ParseFileObject", "(", "self", ",", "parser_mediator", ",", "file_object", ")", ":", "scca_file", "=", "pyscca", ".", "file", "(", ")", "try", ":", "scca_file", ".", "open_file_object", "(", "file_object", ")", "except", "IOError", "as", "exception", ...
37.709091
20.227273
def register_on_state_changed(self, callback): """Set the callback function to consume on state changed events which are generated when the state of the machine changes. Callback receives a IStateChangeEvent object. Returns the callback_id """ event_type = library.VBoxE...
[ "def", "register_on_state_changed", "(", "self", ",", "callback", ")", ":", "event_type", "=", "library", ".", "VBoxEventType", ".", "on_state_changed", "return", "self", ".", "event_source", ".", "register_callback", "(", "callback", ",", "event_type", ")" ]
40.9
18.5
def connectionLost(self, reason): """ Mostly handles clean-up of node + candidate structures. Avoids memory exhaustion for a large number of connections. """ try: self.connected = False if debug: print(self.log_entry("CLOSED =", "no...
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "try", ":", "self", ".", "connected", "=", "False", "if", "debug", ":", "print", "(", "self", ".", "log_entry", "(", "\"CLOSED =\"", ",", "\"none\"", ")", ")", "# Every five minutes: cleanup\r", ...
47.4
19.646154
def unlock(self): """Unlock a previously locked server. """ cmd = {"fsyncUnlock": 1} with self._socket_for_writes() as sock_info: if sock_info.max_wire_version >= 4: try: sock_info.command("admin", cmd) except OperationFailu...
[ "def", "unlock", "(", "self", ")", ":", "cmd", "=", "{", "\"fsyncUnlock\"", ":", "1", "}", "with", "self", ".", "_socket_for_writes", "(", ")", "as", "sock_info", ":", "if", "sock_info", ".", "max_wire_version", ">=", "4", ":", "try", ":", "sock_info", ...
42.25
14.5
def upload( cls, files, metadata=None, tags=None, project=None, coerce_ascii=False, progressbar=None ): """Uploads a series of files to the One Codex server. Parameters ---------- files : `string` or `tuple` A single path to a file on the system, or a tuple conta...
[ "def", "upload", "(", "cls", ",", "files", ",", "metadata", "=", "None", ",", "tags", "=", "None", ",", "project", "=", "None", ",", "coerce_ascii", "=", "False", ",", "progressbar", "=", "None", ")", ":", "res", "=", "cls", ".", "_resource", "if", ...
38.210526
21.22807
def with_img_type(self, image_type): """ Returns the search results having the specified image type :param image_type: the desired image type (valid values are provided by the `pyowm.commons.enums.ImageTypeEnum` enum) :type image_type: `pyowm.commons.databoxes.ImageType` ins...
[ "def", "with_img_type", "(", "self", ",", "image_type", ")", ":", "assert", "isinstance", "(", "image_type", ",", "ImageType", ")", "return", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "image_type", "==", "image_type", ",", "self", ".", "m...
44.416667
23.25
def cycle_interface(self, increment=1): """Cycle through available interfaces in `increment` steps. Sign indicates direction.""" interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces] if self.interface in interfaces: next_index = (interfaces.index(self.in...
[ "def", "cycle_interface", "(", "self", ",", "increment", "=", "1", ")", ":", "interfaces", "=", "[", "i", "for", "i", "in", "netifaces", ".", "interfaces", "(", ")", "if", "i", "not", "in", "self", ".", "ignore_interfaces", "]", "if", "self", ".", "i...
51.083333
15.75
def msearch(self, body, index=None, doc_type=None, **query_params): """ Execute several search requests within the same API. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html>`_ :arg body: The request definitions (metadata-search request definition...
[ "def", "msearch", "(", "self", ",", "body", ",", "index", "=", "None", ",", "doc_type", "=", "None", ",", "*", "*", "query_params", ")", ":", "self", ".", "_es_parser", ".", "is_not_empty_params", "(", "body", ")", "path", "=", "self", ".", "_es_parser...
51.782609
21.347826
def resource_group_present(name, location, managed_by=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a resource group exists. :param name: Name of the resource group. :param location: The Azure location in which to create the resource group...
[ "def", "resource_group_present", "(", "name", ",", "location", ",", "managed_by", "=", "None", ",", "tags", "=", "None", ",", "connection_auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":...
29.971963
26.065421
def set_npn_advertise_callback(self, callback): """ Specify a callback function that will be called when offering `Next Protocol Negotiation <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server. :param callback: The callback function. It will be invoked with o...
[ "def", "set_npn_advertise_callback", "(", "self", ",", "callback", ")", ":", "_warn_npn", "(", ")", "self", ".", "_npn_advertise_helper", "=", "_NpnAdvertiseHelper", "(", "callback", ")", "self", ".", "_npn_advertise_callback", "=", "self", ".", "_npn_advertise_help...
45.833333
22.722222
def check_type(value, type_def): """Check if the value is in the type given in type_def. Args: value: the var to test. type_def: string representing the type in swagger. Returns: True if the type is correct, False otherwise. """ if type_def =...
[ "def", "check_type", "(", "value", ",", "type_def", ")", ":", "if", "type_def", "==", "'integer'", ":", "try", ":", "# We accept string with integer ex: '123'", "int", "(", "value", ")", "return", "True", "except", "ValueError", ":", "return", "isinstance", "(",...
39.142857
20.142857
def get_include_path(): """ Default include path using a tricky sys calls. """ f1 = os.path.basename(sys.argv[0]).lower() # script filename f2 = os.path.basename(sys.executable).lower() # Executable filename # If executable filename and script name are the same, we are if f1 == f2 or f2 =...
[ "def", "get_include_path", "(", ")", ":", "f1", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ".", "lower", "(", ")", "# script filename", "f2", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "ex...
36.714286
24.428571
def write_column(self, column, data, **keys): """ Write data to a column in this HDU This HDU must be a table HDU. parameters ---------- column: scalar string/integer The column in which to write. Can be the name or number (0 offset) column: ndarray...
[ "def", "write_column", "(", "self", ",", "column", ",", "data", ",", "*", "*", "keys", ")", ":", "firstrow", "=", "keys", ".", "get", "(", "'firstrow'", ",", "0", ")", "colnum", "=", "self", ".", "_extract_colnum", "(", "column", ")", "# need it to be ...
37.102041
19.387755
def close(self) -> None: """ To act as a file. """ if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream = None if s...
[ "def", "close", "(", "self", ")", "->", "None", ":", "if", "self", ".", "underlying_stream", ":", "if", "self", ".", "using_stdout", ":", "sys", ".", "stdout", "=", "self", ".", "underlying_stream", "else", ":", "sys", ".", "stderr", "=", "self", ".", ...
34.066667
11
def token_protected_endpoint(function): """Requires valid auth_token in POST to access An auth_token is built by sending a dictionary built from a Werkzeug.Request.form to the scheduler.auth.create_token function. """ @wraps(function) def decorated(*args, **kwargs): auth_token = request.form.get('auth_...
[ "def", "token_protected_endpoint", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "auth_token", "=", "request", ".", "form", ".", "get", "(", "'auth_token'", ")", ...
27.275862
19.37931
def _build_compatibility_members(binding, decorators=None): """Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can ...
[ "def", "_build_compatibility_members", "(", "binding", ",", "decorators", "=", "None", ")", ":", "decorators", "=", "decorators", "or", "dict", "(", ")", "# Allow optional site-level customization of the compatibility members.", "# This method does not need to be implemented in Q...
42.288136
24.20339
def createDatabase(self, name, **dbArgs) : "use dbArgs for arguments other than name. for a full list of arguments please have a look at arangoDB's doc" dbArgs['name'] = name payload = json.dumps(dbArgs, default=str) url = self.URL + "/database" r = self.session.post(url, data = ...
[ "def", "createDatabase", "(", "self", ",", "name", ",", "*", "*", "dbArgs", ")", ":", "dbArgs", "[", "'name'", "]", "=", "name", "payload", "=", "json", ".", "dumps", "(", "dbArgs", ",", "default", "=", "str", ")", "url", "=", "self", ".", "URL", ...
45.538462
15.538462
def _recursiveSetNodePath(self, nodePath): """ Sets the nodePath property and updates it for all children. """ self._nodePath = nodePath for childItem in self.childItems: childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
[ "def", "_recursiveSetNodePath", "(", "self", ",", "nodePath", ")", ":", "self", ".", "_nodePath", "=", "nodePath", "for", "childItem", "in", "self", ".", "childItems", ":", "childItem", ".", "_recursiveSetNodePath", "(", "nodePath", "+", "'/'", "+", "childItem...
46.333333
8.333333
def redirect(self, id, name, **options): """ Forwards an incoming call to another destination / phone number before answering it. Argument: id is a String Argument: name is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs...
[ "def", "redirect", "(", "self", ",", "id", ",", "name", ",", "*", "*", "options", ")", ":", "self", ".", "_steps", ".", "append", "(", "Redirect", "(", "id", ",", "name", ",", "*", "*", "options", ")", ".", "obj", ")" ]
44.666667
14.222222
def create_introspect_response(self, uri, http_method='POST', body=None, headers=None): """Create introspect valid or invalid response If the authorization server is unable to determine the state of the token without additional information, it SHOULD return ...
[ "def", "create_introspect_response", "(", "self", ",", "uri", ",", "http_method", "=", "'POST'", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "resp_headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Cache-Control'", ":"...
40.878788
18.060606
def export(self, output=Mimetypes.PLAINTEXT, exclude=None, **kwargs): """ Export the collection item in the Mimetype required. ..note:: If current implementation does not have special mimetypes, reuses default_export method :param output: Mimetype to export to (Uses Mimetypes) :type ou...
[ "def", "export", "(", "self", ",", "output", "=", "Mimetypes", ".", "PLAINTEXT", ",", "exclude", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "getTextualNode", "(", ")", ".", "export", "(", "output", ",", "exclude", ")" ]
46.166667
24.416667
def getdict(self, crop=True): """Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array. """ D = self.Y if crop: D = cr.bcrop(D, self.cri.dsz, self.cri.dimN) return D
[ "def", "getdict", "(", "self", ",", "crop", "=", "True", ")", ":", "D", "=", "self", ".", "Y", "if", "crop", ":", "D", "=", "cr", ".", "bcrop", "(", "D", ",", "self", ".", "cri", ".", "dsz", ",", "self", ".", "cri", ".", "dimN", ")", "retur...
28.555556
16.111111
def update(gandi, resource, memory, cores, console, password, background, reboot): """Update a virtual machine. Resource can be a Hostname or an ID """ pwd = None if password: pwd = click.prompt('password', hide_input=True, confirmation_prompt=True) ...
[ "def", "update", "(", "gandi", ",", "resource", ",", "memory", ",", "cores", ",", "console", ",", "password", ",", "background", ",", "reboot", ")", ":", "pwd", "=", "None", "if", "password", ":", "pwd", "=", "click", ".", "prompt", "(", "'password'", ...
29.692308
21.884615
def set_index(self, index): """Display the data of the given index :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ item = index.internalPointer() self.actionunit = item.internal_data()...
[ "def", "set_index", "(", "self", ",", "index", ")", ":", "item", "=", "index", ".", "internalPointer", "(", ")", "self", ".", "actionunit", "=", "item", ".", "internal_data", "(", ")", "self", ".", "setEnabled", "(", "bool", "(", "self", ".", "actionun...
31.083333
11.833333
def dcm(self, dcm): """ Set the DCM :param dcm: Matrix3 """ assert(isinstance(dcm, Matrix3)) self._dcm = dcm.copy() # mark other representations as outdated, will get generated on next # read self._q = None self._euler = None
[ "def", "dcm", "(", "self", ",", "dcm", ")", ":", "assert", "(", "isinstance", "(", "dcm", ",", "Matrix3", ")", ")", "self", ".", "_dcm", "=", "dcm", ".", "copy", "(", ")", "# mark other representations as outdated, will get generated on next", "# read", "self"...
22.692308
18.384615
def get_joining_type_property(value, is_bytes=False): """Get `JOINING TYPE` property.""" obj = unidata.ascii_joining_type if is_bytes else unidata.unicode_joining_type if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['joiningtype'].get(negated, negated) ...
[ "def", "get_joining_type_property", "(", "value", ",", "is_bytes", "=", "False", ")", ":", "obj", "=", "unidata", ".", "ascii_joining_type", "if", "is_bytes", "else", "unidata", ".", "unicode_joining_type", "if", "value", ".", "startswith", "(", "'^'", ")", ":...
34.083333
26.583333
def second(self): '''set unit to second''' self.magnification = 1 self._update(self.baseNumber, self.magnification) return self
[ "def", "second", "(", "self", ")", ":", "self", ".", "magnification", "=", "1", "self", ".", "_update", "(", "self", ".", "baseNumber", ",", "self", ".", "magnification", ")", "return", "self" ]
31
15.8
def kmodels(wordlen: int, k: int, input=None, output=None): """Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [1]. Note that this is equivalent to (~x < k). - TODO: Add automated simplification so that the circuits are equiv. [1]: Ch...
[ "def", "kmodels", "(", "wordlen", ":", "int", ",", "k", ":", "int", ",", "input", "=", "None", ",", "output", "=", "None", ")", ":", "assert", "0", "<=", "k", "<", "2", "**", "wordlen", "if", "output", "is", "None", ":", "output", "=", "_fresh", ...
29.657143
20.4
def set_feature_flag_courses(self, feature, course_id, state=None): """ Set feature flag. Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets a feature flag for the same feature in any state other than "allowed". """ ...
[ "def", "set_feature_flag_courses", "(", "self", ",", "feature", ",", "course_id", ",", "state", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", ...
48.333333
28.5
def radiansBetween(self, other): ''' :param: other - Line subclass :return: float Returns the angle measured between two lines in radians with a range of [0, 2 * math.pi]. ''' # a dot b = |a||b| * cos(theta) # a dot b / |a||b| = cos(theta) # cos-...
[ "def", "radiansBetween", "(", "self", ",", "other", ")", ":", "# a dot b = |a||b| * cos(theta)", "# a dot b / |a||b| = cos(theta)", "# cos-1(a dot b / |a||b|) = theta", "# translate each line so that it passes through the origin and", "# produce a new point whose distance (magnitude) from th...
30.75
20.535714
def get_context_data(self, form, *args, **kwargs): """ Returns the template context for a step. You can overwrite this method to add more data for all or some steps. This method returns a dictionary containing the rendered form step. Available template context variables are: ...
[ "def", "get_context_data", "(", "self", ",", "form", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "WizardView", ",", "self", ")", ".", "get_context_data", "(", "*", "args", ",", "*", "*", "kwargs", ")", "context"...
38.75
20.5
def usages(self): """Instance depends on the API version: * 2018-03-01-preview: :class:`UsagesOperations<azure.mgmt.storage.v2018_03_01_preview.operations.UsagesOperations>` * 2018-07-01: :class:`UsagesOperations<azure.mgmt.storage.v2018_07_01.operations.UsagesOperations>` """ ...
[ "def", "usages", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'usages'", ")", "if", "api_version", "==", "'2018-03-01-preview'", ":", "from", ".", "v2018_03_01_preview", ".", "operations", "import", "UsagesOperations", "as", ...
62.428571
36.857143
def match(self, node): """Returns match for a given parse tree node. Should return a true or false object (not necessarily a bool). It may return a non-empty dict of matching sub-nodes as returned by a matching pattern. Subclass may override. """ results = {"nod...
[ "def", "match", "(", "self", ",", "node", ")", ":", "results", "=", "{", "\"node\"", ":", "node", "}", "return", "self", ".", "pattern", ".", "match", "(", "node", ",", "results", ")", "and", "results" ]
34.545455
17.272727
def validate(self, value, validator): """Validates and returns the value. If the value does not validate against the schema, SchemaValidationError will be raised. :param value: A value to validate (usually a dict). :param validator: An instance of a jsonschema validator class, ...
[ "def", "validate", "(", "self", ",", "value", ",", "validator", ")", ":", "try", ":", "validator", ".", "validate", "(", "value", ")", "except", "Exception", "as", "e", ":", "logging", ".", "debug", "(", "e", ",", "exc_info", "=", "e", ")", "if", "...
37.09375
13.96875
def val_to_formatted_str(val, format, enum_set=None): """ Return a string representation of the value given format specified. :param val: a string holding an unsigned integer to convert :param format: a string holding a format which will be used to convert the data string :param enum_set: an iterable o...
[ "def", "val_to_formatted_str", "(", "val", ",", "format", ",", "enum_set", "=", "None", ")", ":", "type", "=", "format", "[", "0", "]", "bitwidth", "=", "int", "(", "format", "[", "1", ":", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", ")", ...
42.978723
21.148936
def all_info_files(self) : 'Returns a generator of "Path"s' try : for info_file in list_files_in_dir(self.info_dir): if not os.path.basename(info_file).endswith('.trashinfo') : self.on_non_trashinfo_found() else : yield ...
[ "def", "all_info_files", "(", "self", ")", ":", "try", ":", "for", "info_file", "in", "list_files_in_dir", "(", "self", ".", "info_dir", ")", ":", "if", "not", "os", ".", "path", ".", "basename", "(", "info_file", ")", ".", "endswith", "(", "'.trashinfo'...
39.3
16.9
def description(self): """Attribute that returns the plugin description from its docstring.""" lines = [] for line in self.__doc__.split('\n')[2:]: line = line.strip() if line: lines.append(line) return ' '.join(lines)
[ "def", "description", "(", "self", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "self", ".", "__doc__", ".", "split", "(", "'\\n'", ")", "[", "2", ":", "]", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ":", "lines",...
35.375
11.75
def header(self) -> dict: """ :return: Token header. :rtype: dict """ header = {} if isinstance(self._header, dict): header = self._header.copy() header.update(self._header) header.update({ 'type': 'JWT', 'alg': self...
[ "def", "header", "(", "self", ")", "->", "dict", ":", "header", "=", "{", "}", "if", "isinstance", "(", "self", ".", "_header", ",", "dict", ")", ":", "header", "=", "self", ".", "_header", ".", "copy", "(", ")", "header", ".", "update", "(", "se...
24.571429
11.571429
def register_layer(self, layer): """ Register the layer so that it's param will be trained. But the output of the layer will not be stacked. """ if type(layer) == Block: layer.fix() self.parameter_count += layer.parameter_count self.parameters.extend(l...
[ "def", "register_layer", "(", "self", ",", "layer", ")", ":", "if", "type", "(", "layer", ")", "==", "Block", ":", "layer", ".", "fix", "(", ")", "self", ".", "parameter_count", "+=", "layer", ".", "parameter_count", "self", ".", "parameters", ".", "ex...
45.6
15.8
def _get_csv_from_section(sections, crumbs, csvs): """ Get table name, variable name, and column values from paleo metadata :param dict sections: Metadata :param str crumbs: Crumbs :param dict csvs: Csv :return dict sections: Metadata :return dict csvs: Csv """ logger_csvs.info("ent...
[ "def", "_get_csv_from_section", "(", "sections", ",", "crumbs", ",", "csvs", ")", ":", "logger_csvs", ".", "info", "(", "\"enter get_csv_from_section: {}\"", ".", "format", "(", "crumbs", ")", ")", "_idx", "=", "0", "try", ":", "# Process the tables in section", ...
40.827586
25.517241
def open(self, mode='rb'): """Open file. The caller is responsible for closing the file. """ fs, path = self._get_fs() return fs.open(path, mode=mode)
[ "def", "open", "(", "self", ",", "mode", "=", "'rb'", ")", ":", "fs", ",", "path", "=", "self", ".", "_get_fs", "(", ")", "return", "fs", ".", "open", "(", "path", ",", "mode", "=", "mode", ")" ]
26.428571
11
def from_array(array): """ Deserialize a new PassportElementErrorFiles from a given dictionary. :return: new PassportElementErrorFiles instance. :rtype: PassportElementErrorFiles """ if array is None or not array: return None # end if assert_t...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "data", "=", "{", "}", "da...
36.809524
21.666667
def _sse_content_with_protocol(response, handler, **sse_kwargs): """ Sometimes we need the protocol object so that we can manipulate the underlying transport in tests. """ protocol = SseProtocol(handler, **sse_kwargs) finished = protocol.when_finished() response.deliverBody(protocol) r...
[ "def", "_sse_content_with_protocol", "(", "response", ",", "handler", ",", "*", "*", "sse_kwargs", ")", ":", "protocol", "=", "SseProtocol", "(", "handler", ",", "*", "*", "sse_kwargs", ")", "finished", "=", "protocol", ".", "when_finished", "(", ")", "respo...
30.363636
15.272727
def _get_values(self, rdn): """ Returns a dict of prepped values contained in an RDN :param rdn: A RelativeDistinguishedName object :return: A dict object with unicode strings of NameTypeAndValue value field values that have been prepped for comparis...
[ "def", "_get_values", "(", "self", ",", "rdn", ")", ":", "output", "=", "{", "}", "[", "output", ".", "update", "(", "[", "(", "ntv", "[", "'type'", "]", ".", "native", ",", "ntv", ".", "prepped_value", ")", "]", ")", "for", "ntv", "in", "rdn", ...
29.666667
22.6
def tmsiReallocationCommand(): """TMSI REALLOCATION COMMAND Section 9.2.17""" a = TpPd(pd=0x5) b = MessageType(mesType=0x1a) # 00011010 c = LocalAreaId() d = MobileId() packet = a / b / c / d return packet
[ "def", "tmsiReallocationCommand", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x5", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x1a", ")", "# 00011010", "c", "=", "LocalAreaId", "(", ")", "d", "=", "MobileId", "(", ")", "packet", "=", ...
28.375
14.125
def main(): """Get status from APC NIS and print output on stdout.""" # No need to use "proper" names on such simple code. # pylint: disable=invalid-name p = argparse.ArgumentParser() p.add_argument("--host", default="localhost") p.add_argument("--port", type=int, default=3551) p.add_argumen...
[ "def", "main", "(", ")", ":", "# No need to use \"proper\" names on such simple code.", "# pylint: disable=invalid-name", "p", "=", "argparse", ".", "ArgumentParser", "(", ")", "p", ".", "add_argument", "(", "\"--host\"", ",", "default", "=", "\"localhost\"", ")", "p"...
38.307692
13.923077
def extract_event_info(dstore, eidx): """ Extract information about the given event index. Example: http://127.0.0.1:8800/v1/calc/30/extract/event_info/0 """ event = dstore['events'][int(eidx)] serial = int(event['eid'] // TWO32) ridx = list(dstore['ruptures']['serial']).index(serial) ...
[ "def", "extract_event_info", "(", "dstore", ",", "eidx", ")", ":", "event", "=", "dstore", "[", "'events'", "]", "[", "int", "(", "eidx", ")", "]", "serial", "=", "int", "(", "event", "[", "'eid'", "]", "//", "TWO32", ")", "ridx", "=", "list", "(",...
36.333333
12
def unit_defs_from_sheet(sheet, column_names): """A generator that parses a worksheet containing UNECE code definitions. Args: sheet: An xldr.sheet object representing a UNECE code worksheet. column_names: A list/tuple with the expected column names corresponding to the unit name, code an...
[ "def", "unit_defs_from_sheet", "(", "sheet", ",", "column_names", ")", ":", "seen", "=", "set", "(", ")", "try", ":", "col_indices", "=", "{", "}", "rows", "=", "sheet", ".", "get_rows", "(", ")", "# Find the indices for the columns we care about.", "for", "id...
36.351351
19.972973
def get_stats(self): """ Get some stats on the packages in the registry """ try: query = { # We only care about the aggregations, so don't return the hits 'size': 0, 'aggs': { 'num_packages': { ...
[ "def", "get_stats", "(", "self", ")", ":", "try", ":", "query", "=", "{", "# We only care about the aggregations, so don't return the hits", "'size'", ":", "0", ",", "'aggs'", ":", "{", "'num_packages'", ":", "{", "'value_count'", ":", "{", "'field'", ":", "'id'...
32.485714
15.571429
def as_matrix_transform(transform): """ Simplify a transform to a single matrix transform, which makes it a lot faster to compute transformations. Raises a TypeError if the transform cannot be simplified. """ if isinstance(transform, ChainTransform): matrix = np.identity(4) for ...
[ "def", "as_matrix_transform", "(", "transform", ")", ":", "if", "isinstance", "(", "transform", ",", "ChainTransform", ")", ":", "matrix", "=", "np", ".", "identity", "(", "4", ")", "for", "tr", "in", "transform", ".", "transforms", ":", "# We need to do the...
44.888889
16.074074
def parse_proteins(self,OrganismDB): ''' Iterate through all the proteins in the DB, creates a hit_dataframe for each protein. ''' for org in OrganismDB.organisms: for prot in org.proteins: if len(prot.hmm_hit_list) > 0: try: ...
[ "def", "parse_proteins", "(", "self", ",", "OrganismDB", ")", ":", "for", "org", "in", "OrganismDB", ".", "organisms", ":", "for", "prot", "in", "org", ".", "proteins", ":", "if", "len", "(", "prot", ".", "hmm_hit_list", ")", ">", "0", ":", "try", ":...
36.214286
19.214286
def transform(self, X): """Apply dimensionality reduction on X. X is projected on the first principal components previous extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples in the numb...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "[", "\"mean_\"", ",", "\"components_\"", "]", ",", "all_or_any", "=", "all", ")", "# X = check_array(X)", "if", "self", ".", "mean_", "is", "not", "None", ":", "X"...
31
21.076923
def _default_styles_xml(cls): """ Return a bytestream containing XML for a default styles part. """ path = os.path.join( os.path.split(__file__)[0], '..', 'templates', 'default-styles.xml' ) with open(path, 'rb') as f: xml_bytes = f.rea...
[ "def", "_default_styles_xml", "(", "cls", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "split", "(", "__file__", ")", "[", "0", "]", ",", "'..'", ",", "'templates'", ",", "'default-styles.xml'", ")", "with", "op...
30.727273
12.545455
def parse_lines(self, code): """ Return a list of the parsed code For each line, return a three-tuple containing: 1. The label 2. The instruction 3. Any arguments or parameters An element in the tuple may be None or '' if it did not find anything :param ...
[ "def", "parse_lines", "(", "self", ",", "code", ")", ":", "remove_comments", "=", "re", ".", "compile", "(", "r'^([^;@\\n]*);?.*$'", ",", "re", ".", "MULTILINE", ")", "code", "=", "'\\n'", ".", "join", "(", "remove_comments", ".", "findall", "(", "code", ...
47.285714
25.095238
def _get_repo_filter(self, query): """ Apply repository wide side filter / mask query """ if self.filter is not None: return query.extra(where=[self.filter]) return query
[ "def", "_get_repo_filter", "(", "self", ",", "query", ")", ":", "if", "self", ".", "filter", "is", "not", "None", ":", "return", "query", ".", "extra", "(", "where", "=", "[", "self", ".", "filter", "]", ")", "return", "query" ]
30.857143
8
def fromMimeData(self, data): """ Paste the clipboard data at the current cursor position. This method also adds another undo-object to the undo-stack. ..note: This method forcefully interrupts the ``QsciInternal`` pasting mechnism by returning an empty MIME data elemen...
[ "def", "fromMimeData", "(", "self", ",", "data", ")", ":", "# Only insert the element if it is available in plain text.", "if", "data", ".", "hasText", "(", ")", ":", "self", ".", "insert", "(", "data", ".", "text", "(", ")", ")", "# Tell the underlying QsciScinti...
37.842105
21.421053
def _remove_brackets(x, i): """Removes curly brackets surrounding the Cite element at index 'i' in the element list 'x'. It is assumed that the modifier has been extracted. Empty strings are deleted from 'x'.""" assert x[i]['t'] == 'Cite' assert i > 0 and i < len(x) - 1 # Check if the surrou...
[ "def", "_remove_brackets", "(", "x", ",", "i", ")", ":", "assert", "x", "[", "i", "]", "[", "'t'", "]", "==", "'Cite'", "assert", "i", ">", "0", "and", "i", "<", "len", "(", "x", ")", "-", "1", "# Check if the surrounding elements are strings", "if", ...
30.869565
17.565217
def create_aside(self, definition_id, usage_id, aside_type): """Create the aside.""" return ( self.ASIDE_DEFINITION_ID(definition_id, aside_type), self.ASIDE_USAGE_ID(usage_id, aside_type), )
[ "def", "create_aside", "(", "self", ",", "definition_id", ",", "usage_id", ",", "aside_type", ")", ":", "return", "(", "self", ".", "ASIDE_DEFINITION_ID", "(", "definition_id", ",", "aside_type", ")", ",", "self", ".", "ASIDE_USAGE_ID", "(", "usage_id", ",", ...
39
18.833333
def visit_FunctionDef(self, node): ''' Initialise aliasing default value before visiting. Add aliasing values for : - Pythonic - globals declarations - current function arguments ''' self.aliases = IntrinsicAliases.copy() self.aliases...
[ "def", "visit_FunctionDef", "(", "self", ",", "node", ")", ":", "self", ".", "aliases", "=", "IntrinsicAliases", ".", "copy", "(", ")", "self", ".", "aliases", ".", "update", "(", "(", "f", ".", "name", ",", "{", "f", "}", ")", "for", "f", "in", ...
40.927536
15.594203
def acquire(self): """ Locks the account. Returns True on success, False if the account is thread-local and must not be locked. """ if self.host: self.parent.send(('acquire-account-for-host', self.host)) elif self.account_hash: self.parent.send(('a...
[ "def", "acquire", "(", "self", ")", ":", "if", "self", ".", "host", ":", "self", ".", "parent", ".", "send", "(", "(", "'acquire-account-for-host'", ",", "self", ".", "host", ")", ")", "elif", "self", ".", "account_hash", ":", "self", ".", "parent", ...
31.25
16.333333
def add_extension(module, name, code): """Register an extension code.""" code = int(code) if not 1 <= code <= 0x7fffffff: raise ValueError, "code out of range" key = (module, name) if (_extension_registry.get(key) == code and _inverted_registry.get(code) == key): return # Red...
[ "def", "add_extension", "(", "module", ",", "name", ",", "code", ")", ":", "code", "=", "int", "(", "code", ")", "if", "not", "1", "<=", "code", "<=", "0x7fffffff", ":", "raise", "ValueError", ",", "\"code out of range\"", "key", "=", "(", "module", ",...
42.941176
10.882353
def create_summary_metadata(display_name, description, num_thresholds): """Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data. Arguments: display_name: The display name used in TensorBoard. description: The description to show in TensorBoard. num_thresholds: The number of thresholds...
[ "def", "create_summary_metadata", "(", "display_name", ",", "description", ",", "num_thresholds", ")", ":", "pr_curve_plugin_data", "=", "plugin_data_pb2", ".", "PrCurvePluginData", "(", "version", "=", "PROTO_VERSION", ",", "num_thresholds", "=", "num_thresholds", ")",...
39.9
16.85
def HTypeFromIntfMap(interfaceMap): """ Generate flattened register map for HStruct :param interfaceMap: sequence of tuple (type, name) or (will create standard struct field member) interface or (will create a struct field from interface) instance of hdl type (is used as padding) ...
[ "def", "HTypeFromIntfMap", "(", "interfaceMap", ")", ":", "structFields", "=", "[", "]", "for", "m", "in", "interfaceMap", ":", "f", "=", "HTypeFromIntfMapItem", "(", "m", ")", "structFields", ".", "append", "(", "f", ")", "return", "HStruct", "(", "*", ...
34.238095
15.380952
def get_file_urls_map(self): """stub""" file_urls_map = {} if self.has_files(): for label in self.my_osid_object._my_map['fileIds']: label_map = self.my_osid_object._my_map['fileIds'][label] if 'assetContentId' in label_map and bool(label_map['assetCon...
[ "def", "get_file_urls_map", "(", "self", ")", ":", "file_urls_map", "=", "{", "}", "if", "self", ".", "has_files", "(", ")", ":", "for", "label", "in", "self", ".", "my_osid_object", ".", "_my_map", "[", "'fileIds'", "]", ":", "label_map", "=", "self", ...
50.058824
19
def _init_tag_params(self, tag, params): """ Alternative constructor used when the tag parameters are added to the HTMLElement (HTMLElement(tag, params)). This method just creates string and then pass it to the :meth:`_init_tag`. Args: tag (str): HTML tag as...
[ "def", "_init_tag_params", "(", "self", ",", "tag", ",", "params", ")", ":", "self", ".", "_element", "=", "tag", "self", ".", "params", "=", "params", "self", ".", "_parseTagName", "(", ")", "self", ".", "_istag", "=", "True", "self", ".", "_isendtag"...
30.3
16
def verify_pubkey_sig(self, message, sig): ''' Wraps the verify_signature method so we have additional checks. :rtype: bool :return: Success or failure of public key verification ''' if self.opts['master_sign_key_name']: path = os.path.join(self.opts[...
[ "def", "verify_pubkey_sig", "(", "self", ",", "message", ",", "sig", ")", ":", "if", "self", ".", "opts", "[", "'master_sign_key_name'", "]", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "opts", "[", "'pki_dir'", "]", ",", "sel...
38.65
20.75
def filename_for(self, subpath): """ Returns the relative filename for the specified subpath, or the root filename if subpath is None. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory. """ try: filename = ...
[ "def", "filename_for", "(", "self", ",", "subpath", ")", ":", "try", ":", "filename", "=", "self", ".", "readme_for", "(", "subpath", ")", "return", "os", ".", "path", ".", "relpath", "(", "filename", ",", "self", ".", "root_directory", ")", "except", ...
35.230769
14.769231
def filter(self, result): """ Filter the specified result based on query criteria. @param result: A potential result. @type result: L{sxbase.SchemaObject} @return: True if result should be excluded. @rtype: boolean """ if result is None: return...
[ "def", "filter", "(", "self", ",", "result", ")", ":", "if", "result", "is", "None", ":", "return", "True", "reject", "=", "result", "in", "self", ".", "history", "if", "reject", ":", "log", ".", "debug", "(", "'result %s, rejected by\\n%s'", ",", "Repr"...
33.214286
12.357143
def output_str(f): """Create a function that always return instances of `str`. This decorator is useful when the returned string is to be used with libraries that do not support ̀`unicode` in Python 2, but work fine with Python 3 `str` objects. """ if six.PY2: #@functools.wraps(f) ...
[ "def", "output_str", "(", "f", ")", ":", "if", "six", ".", "PY2", ":", "#@functools.wraps(f)", "def", "new_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ".", "encode", "(",...
31.142857
18.285714
def skipline(self): """ Skip the next line and returns position and size of line. Raises IOError if pre- and suffix of line do not match. """ position = self.tell() prefix = self._fix() self.seek(prefix, 1) # skip content suffix = self._fix() if ...
[ "def", "skipline", "(", "self", ")", ":", "position", "=", "self", ".", "tell", "(", ")", "prefix", "=", "self", ".", "_fix", "(", ")", "self", ".", "seek", "(", "prefix", ",", "1", ")", "# skip content", "suffix", "=", "self", ".", "_fix", "(", ...
28.214286
15.071429
def key(self): """Embedded supports curies.""" if self.curie is None: return self.name return ":".join((self.curie.name, self.name))
[ "def", "key", "(", "self", ")", ":", "if", "self", ".", "curie", "is", "None", ":", "return", "self", ".", "name", "return", "\":\"", ".", "join", "(", "(", "self", ".", "curie", ".", "name", ",", "self", ".", "name", ")", ")" ]
32.8
12.2
def convert(path, source_fmt, target_fmt, select='result:mrs', properties=True, show_status=False, predicate_modifiers=False, color=False, pretty_print=False, indent=None): """ Convert between various DELPH-IN Semantics representations. Args: path (str, file): filename, test...
[ "def", "convert", "(", "path", ",", "source_fmt", ",", "target_fmt", ",", "select", "=", "'result:mrs'", ",", "properties", "=", "True", ",", "show_status", "=", "False", ",", "predicate_modifiers", "=", "False", ",", "color", "=", "False", ",", "pretty_prin...
38.717172
18.232323
def cred_def_id2seq_no(cd_id: str) -> int: """ Given a credential definition identifier, return its schema sequence number. Raise BadIdentifier on input that is not a credential definition identifier. :param cd_id: credential definition identifier :return: sequence number """ if ok_cred_de...
[ "def", "cred_def_id2seq_no", "(", "cd_id", ":", "str", ")", "->", "int", ":", "if", "ok_cred_def_id", "(", "cd_id", ")", ":", "return", "int", "(", "cd_id", ".", "split", "(", "':'", ")", "[", "3", "]", ")", "# sequence number is token at 0-based position 3"...
41
23.666667
def _download_datasets(): """Utility to download datasets into package source""" def filepath(*args): return abspath(join(dirname(__file__), '..', 'vega_datasets', *args)) dataset_listing = {} for name in DATASETS_TO_DOWNLOAD: data = Dataset(name) url = data.url filename ...
[ "def", "_download_datasets", "(", ")", ":", "def", "filepath", "(", "*", "args", ")", ":", "return", "abspath", "(", "join", "(", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'vega_datasets'", ",", "*", "args", ")", ")", "dataset_listing", "=", ...
45
16
def _merge_cfgnodes(self, cfgnode_0, cfgnode_1): """ Merge two adjacent CFGNodes into one. :param CFGNode cfgnode_0: The first CFGNode. :param CFGNode cfgnode_1: The second CFGNode. :return: None """ assert cfgnode_0.addr + cfgnode_0.size ...
[ "def", "_merge_cfgnodes", "(", "self", ",", "cfgnode_0", ",", "cfgnode_1", ")", ":", "assert", "cfgnode_0", ".", "addr", "+", "cfgnode_0", ".", "size", "==", "cfgnode_1", ".", "addr", "addr0", ",", "addr1", "=", "cfgnode_0", ".", "addr", ",", "cfgnode_1", ...
36.775
14.625
def _inner_take_over_or_update(self, full_values=None, current_values=None, value_indices=None): """ This is for automatic updates of values in the inner loop of missing data handling. Both arguments are dictionaries and the values in full_values will be updated by the current_gradients....
[ "def", "_inner_take_over_or_update", "(", "self", ",", "full_values", "=", "None", ",", "current_values", "=", "None", ",", "value_indices", "=", "None", ")", ":", "for", "key", "in", "current_values", ".", "keys", "(", ")", ":", "if", "value_indices", "is",...
45.736842
26.210526
def a_alpha_and_derivatives(self, T, full=True, quick=True): r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `a...
[ "def", "a_alpha_and_derivatives", "(", "self", ",", "T", ",", "full", "=", "True", ",", "quick", "=", "True", ")", ":", "if", "not", "full", ":", "return", "self", ".", "a", "else", ":", "a_alpha", "=", "self", ".", "a", "da_alpha_dT", "=", "0.0", ...
33.05
20.15
def select_server(self, selector, server_selection_timeout=None, address=None): """Like select_servers, but choose a random server if several match.""" return random.choice(self.select_servers(selector, ...
[ "def", "select_server", "(", "self", ",", "selector", ",", "server_selection_timeout", "=", "None", ",", "address", "=", "None", ")", ":", "return", "random", ".", "choice", "(", "self", ".", "select_servers", "(", "selector", ",", "server_selection_timeout", ...
51.375
14
def make_pdb(self): """Generates a PDB string for the `Monomer`.""" pdb_str = write_pdb( [self], ' ' if not self.parent else self.parent.id) return pdb_str
[ "def", "make_pdb", "(", "self", ")", ":", "pdb_str", "=", "write_pdb", "(", "[", "self", "]", ",", "' '", "if", "not", "self", ".", "parent", "else", "self", ".", "parent", ".", "id", ")", "return", "pdb_str" ]
37.4
14.8
def get_parm(self, key): """Get parameter of FIO""" if key in self.__parm.keys(): return self.__parm[key] return None
[ "def", "get_parm", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "__parm", ".", "keys", "(", ")", ":", "return", "self", ".", "__parm", "[", "key", "]", "return", "None" ]
21.285714
17.857143
def _mask_space(self, data): """Mask space pixels""" geomask = get_geostationary_mask(area=self.area) return data.where(geomask)
[ "def", "_mask_space", "(", "self", ",", "data", ")", ":", "geomask", "=", "get_geostationary_mask", "(", "area", "=", "self", ".", "area", ")", "return", "data", ".", "where", "(", "geomask", ")" ]
37.25
8.5
def is_separating(direction, polygon1, polygon2): """Checks if a given ``direction`` is a separating line for two polygons. .. note:: This is a helper for :func:`_polygon_collide`. Args: direction (numpy.ndarray): A 1D ``2``-array (``float64``) of a potential separating line fo...
[ "def", "is_separating", "(", "direction", ",", "polygon1", ",", "polygon2", ")", ":", "# NOTE: We assume throughout that ``norm_squared != 0``. If it **were**", "# zero that would mean the ``direction`` corresponds to an", "# invalid edge.", "norm_squared", "=", "direction"...
41.026316
18.552632
def subs(self, substitutions, default=None, simplify=False): """ Return an expression where the expression or all subterms equal to a key expression are substituted with the corresponding value expression using a mapping of: {expr->expr to substitute.} Return this expression unm...
[ "def", "subs", "(", "self", ",", "substitutions", ",", "default", "=", "None", ",", "simplify", "=", "False", ")", ":", "# shortcut: check if we have our whole expression as a possible", "# subsitution source", "for", "expr", ",", "substitution", "in", "substitutions", ...
43.315789
22.052632