index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
28,556
ometa.runtime
eatWhitespace
Consume input until a non-whitespace character is reached.
def eatWhitespace(self): """ Consume input until a non-whitespace character is reached. """ while True: try: c, e = self.input.head() except EOFError as err: e = err break tl = self.input.tail() if c.isspace(): self.input = tl else: break return True, e
(self)
28,580
ometa.runtime
ParseError
?Redo from start
class ParseError(Exception): """ ?Redo from start """ def __init__(self, input, position, message, trail=None): Exception.__init__(self, position, message) self.position = position self.error = message or [] self.input = input self.trail = trail or [] def __eq__(self, other): if other.__class__ == self.__class__: return (self.position, self.error) == (other.position, other.error) def mergeWith(self, other): """ Merges in another error's error and trail. """ self.error = list(set(self.error + other.error)) self.args = (self.position, self.error) self.trail = other.trail or self.trail or [] def formatReason(self): if not self.error: return "Syntax error" if len(self.error) == 1: if self.error[0][0] == 'message': return self.error[0][1] if self.error[0][2] == None: return 'expected a %s' % (self.error[0][1]) else: typ = self.error[0][1] if typ is None: if isinstance(self.input, basestring): typ = 'character' else: typ = 'object' return 'expected the %s %r' % (typ, self.error[0][2]) else: bits = [] for s in self.error: if s[0] == 'message': desc = s[1] elif s[2] is None: desc = "a " + s[1] else: desc = repr(s[2]) if s[1] is not None: desc = "%s %s" % (s[1], desc) bits.append(desc) bits.sort() return "expected one of %s, or %s" % (', '.join(bits[:-1]), bits[-1]) def formatError(self): """ Return a pretty string containing error info about string parsing failure. """ #de-twineifying lines = str(self.input).split('\n') counter = 0 lineNo = 1 columnNo = 0 for line in lines: newCounter = counter + len(line) if newCounter > self.position: columnNo = self.position - counter break else: counter += len(line) + 1 lineNo += 1 reason = self.formatReason() return ('\n' + line + '\n' + (' ' * columnNo + '^') + "\nParse error at line %s, column %s: %s. trail: [%s]\n" % (lineNo, columnNo, reason, ' '.join(self.trail))) def __str__(self): return self.formatError() def withMessage(self, msg): return ParseError(self.input, self.position, msg, self.trail)
(input, position, message, trail=None)
28,582
ometa.runtime
__init__
null
def __init__(self, input, position, message, trail=None): Exception.__init__(self, position, message) self.position = position self.error = message or [] self.input = input self.trail = trail or []
(self, input, position, message, trail=None)
28,588
parsley
_GrammarWrapper
A wrapper for Parsley grammar instances. To invoke a Parsley rule, invoke a method with that name -- this turns x(input).foo() calls into grammar.apply("foo") calls.
class _GrammarWrapper(object): """ A wrapper for Parsley grammar instances. To invoke a Parsley rule, invoke a method with that name -- this turns x(input).foo() calls into grammar.apply("foo") calls. """ def __init__(self, grammar, input): self._grammar = grammar self._input = input #so pydoc doesn't get trapped in the __getattr__ self.__name__ = _GrammarWrapper.__name__ def __getattr__(self, name): """ Return a function that will instantiate a grammar and invoke the named rule. :param name: Rule name. """ def invokeRule(*args, **kwargs): """ Invoke a Parsley rule. Passes any positional args to the rule. """ try: ret, err = self._grammar.apply(name, *args) except ParseError as e: self._grammar.considerError(e) err = self._grammar.currentError else: try: extra, _ = self._grammar.input.head() except EOFError: return ret else: # problem is that input remains, so: err = ParseError(err.input, err.position + 1, [["message", "expected EOF"]], err.trail) raise err return invokeRule
(grammar, input)
28,589
parsley
__getattr__
Return a function that will instantiate a grammar and invoke the named rule. :param name: Rule name.
def __getattr__(self, name): """ Return a function that will instantiate a grammar and invoke the named rule. :param name: Rule name. """ def invokeRule(*args, **kwargs): """ Invoke a Parsley rule. Passes any positional args to the rule. """ try: ret, err = self._grammar.apply(name, *args) except ParseError as e: self._grammar.considerError(e) err = self._grammar.currentError else: try: extra, _ = self._grammar.input.head() except EOFError: return ret else: # problem is that input remains, so: err = ParseError(err.input, err.position + 1, [["message", "expected EOF"]], err.trail) raise err return invokeRule
(self, name)
28,590
parsley
__init__
null
def __init__(self, grammar, input): self._grammar = grammar self._input = input #so pydoc doesn't get trapped in the __getattr__ self.__name__ = _GrammarWrapper.__name__
(self, grammar, input)
28,592
parsley
makeGrammar
Create a class from a Parsley grammar. :param source: A grammar, as a string. :param bindings: A mapping of variable names to objects. :param name: Name used for the generated class. :param unwrap: If True, return a parser class suitable for subclassing. If False, return a wrapper with the friendly API. :param extends: The superclass for the generated parser class. :param tracefunc: A 3-arg function which takes a fragment of grammar source, the start/end indexes in the grammar of this fragment, and a position in the input. Invoked for terminals and rule applications.
def makeGrammar(source, bindings, name='Grammar', unwrap=False, extends=wrapGrammar(OMetaBase), tracefunc=None): """ Create a class from a Parsley grammar. :param source: A grammar, as a string. :param bindings: A mapping of variable names to objects. :param name: Name used for the generated class. :param unwrap: If True, return a parser class suitable for subclassing. If False, return a wrapper with the friendly API. :param extends: The superclass for the generated parser class. :param tracefunc: A 3-arg function which takes a fragment of grammar source, the start/end indexes in the grammar of this fragment, and a position in the input. Invoked for terminals and rule applications. """ g = OMeta.makeGrammar(source, name).createParserClass( unwrapGrammar(extends), bindings) if unwrap: return g else: return wrapGrammar(g, tracefunc=tracefunc)
(source, bindings, name='Grammar', unwrap=False, extends=<function wrapGrammar.<locals>.makeParser at 0x7fdcfed068c0>, tracefunc=None)
28,593
parsley
makeProtocol
Create a Twisted ``Protocol`` factory from a Parsley grammar. :param source: A grammar, as a string. :param senderFactory: A one-argument callable that takes a twisted ``Transport`` and returns a :ref:`sender <senders>`. :param receiverFactory: A one-argument callable that takes the sender returned by the ``senderFactory`` and returns a :ref:`receiver <receivers>`. :param bindings: A mapping of variable names to objects which will be accessible from python code in the grammar. :param name: The name used for the generated grammar class. :returns: A nullary callable which will return an instance of :class:`~.ParserProtocol`.
def makeProtocol(source, senderFactory, receiverFactory, bindings=None, name='Grammar'): """ Create a Twisted ``Protocol`` factory from a Parsley grammar. :param source: A grammar, as a string. :param senderFactory: A one-argument callable that takes a twisted ``Transport`` and returns a :ref:`sender <senders>`. :param receiverFactory: A one-argument callable that takes the sender returned by the ``senderFactory`` and returns a :ref:`receiver <receivers>`. :param bindings: A mapping of variable names to objects which will be accessible from python code in the grammar. :param name: The name used for the generated grammar class. :returns: A nullary callable which will return an instance of :class:`~.ParserProtocol`. """ from ometa.protocol import ParserProtocol if bindings is None: bindings = {} grammar = OMeta(source).parseGrammar(name) return functools.partial( ParserProtocol, grammar, senderFactory, receiverFactory, bindings)
(source, senderFactory, receiverFactory, bindings=None, name='Grammar')
28,594
terml.quasiterm
quasiterm
Build a quasiterm from a string.
def quasiterm(termString): """ Build a quasiterm from a string. """ p = QTermParser(termString) result, error = p.apply("term") try: p.input.head() except EOFError: pass else: raise error return result
(termString)
28,595
parsley
stack
Stack some senders or receivers for ease of wrapping. ``stack(x, y, z)`` will return a factory usable as a sender or receiver factory which will, when called with a transport or sender as an argument, return ``x(y(z(argument)))``.
def stack(*wrappers): """ Stack some senders or receivers for ease of wrapping. ``stack(x, y, z)`` will return a factory usable as a sender or receiver factory which will, when called with a transport or sender as an argument, return ``x(y(z(argument)))``. """ if not wrappers: raise TypeError('at least one argument is required') def factory(arg): ret = wrappers[-1](arg) for wrapper in wrappers[-2::-1]: ret = wrapper(ret) return ret return factory
(*wrappers)
28,596
terml.parser
parseTerm
Build a TermL term tree from a string.
def parseTerm(termString): """ Build a TermL term tree from a string. """ p = TermLParser(termString) result, error = p.apply("term") try: p.input.head() except EOFError: pass else: raise error return result
(termString)
28,597
parsley
unwrapGrammar
Access the internal parser class for a Parsley grammar object.
def unwrapGrammar(w): """ Access the internal parser class for a Parsley grammar object. """ return getattr(w, '_grammarClass', None) or w
(w)
28,598
parsley
wrapGrammar
null
def wrapGrammar(g, tracefunc=None): def makeParser(input): """ Creates a parser for the given input, with methods for invoking each rule. :param input: The string you want to parse. """ parser = g(input) if tracefunc: parser._trace = tracefunc return _GrammarWrapper(parser, input) makeParser._grammarClass = g return makeParser
(g, tracefunc=None)
28,599
jupyter_server_fileid.extension
FileIdExtension
null
class FileIdExtension(ExtensionApp): name = "jupyter_server_fileid" file_id_manager_class = Type( klass=BaseFileIdManager, help="""File ID manager class to use. Defaults to ArbitraryFileIdManager. """, config=True, default_value=ArbitraryFileIdManager, ) file_id_manager = Instance( klass=BaseFileIdManager, help="An instance of the File ID manager.", allow_none=True ) handlers = [("/api/fileid/id", FileIDHandler), ("/api/fileid/path", FilePathHandler)] def initialize_settings(self): self.log.info(f"Configured File ID manager: {self.file_id_manager_class.__name__}") self.file_id_manager = self.file_id_manager_class( log=self.log, root_dir=self.serverapp.root_dir, config=self.config ) self.settings.update({"file_id_manager": self.file_id_manager}) # attach listener to contents manager events (requires jupyter_server~=2) if "event_logger" in self.settings: self.initialize_event_listeners() def initialize_event_listeners(self): handlers_by_action = self.file_id_manager.get_handlers_by_action() async def cm_listener(logger: EventLogger, schema_id: str, data: dict) -> None: handler = handlers_by_action[data["action"]] if handler: handler(data) self.settings["event_logger"].add_listener( schema_id="https://events.jupyter.org/jupyter_server/contents_service/v1", listener=cm_listener, ) self.log.info("Attached event listeners.")
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
28,600
traitlets.config.application
__del__
null
def __del__(self) -> None: self.close_handlers()
(self) -> NoneType
28,602
traitlets.config.application
__init__
null
def __init__(self, **kwargs: t.Any) -> None: SingletonConfigurable.__init__(self, **kwargs) # Ensure my class is in self.classes, so my attributes appear in command line # options and config files. cls = self.__class__ if cls not in self.classes: if self.classes is cls.classes: # class attr, assign instead of insert self.classes = [cls, *self.classes] else: self.classes.insert(0, self.__class__)
(self, **kwargs: Any) -> NoneType
28,606
traitlets.config.application
_classes_inc_parents
Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once.
def _classes_inc_parents( self, classes: ClassesType | None = None ) -> t.Generator[type[Configurable], None, None]: """Iterate through configurable classes, including configurable parents :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Children should always be after parents, and each class should only be yielded once. """ if classes is None: classes = self.classes seen = set() for c in classes: # We want to sort parents before children, so we reverse the MRO for parent in reversed(c.mro()): if issubclass(parent, Configurable) and (parent not in seen): seen.add(parent) yield parent
(self, classes: Optional[List[Type[traitlets.config.configurable.Configurable]]] = None) -> Generator[type[traitlets.config.configurable.Configurable], NoneType, NoneType]
28,607
traitlets.config.application
_classes_with_config_traits
Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves.
def _classes_with_config_traits( self, classes: ClassesType | None = None ) -> t.Generator[type[Configurable], None, None]: """ Yields only classes with configurable traits, and their subclasses. :param classes: The list of classes to iterate; if not set, uses :attr:`classes`. Thus, produced sample config-file will contain all classes on which a trait-value may be overridden: - either on the class owning the trait, - or on its subclasses, even if those subclasses do not define any traits themselves. """ if classes is None: classes = self.classes cls_to_config = OrderedDict( (cls, bool(cls.class_own_traits(config=True))) for cls in self._classes_inc_parents(classes) ) def is_any_parent_included(cls: t.Any) -> bool: return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__) # Mark "empty" classes for inclusion if their parents own-traits, # and loop until no more classes gets marked. # while True: to_incl_orig = cls_to_config.copy() cls_to_config = OrderedDict( (cls, inc_yes or is_any_parent_included(cls)) for cls, inc_yes in cls_to_config.items() ) if cls_to_config == to_incl_orig: break for cl, inc_yes in cls_to_config.items(): if inc_yes: yield cl
(self, classes: Optional[List[Type[traitlets.config.configurable.Configurable]]] = None) -> Generator[type[traitlets.config.configurable.Configurable], NoneType, NoneType]
28,608
jupyter_core.application
_config_dir_default
null
def _config_dir_default(self) -> str: return jupyter_config_dir()
(self) -> str
28,609
jupyter_server.extension.application
_config_file_name_default
The default config file name.
def _config_file_name_default(self): """The default config file name.""" if not self.name: return "" return "jupyter_{}_config".format(self.name.replace("-", "_"))
(self)
28,610
traitlets.config.application
_configure_logging
null
def _configure_logging(self) -> None: config = self.get_default_logging_config() nested_update(config, self.logging_config or {}) dictConfig(config) # make a note that we have configured logging self._logging_configured = True
(self) -> NoneType
28,611
traitlets.config.application
_create_loader
null
def _create_loader( self, argv: list[str] | None, aliases: StrDict, flags: StrDict, classes: ClassesType | None, ) -> KVArgParseConfigLoader: return KVArgParseConfigLoader( argv, aliases, flags, classes=classes, log=self.log, subcommands=self.subcommands )
(self, argv: list[str] | None, aliases: Dict[str, Any], flags: Dict[str, Any], classes: Optional[List[Type[traitlets.config.configurable.Configurable]]]) -> traitlets.config.loader.KVArgParseConfigLoader
28,612
jupyter_core.application
_data_dir_default
null
def _data_dir_default(self) -> str: d = jupyter_data_dir() ensure_dir_exists(d, mode=0o700) return d
(self) -> str
28,614
jupyter_core.application
_find_subcommand
null
def _find_subcommand(self, name: str) -> str: name = f"{self.name}-{name}" return which(name) or ""
(self, name: str) -> str
28,615
traitlets.config.configurable
_get_log_handler
Return the default Handler Returns None if none can be found Deprecated, this now returns the first log handler which may or may not be the default one.
def _get_log_handler(self) -> logging.Handler | None: """Return the default Handler Returns None if none can be found Deprecated, this now returns the first log handler which may or may not be the default one. """ if not self.log: return None logger: logging.Logger = ( self.log if isinstance(self.log, logging.Logger) else self.log.logger ) if not getattr(logger, "handlers", None): # no handlers attribute or empty handlers list return None return logger.handlers[0]
(self) -> logging.Handler | None
28,617
jupyter_core.application
_jupyter_path_default
null
def _jupyter_path_default(self) -> list[str]: return jupyter_path()
(self) -> list[str]
28,618
jupyter_server.extension.application
_jupyter_server_config
The jupyter server config.
def _jupyter_server_config(self): """The jupyter server config.""" base_config = { "ServerApp": { "default_url": self.default_url, "open_browser": self.open_browser, "file_url_prefix": self.file_url_prefix, } } base_config["ServerApp"].update(self.serverapp_config) return base_config
(self)
28,619
jupyter_server.extension.application
_link_jupyter_server_extension
Link the ExtensionApp to an initialized ServerApp. The ServerApp is stored as an attribute and config is exchanged between ServerApp and `self` in case the command line contains traits for the ExtensionApp or the ExtensionApp's config files have server settings. Note, the ServerApp has not initialized the Tornado Web Application yet, so do not try to affect the `web_app` attribute.
def _link_jupyter_server_extension(self, serverapp: ServerApp) -> None: """Link the ExtensionApp to an initialized ServerApp. The ServerApp is stored as an attribute and config is exchanged between ServerApp and `self` in case the command line contains traits for the ExtensionApp or the ExtensionApp's config files have server settings. Note, the ServerApp has not initialized the Tornado Web Application yet, so do not try to affect the `web_app` attribute. """ self.serverapp = serverapp # Load config from an ExtensionApp's config files. self.load_config_file() # ServerApp's config might have picked up # config for the ExtensionApp. We call # update_config to update ExtensionApp's # traits with these values found in ServerApp's # config. # ServerApp config ---> ExtensionApp traits self.update_config(self.serverapp.config) # Use ExtensionApp's CLI parser to find any extra # args that passed through ServerApp and # now belong to ExtensionApp. self.parse_command_line(self.serverapp.extra_args) # If any config should be passed upstream to the # ServerApp, do it here. # i.e. ServerApp traits <--- ExtensionApp config self.serverapp.update_config(self.config) # Acknowledge that this extension has been linked. self._linked = True
(self, serverapp: jupyter_server.serverapp.ServerApp) -> NoneType
28,621
jupyter_core.application
_log_level_default
null
def _log_level_default(self) -> int: return logging.INFO
(self) -> int
28,624
jupyter_server.extension.application
_prepare_config
Builds a Config object from the extension's traits and passes the object to the webapp's settings as `<name>_config`.
def _prepare_config(self): """Builds a Config object from the extension's traits and passes the object to the webapp's settings as `<name>_config`. """ traits = self.class_own_traits().keys() self.extension_config = Config({t: getattr(self, t) for t in traits}) self.settings[f"{self.name}_config"] = self.extension_config
(self)
28,625
jupyter_server.extension.application
_prepare_handlers
Prepare the handlers.
def _prepare_handlers(self): """Prepare the handlers.""" assert self.serverapp is not None webapp = self.serverapp.web_app # Get handlers defined by extension subclass. self.initialize_handlers() # prepend base_url onto the patterns that we match new_handlers = [] for handler_items in self.handlers: # Build url pattern including base_url pattern = url_path_join(webapp.settings["base_url"], handler_items[0]) handler = handler_items[1] # Get handler kwargs, if given kwargs: dict[str, t.Any] = {} if issubclass(handler, ExtensionHandlerMixin): kwargs["name"] = self.name try: kwargs.update(handler_items[2]) except IndexError: pass new_handler = (pattern, handler, kwargs) new_handlers.append(new_handler) # Add static endpoint for this extension, if static paths are given. if len(self.static_paths) > 0: # Append the extension's static directory to server handlers. static_url = url_path_join(self.static_url_prefix, "(.*)") # Construct handler. handler = ( static_url, webapp.settings["static_handler_class"], {"path": self.static_paths}, ) new_handlers.append(handler) webapp.add_handlers(".*$", new_handlers)
(self)
28,626
jupyter_server.extension.application
_prepare_settings
Prepare the settings.
def _prepare_settings(self): """Prepare the settings.""" # Make webapp settings accessible to initialize_settings method assert self.serverapp is not None webapp = self.serverapp.web_app self.settings.update(**webapp.settings) # Add static and template paths to settings. self.settings.update( { f"{self.name}_static_paths": self.static_paths, f"{self.name}": self, } ) # Get setting defined by subclass using initialize_settings method. self.initialize_settings() # Update server settings with extension settings. webapp.settings.update(**self.settings)
(self)
28,627
jupyter_server.extension.application
_prepare_templates
Add templates to web app settings if extension has templates.
def _prepare_templates(self): """Add templates to web app settings if extension has templates.""" if len(self.template_paths) > 0: self.settings.update({f"{self.name}_template_paths": self.template_paths}) self.initialize_templates()
(self)
28,630
jupyter_core.application
_runtime_dir_default
null
def _runtime_dir_default(self) -> str: rd = jupyter_runtime_dir() ensure_dir_exists(rd, mode=0o700) return rd
(self) -> str
28,632
traitlets.config.application
close_handlers
null
def close_handlers(self) -> None: if getattr(self, "_logging_configured", False): # don't attempt to close handlers unless they have been opened # (note accessing self.log.handlers will create handlers if they # have not yet been initialised) for handler in self.log.handlers: with suppress(Exception): handler.close() self._logging_configured = False
(self) -> NoneType
28,633
jupyter_server.extension.application
current_activity
Return a list of activity happening in this extension.
def current_activity(self): """Return a list of activity happening in this extension.""" return
(self)
28,634
traitlets.config.application
document_config_options
Generate rST format documentation for the config options this application Returns a multiline string.
def document_config_options(self) -> str: """Generate rST format documentation for the config options this application Returns a multiline string. """ return "\n".join(c.class_config_rst_doc() for c in self._classes_inc_parents())
(self) -> str
28,635
traitlets.config.application
emit_alias_help
Yield the lines for alias part of the help.
def emit_alias_help(self) -> t.Generator[str, None, None]: """Yield the lines for alias part of the help.""" if not self.aliases: return classdict: dict[str, type[Configurable]] = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = t.cast(t.Type[Configurable], c) fhelp: str | None for alias, longname in self.aliases.items(): try: if isinstance(longname, tuple): longname, fhelp = longname else: fhelp = None classname, traitname = longname.split(".")[-2:] longname = classname + "." + traitname cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] fhelp_lines = cls.class_get_trait_help(trait, helptext=fhelp).splitlines() if not isinstance(alias, tuple): # type:ignore[unreachable] alias = (alias,) # type:ignore[assignment] alias = sorted(alias, key=len) # type:ignore[assignment] alias = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in alias) # reformat first line fhelp_lines[0] = fhelp_lines[0].replace("--" + longname, alias) yield from fhelp_lines yield indent("Equivalent to: [--%s]" % longname) except Exception as ex: self.log.error("Failed collecting help-message for alias %r, due to: %s", alias, ex) raise
(self) -> Generator[str, NoneType, NoneType]
28,636
traitlets.config.application
emit_description
Yield lines with the application description.
def emit_description(self) -> t.Generator[str, None, None]: """Yield lines with the application description.""" for p in wrap_paragraphs(self.description or self.__doc__ or ""): yield p yield ""
(self) -> Generator[str, NoneType, NoneType]
28,637
traitlets.config.application
emit_examples
Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage.
def emit_examples(self) -> t.Generator[str, None, None]: """Yield lines with the usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples: yield "Examples" yield "--------" yield "" yield indent(dedent(self.examples.strip())) yield ""
(self) -> Generator[str, NoneType, NoneType]
28,638
traitlets.config.application
emit_flag_help
Yield the lines for the flag part of the help.
def emit_flag_help(self) -> t.Generator[str, None, None]: """Yield the lines for the flag part of the help.""" if not self.flags: return for flags, (cfg, fhelp) in self.flags.items(): try: if not isinstance(flags, tuple): # type:ignore[unreachable] flags = (flags,) # type:ignore[assignment] flags = sorted(flags, key=len) # type:ignore[assignment] flags = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in flags) yield flags yield indent(dedent(fhelp.strip())) cfg_list = " ".join( f"--{clname}.{prop}={val}" for clname, props_dict in cfg.items() for prop, val in props_dict.items() ) cfg_txt = "Equivalent to: [%s]" % cfg_list yield indent(dedent(cfg_txt)) except Exception as ex: self.log.error("Failed collecting help-message for flag %r, due to: %s", flags, ex) raise
(self) -> Generator[str, NoneType, NoneType]
28,639
traitlets.config.application
emit_help
Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed.
def emit_help(self, classes: bool = False) -> t.Generator[str, None, None]: """Yield the help-lines for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ yield from self.emit_description() yield from self.emit_subcommands_help() yield from self.emit_options_help() if classes: help_classes = self._classes_with_config_traits() if help_classes is not None: yield "Class options" yield "=============" for p in wrap_paragraphs(self.keyvalue_description): yield p yield "" for cls in help_classes: yield cls.class_get_help() yield "" yield from self.emit_examples() yield from self.emit_help_epilogue(classes)
(self, classes: bool = False) -> Generator[str, NoneType, NoneType]
28,640
traitlets.config.application
emit_help_epilogue
Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg.
def emit_help_epilogue(self, classes: bool) -> t.Generator[str, None, None]: """Yield the very bottom lines of the help message. If classes=False (the default), print `--help-all` msg. """ if not classes: yield "To see all available configurables, use `--help-all`." yield ""
(self, classes: bool) -> Generator[str, NoneType, NoneType]
28,641
traitlets.config.application
emit_options_help
Yield the lines for the options part of the help.
def emit_options_help(self) -> t.Generator[str, None, None]: """Yield the lines for the options part of the help.""" if not self.flags and not self.aliases: return header = "Options" yield header yield "=" * len(header) for p in wrap_paragraphs(self.option_description): yield p yield "" yield from self.emit_flag_help() yield from self.emit_alias_help() yield ""
(self) -> Generator[str, NoneType, NoneType]
28,642
traitlets.config.application
emit_subcommands_help
Yield the lines for the subcommand part of the help.
def emit_subcommands_help(self) -> t.Generator[str, None, None]: """Yield the lines for the subcommand part of the help.""" if not self.subcommands: return header = "Subcommands" yield header yield "=" * len(header) for p in wrap_paragraphs(self.subcommand_description.format(app=self.name)): yield p yield "" for subc, (_, help) in self.subcommands.items(): yield subc if help: yield indent(dedent(help.strip())) yield ""
(self) -> Generator[str, NoneType, NoneType]
28,643
traitlets.config.application
exit
null
def exit(self, exit_status: int | str | None = 0) -> None: self.log.debug("Exiting application: %s", self.name) self.close_handlers() sys.exit(exit_status)
(self, exit_status: int | str | None = 0) -> NoneType
28,644
traitlets.config.application
flatten_flags
Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted.
def flatten_flags(self) -> tuple[dict[str, t.Any], dict[str, t.Any]]: """Flatten flags and aliases for loaders, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases: dict[str, str] = {} for alias, longname in self.aliases.items(): if isinstance(longname, tuple): longname, _ = longname cls, trait = longname.split(".", 1) children = mro_tree[cls] # type:ignore[index] if len(children) == 1: # exactly one descendent, promote alias cls = children[0] # type:ignore[assignment] if not isinstance(aliases, tuple): # type:ignore[unreachable] alias = (alias,) # type:ignore[assignment] for al in alias: aliases[al] = ".".join([cls, trait]) # type:ignore[list-item] # flatten flags, which are of the form: # { 'key' : ({'Cls' : {'trait' : value}}, 'help')} flags = {} for key, (flagdict, help) in self.flags.items(): newflag: dict[t.Any, t.Any] = {} for cls, subdict in flagdict.items(): children = mro_tree[cls] # type:ignore[index] # exactly one descendent, promote flag section if len(children) == 1: cls = children[0] # type:ignore[assignment] if cls in newflag: newflag[cls].update(subdict) else: newflag[cls] = subdict if not isinstance(key, tuple): # type:ignore[unreachable] key = (key,) # type:ignore[assignment] for k in key: flags[k] = (newflag, help) return flags, aliases
(self) -> tuple[dict[str, typing.Any], dict[str, typing.Any]]
28,645
traitlets.config.application
generate_config_file
generate default config file from Configurables
def generate_config_file(self, classes: ClassesType | None = None) -> str: """generate default config file from Configurables""" lines = ["# Configuration file for %s." % self.name] lines.append("") lines.append("c = get_config() #" + "noqa") lines.append("") classes = self.classes if classes is None else classes config_classes = list(self._classes_with_config_traits(classes)) for cls in config_classes: lines.append(cls.class_config_section(config_classes)) return "\n".join(lines)
(self, classes: Optional[List[Type[traitlets.config.configurable.Configurable]]] = None) -> str
28,646
traitlets.config.application
get_default_logging_config
Return the base logging configuration. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log handler level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. The ``logging_config`` trait is merged into this allowing for finer control of logging.
def get_default_logging_config(self) -> StrDict: """Return the base logging configuration. The default is to log to stderr using a StreamHandler, if no default handler already exists. The log handler level starts at logging.WARN, but this can be adjusted by setting the ``log_level`` attribute. The ``logging_config`` trait is merged into this allowing for finer control of logging. """ config: StrDict = { "version": 1, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "console", "level": logging.getLevelName(self.log_level), # type:ignore[arg-type] "stream": "ext://sys.stderr", }, }, "formatters": { "console": { "class": ( f"{self._log_formatter_cls.__module__}" f".{self._log_formatter_cls.__name__}" ), "format": self.log_format, "datefmt": self.log_datefmt, }, }, "loggers": { self.__class__.__name__: { "level": "DEBUG", "handlers": ["console"], } }, "disable_existing_loggers": False, } if IS_PYTHONW: # disable logging # (this should really go to a file, but file-logging is only # hooked up in parallel applications) del config["handlers"] del config["loggers"] return config
(self) -> Dict[str, Any]
28,649
jupyter_server.extension.application
initialize
Initialize the extension app. The corresponding server app and webapp should already be initialized by this step. - Appends Handlers to the ServerApp, - Passes config and settings from ExtensionApp to the Tornado web application - Points Tornado Webapp to templates and static assets.
def initialize(self): """Initialize the extension app. The corresponding server app and webapp should already be initialized by this step. - Appends Handlers to the ServerApp, - Passes config and settings from ExtensionApp to the Tornado web application - Points Tornado Webapp to templates and static assets. """ if not self.serverapp: msg = ( "This extension has no attribute `serverapp`. " "Try calling `.link_to_serverapp()` before calling " "`.initialize()`." ) raise JupyterServerExtensionException(msg) self._prepare_config() self._prepare_templates() self._prepare_settings() self._prepare_handlers()
(self)
28,650
jupyter_server_fileid.extension
initialize_event_listeners
null
def initialize_event_listeners(self): handlers_by_action = self.file_id_manager.get_handlers_by_action() async def cm_listener(logger: EventLogger, schema_id: str, data: dict) -> None: handler = handlers_by_action[data["action"]] if handler: handler(data) self.settings["event_logger"].add_listener( schema_id="https://events.jupyter.org/jupyter_server/contents_service/v1", listener=cm_listener, ) self.log.info("Attached event listeners.")
(self)
28,651
jupyter_server.extension.application
initialize_handlers
Override this method to append handlers to a Jupyter Server.
def initialize_handlers(self): """Override this method to append handlers to a Jupyter Server."""
(self)
28,652
jupyter_server_fileid.extension
initialize_settings
null
def initialize_settings(self): self.log.info(f"Configured File ID manager: {self.file_id_manager_class.__name__}") self.file_id_manager = self.file_id_manager_class( log=self.log, root_dir=self.serverapp.root_dir, config=self.config ) self.settings.update({"file_id_manager": self.file_id_manager}) # attach listener to contents manager events (requires jupyter_server~=2) if "event_logger" in self.settings: self.initialize_event_listeners()
(self)
28,653
traitlets.config.application
initialize_subcommand
Initialize a subcommand with argv.
def catch_config_error(method: T) -> T: """Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input. """ @functools.wraps(method) def inner(app: Application, *args: t.Any, **kwargs: t.Any) -> t.Any: try: return method(app, *args, **kwargs) except (TraitError, ArgumentError) as e: app.log.fatal("Bad config encountered during initialization: %s", e) app.log.debug("Config at the time: %s", app.config) app.exit(1) return t.cast(T, inner)
(self, subc: str, argv: Optional[List[str]] = None) -> NoneType
28,654
jupyter_server.extension.application
initialize_templates
Override this method to add handling of template files.
def initialize_templates(self): """Override this method to add handling of template files."""
(self)
28,655
traitlets.config.application
load_config_environ
Load config files by environment.
def catch_config_error(method: T) -> T: """Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input. """ @functools.wraps(method) def inner(app: Application, *args: t.Any, **kwargs: t.Any) -> t.Any: try: return method(app, *args, **kwargs) except (TraitError, ArgumentError) as e: app.log.fatal("Bad config encountered during initialization: %s", e) app.log.debug("Config at the time: %s", app.config) app.exit(1) return t.cast(T, inner)
(self) -> NoneType
28,656
jupyter_core.application
load_config_file
Load the config file. By default, errors in loading config are handled, and a warning printed on screen. For testing, the suppress_errors option is set to False, so errors will make tests fail.
def load_config_file(self, suppress_errors: bool = True) -> None: # type:ignore[override] """Load the config file. By default, errors in loading config are handled, and a warning printed on screen. For testing, the suppress_errors option is set to False, so errors will make tests fail. """ self.log.debug("Searching %s for config files", self.config_file_paths) base_config = "jupyter_config" try: super().load_config_file( base_config, path=self.config_file_paths, ) except ConfigFileNotFound: # ignore errors loading parent self.log.debug("Config file %s not found", base_config) if self.config_file: path, config_file_name = os.path.split(self.config_file) else: path = self.config_file_paths # type:ignore[assignment] config_file_name = self.config_file_name if not config_file_name or (config_file_name == base_config): return try: super().load_config_file(config_file_name, path=path) except ConfigFileNotFound: self.log.debug("Config file not found, skipping: %s", config_file_name) except Exception: # Reraise errors for testing purposes, or if set in # self.raise_config_file_errors if (not suppress_errors) or self.raise_config_file_errors: raise self.log.warning("Error loading config file: %s", config_file_name, exc_info=True)
(self, suppress_errors: bool = True) -> NoneType
28,657
jupyter_core.application
migrate_config
Migrate config/data from IPython 3
def migrate_config(self) -> None: """Migrate config/data from IPython 3""" try: # let's see if we can open the marker file # for reading and updating (writing) f_marker = Path.open(Path(self.config_dir, "migrated"), "r+") except FileNotFoundError: # cannot find the marker file pass # that means we have not migrated yet, so continue except OSError: # not readable and/or writable return # so let's give up migration in such an environment else: # if we got here without raising anything, # that means the file exists f_marker.close() return # so we must have already migrated -> bail out from .migrate import get_ipython_dir, migrate # No IPython dir, nothing to migrate if not Path(get_ipython_dir()).exists(): return migrate()
(self) -> NoneType
28,661
traitlets.config.application
parse_command_line
Parse the command line arguments.
def catch_config_error(method: T) -> T: """Method decorator for catching invalid config (Trait/ArgumentErrors) during init. On a TraitError (generally caused by bad config), this will print the trait's message, and exit the app. For use on init methods, to prevent invoking excepthook on invalid input. """ @functools.wraps(method) def inner(app: Application, *args: t.Any, **kwargs: t.Any) -> t.Any: try: return method(app, *args, **kwargs) except (TraitError, ArgumentError) as e: app.log.fatal("Bad config encountered during initialization: %s", e) app.log.debug("Config at the time: %s", app.config) app.exit(1) return t.cast(T, inner)
(self, argv: Optional[List[str]] = None) -> NoneType
28,662
traitlets.config.application
print_alias_help
Print the alias parts of the help.
def print_alias_help(self) -> None: """Print the alias parts of the help.""" print("\n".join(self.emit_alias_help()))
(self) -> NoneType
28,663
traitlets.config.application
print_description
Print the application description.
def print_description(self) -> None: """Print the application description.""" print("\n".join(self.emit_description()))
(self) -> NoneType
28,664
traitlets.config.application
print_examples
Print usage and examples (see `emit_examples()`).
def print_examples(self) -> None: """Print usage and examples (see `emit_examples()`).""" print("\n".join(self.emit_examples()))
(self) -> NoneType
28,665
traitlets.config.application
print_flag_help
Print the flag part of the help.
def print_flag_help(self) -> None: """Print the flag part of the help.""" print("\n".join(self.emit_flag_help()))
(self) -> NoneType
28,666
traitlets.config.application
print_help
Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed.
def print_help(self, classes: bool = False) -> None: """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ print("\n".join(self.emit_help(classes=classes)))
(self, classes: bool = False) -> NoneType
28,667
traitlets.config.application
print_options
Print the options part of the help.
def print_options(self) -> None: """Print the options part of the help.""" print("\n".join(self.emit_options_help()))
(self) -> NoneType
28,668
traitlets.config.application
print_subcommands
Print the subcommand part of the help.
def print_subcommands(self) -> None: """Print the subcommand part of the help.""" print("\n".join(self.emit_subcommands_help()))
(self) -> NoneType
28,669
traitlets.config.application
print_version
Print the version string.
def print_version(self) -> None: """Print the version string.""" print(self.version)
(self) -> NoneType
28,672
jupyter_server.extension.application
start
Start the underlying Jupyter server. Server should be started after extension is initialized.
def start(self): """Start the underlying Jupyter server. Server should be started after extension is initialized. """ super().start() # Start the server. assert self.serverapp is not None self.serverapp.start()
(self)
28,673
traitlets.config.application
start_show_config
start function used when show_config is True
def start_show_config(self) -> None: """start function used when show_config is True""" config = self.config.copy() # exclude show_config flags from displayed config for cls in self.__class__.mro(): if cls.__name__ in config: cls_config = config[cls.__name__] cls_config.pop("show_config", None) cls_config.pop("show_config_json", None) if self.show_config_json: json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr) # add trailing newline sys.stdout.write("\n") return if self._loaded_config_files: print("Loaded config files:") for f in self._loaded_config_files: print(" " + f) print() for classname in sorted(config): class_config = config[classname] if not class_config: continue print(classname) pformat_kwargs: StrDict = dict(indent=4, compact=True) # noqa: C408 for traitname in sorted(class_config): value = class_config[traitname] print(f" .{traitname} = {pprint.pformat(value, **pformat_kwargs)}")
(self) -> NoneType
28,674
jupyter_server.extension.application
stop
Stop the underlying Jupyter server.
def stop(self): """Stop the underlying Jupyter server.""" assert self.serverapp is not None self.serverapp.stop() self.serverapp.clear_instance()
(self)
28,675
jupyter_server.extension.application
stop_extension
Cleanup any resources managed by this extension.
def current_activity(self): """Return a list of activity happening in this extension.""" return
(self)
28,685
jupyter_core.application
write_default_config
Write our default config to a .py config file
def write_default_config(self) -> None: """Write our default config to a .py config file""" if self.config_file: config_file = self.config_file else: config_file = str(Path(self.config_dir, self.config_file_name + ".py")) if Path(config_file).exists() and not self.answer_yes: answer = "" def ask() -> str: prompt = "Overwrite %s with default config? [y/N]" % config_file try: return input(prompt).lower() or "n" except KeyboardInterrupt: print("") # empty line return "n" answer = ask() while not answer.startswith(("y", "n")): print("Please answer 'yes' or 'no'") answer = ask() if answer.startswith("n"): return config_text = self.generate_config_file() print("Writing default config to: %s" % config_file) ensure_dir_exists(Path(config_file).parent.resolve(), 0o700) with Path.open(Path(config_file), mode="w", encoding="utf-8") as f: f.write(config_text)
(self) -> NoneType
28,686
jupyter_server_fileid
_jupyter_server_extension_points
null
def _jupyter_server_extension_points(): return [{"module": "jupyter_server_fileid", "app": FileIdExtension}]
()
28,690
wget
bar_adaptive
Return progress bar string for given values in one of three styles depending on available width: [.. ] downloaded / total downloaded / total [.. ] if total value is unknown or <= 0, show bytes counter using two adaptive styles: %s / unknown %s if there is not enough space on the screen, do not display anything returned string doesn't include control characters like used to place cursor at the beginning of the line to erase previous content. this function leaves one free character at the end of string to avoid automatic linefeed on Windows.
def bar_adaptive(current, total, width=80): """Return progress bar string for given values in one of three styles depending on available width: [.. ] downloaded / total downloaded / total [.. ] if total value is unknown or <= 0, show bytes counter using two adaptive styles: %s / unknown %s if there is not enough space on the screen, do not display anything returned string doesn't include control characters like \r used to place cursor at the beginning of the line to erase previous content. this function leaves one free character at the end of string to avoid automatic linefeed on Windows. """ # process special case when total size is unknown and return immediately if not total or total < 0: msg = "%s / unknown" % current if len(msg) < width: # leaves one character to avoid linefeed return msg if len("%s" % current) < width: return "%s" % current # --- adaptive layout algorithm --- # # [x] describe the format of the progress bar # [x] describe min width for each data field # [x] set priorities for each element # [x] select elements to be shown # [x] choose top priority element min_width < avail_width # [x] lessen avail_width by value if min_width # [x] exclude element from priority list and repeat # 10% [.. ] 10/100 # pppp bbbbb sssssss min_width = { 'percent': 4, # 100% 'bar': 3, # [.] 'size': len("%s" % total)*2 + 3, # 'xxxx / yyyy' } priority = ['percent', 'bar', 'size'] # select elements to show selected = [] avail = width for field in priority: if min_width[field] < avail: selected.append(field) avail -= min_width[field]+1 # +1 is for separator or for reserved space at # the end of line to avoid linefeed on Windows # render output = '' for field in selected: if field == 'percent': # fixed size width for percentage output += ('%s%%' % (100 * current // total)).rjust(min_width['percent']) elif field == 'bar': # [. ] # bar takes its min width + all available space output += bar_thermometer(current, total, min_width['bar']+avail) elif field == 'size': # size field has a constant width (min == max) output += ("%s / %s" % (current, total)).rjust(min_width['size']) selected = selected[1:] if selected: output += ' ' # add field separator return output
(current, total, width=80)
28,691
wget
bar_thermometer
Return thermometer style progress bar string. `total` argument can not be zero. The minimum size of bar returned is 3. Example: [.......... ] Control and trailing symbols ( and spaces) are not included. See `bar_adaptive` for more information.
def bar_thermometer(current, total, width=80): """Return thermometer style progress bar string. `total` argument can not be zero. The minimum size of bar returned is 3. Example: [.......... ] Control and trailing symbols (\r and spaces) are not included. See `bar_adaptive` for more information. """ # number of dots on thermometer scale avail_dots = width-2 shaded_dots = int(math.floor(float(current) / total * avail_dots)) return '[' + '.'*shaded_dots + ' '*(avail_dots-shaded_dots) + ']'
(current, total, width=80)
28,692
wget
callback_progress
callback function for urlretrieve that is called when connection is created and when once for each block draws adaptive progress bar in terminal/console use sys.stdout.write() instead of "print,", because it allows one more symbol at the line end without linefeed on Windows :param blocks: number of blocks transferred so far :param block_size: in bytes :param total_size: in bytes, can be -1 if server doesn't return it :param bar_function: another callback function to visualize progress
def callback_progress(blocks, block_size, total_size, bar_function): """callback function for urlretrieve that is called when connection is created and when once for each block draws adaptive progress bar in terminal/console use sys.stdout.write() instead of "print,", because it allows one more symbol at the line end without linefeed on Windows :param blocks: number of blocks transferred so far :param block_size: in bytes :param total_size: in bytes, can be -1 if server doesn't return it :param bar_function: another callback function to visualize progress """ global __current_size width = min(100, get_console_width()) if sys.version_info[:3] == (3, 3, 0): # regression workaround if blocks == 0: # first call __current_size = 0 else: __current_size += block_size current_size = __current_size else: current_size = min(blocks*block_size, total_size) progress = bar_function(current_size, total_size, width) if progress: sys.stdout.write("\r" + progress)
(blocks, block_size, total_size, bar_function)
28,693
wget
detect_filename
Return filename for saving file. If no filename is detected from output argument, url or headers, return default (download.wget)
def detect_filename(url=None, out=None, headers=None, default="download.wget"): """Return filename for saving file. If no filename is detected from output argument, url or headers, return default (download.wget) """ names = dict(out='', url='', headers='') if out: names["out"] = out or '' if url: names["url"] = filename_from_url(url) or '' if headers: names["headers"] = filename_from_headers(headers) or '' return names["out"] or names["headers"] or names["url"] or default
(url=None, out=None, headers=None, default='download.wget')
28,694
wget
download
High level function, which downloads URL into tmp file in current directory and then renames it to filename autodetected from either URL or HTTP headers. :param bar: function to track download progress (visualize etc.) :param out: output filename or directory :return: filename where URL is downloaded to
def download(url, out=None, bar=bar_adaptive): """High level function, which downloads URL into tmp file in current directory and then renames it to filename autodetected from either URL or HTTP headers. :param bar: function to track download progress (visualize etc.) :param out: output filename or directory :return: filename where URL is downloaded to """ # detect of out is a directory outdir = None if out and os.path.isdir(out): outdir = out out = None # get filename for temp file in current directory prefix = detect_filename(url, out) (fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=prefix, dir=".") os.close(fd) os.unlink(tmpfile) # set progress monitoring callback def callback_charged(blocks, block_size, total_size): # 'closure' to set bar drawing function in callback callback_progress(blocks, block_size, total_size, bar_function=bar) if bar: callback = callback_charged else: callback = None if PY3K: # Python 3 can not quote URL as needed binurl = list(urlparse.urlsplit(url)) binurl[2] = urlparse.quote(binurl[2]) binurl = urlparse.urlunsplit(binurl) else: binurl = url (tmpfile, headers) = ulib.urlretrieve(binurl, tmpfile, callback) filename = detect_filename(url, out, headers) if outdir: filename = outdir + "/" + filename # add numeric ' (x)' suffix if filename already exists if os.path.exists(filename): filename = filename_fix_existing(filename) shutil.move(tmpfile, filename) #print headers return filename
(url, out=None, bar=<function bar_adaptive at 0x7f0e2e0b5090>)
28,695
wget
filename_fix_existing
Expands name portion of filename with numeric ' (x)' suffix to return filename that doesn't exist already.
def filename_fix_existing(filename): """Expands name portion of filename with numeric ' (x)' suffix to return filename that doesn't exist already. """ dirname = u'.' name, ext = filename.rsplit('.', 1) names = [x for x in os.listdir(dirname) if x.startswith(name)] names = [x.rsplit('.', 1)[0] for x in names] suffixes = [x.replace(name, '') for x in names] # filter suffixes that match ' (x)' pattern suffixes = [x[2:-1] for x in suffixes if x.startswith(' (') and x.endswith(')')] indexes = [int(x) for x in suffixes if set(x) <= set('0123456789')] idx = 1 if indexes: idx += sorted(indexes)[-1] return '%s (%d).%s' % (name, idx, ext)
(filename)
28,696
wget
filename_from_headers
Detect filename from Content-Disposition headers if present. http://greenbytes.de/tech/tc2231/ :param: headers as dict, list or string :return: filename from content-disposition header or None
def filename_from_headers(headers): """Detect filename from Content-Disposition headers if present. http://greenbytes.de/tech/tc2231/ :param: headers as dict, list or string :return: filename from content-disposition header or None """ if type(headers) == str: headers = headers.splitlines() if type(headers) == list: headers = dict([x.split(':', 1) for x in headers]) cdisp = headers.get("Content-Disposition") if not cdisp: return None cdtype = cdisp.split(';') if len(cdtype) == 1: return None if cdtype[0].strip().lower() not in ('inline', 'attachment'): return None # several filename params is illegal, but just in case fnames = [x for x in cdtype[1:] if x.strip().startswith('filename=')] if len(fnames) > 1: return None name = fnames[0].split('=')[1].strip(' \t"') name = os.path.basename(name) if not name: return None return name
(headers)
28,697
wget
filename_from_url
:return: detected filename as unicode or None
def filename_from_url(url): """:return: detected filename as unicode or None""" # [ ] test urlparse behavior with unicode url fname = os.path.basename(urlparse.urlparse(url).path) if len(fname.strip(" \n\t.")) == 0: return None return to_unicode(fname)
(url)
28,698
wget
get_console_width
Return width of available window area. Autodetection works for Windows and POSIX platforms. Returns 80 for others Code from http://bitbucket.org/techtonik/python-pager
def get_console_width(): """Return width of available window area. Autodetection works for Windows and POSIX platforms. Returns 80 for others Code from http://bitbucket.org/techtonik/python-pager """ if os.name == 'nt': STD_INPUT_HANDLE = -10 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 # get console handle from ctypes import windll, Structure, byref try: from ctypes.wintypes import SHORT, WORD, DWORD except ImportError: # workaround for missing types in Python 2.5 from ctypes import ( c_short as SHORT, c_ushort as WORD, c_ulong as DWORD) console_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) # CONSOLE_SCREEN_BUFFER_INFO Structure class COORD(Structure): _fields_ = [("X", SHORT), ("Y", SHORT)] class SMALL_RECT(Structure): _fields_ = [("Left", SHORT), ("Top", SHORT), ("Right", SHORT), ("Bottom", SHORT)] class CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [("dwSize", COORD), ("dwCursorPosition", COORD), ("wAttributes", WORD), ("srWindow", SMALL_RECT), ("dwMaximumWindowSize", DWORD)] sbi = CONSOLE_SCREEN_BUFFER_INFO() ret = windll.kernel32.GetConsoleScreenBufferInfo( console_handle, byref(sbi)) if ret == 0: return 0 return sbi.srWindow.Right+1 elif os.name == 'posix': from fcntl import ioctl from termios import TIOCGWINSZ from array import array winsize = array("H", [0] * 4) try: ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize) except IOError: pass return (winsize[1], winsize[0])[0] return 80
()
28,704
wget
to_unicode
:return: filename decoded from utf-8 to unicode
def to_unicode(filename): """:return: filename decoded from utf-8 to unicode""" # if PY3K: # [ ] test this on Python 3 + (Windows, Linux) # [ ] port filename_from_headers once this works # [ ] add test to repository / Travis return filename else: if isinstance(filename, unicode): return filename else: return unicode(filename, 'utf-8')
(filename)
28,707
wget
win32_unicode_console
null
def win32_unicode_console(): import codecs from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int from ctypes.wintypes import BOOL, HANDLE, DWORD, LPWSTR, LPCWSTR, LPVOID original_stderr = sys.stderr # Output exceptions in this code to original_stderr, so that we can at least see them def _complain(message): original_stderr.write(message if isinstance(message, str) else repr(message)) original_stderr.write('\n') codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) try: GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32)) STD_OUTPUT_HANDLE = DWORD(-11) STD_ERROR_HANDLE = DWORD(-12) GetFileType = WINFUNCTYPE(DWORD, DWORD)(("GetFileType", windll.kernel32)) FILE_TYPE_CHAR = 0x0002 FILE_TYPE_REMOTE = 0x8000 GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(("GetConsoleMode", windll.kernel32)) INVALID_HANDLE_VALUE = DWORD(-1).value def not_a_console(handle): if handle == INVALID_HANDLE_VALUE or handle is None: return True return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or GetConsoleMode(handle, byref(DWORD())) == 0) old_stdout_fileno = None old_stderr_fileno = None if hasattr(sys.stdout, 'fileno'): old_stdout_fileno = sys.stdout.fileno() if hasattr(sys.stderr, 'fileno'): old_stderr_fileno = sys.stderr.fileno() STDOUT_FILENO = 1 STDERR_FILENO = 2 real_stdout = (old_stdout_fileno == STDOUT_FILENO) real_stderr = (old_stderr_fileno == STDERR_FILENO) if real_stdout: hStdout = GetStdHandle(STD_OUTPUT_HANDLE) if not_a_console(hStdout): real_stdout = False if real_stderr: hStderr = GetStdHandle(STD_ERROR_HANDLE) if not_a_console(hStderr): real_stderr = False if real_stdout or real_stderr: WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(("WriteConsoleW", windll.kernel32)) class UnicodeOutput: def __init__(self, hConsole, stream, fileno, name): self._hConsole = hConsole self._stream = stream self._fileno = fileno self.closed = False self.softspace = False self.mode = 'w' self.encoding = 'utf-8' self.name = name self.flush() def isatty(self): return False def close(self): # don't really close the handle, that would only cause problems self.closed = True def fileno(self): return self._fileno def flush(self): if self._hConsole is None: try: self._stream.flush() except Exception as e: _complain("%s.flush: %r from %r" % (self.name, e, self._stream)) raise def write(self, text): try: if self._hConsole is None: if not PY3K and isinstance(text, unicode): text = text.encode('utf-8') elif PY3K and isinstance(text, str): text = text.encode('utf-8') self._stream.write(text) else: if not PY3K and not isinstance(text, unicode): text = str(text).decode('utf-8') elif PY3K and not isinstance(text, str): text = text.decode('utf-8') remaining = len(text) while remaining: n = DWORD(0) # There is a shorter-than-documented limitation on the # length of the string passed to WriteConsoleW (see # <http://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232>. retval = WriteConsoleW(self._hConsole, text, min(remaining, 10000), byref(n), None) if retval == 0 or n.value == 0: raise IOError("WriteConsoleW returned %r, n.value = %r" % (retval, n.value)) remaining -= n.value if not remaining: break text = text[n.value:] except Exception as e: _complain("%s.write: %r" % (self.name, e)) raise def writelines(self, lines): try: for line in lines: self.write(line) except Exception as e: _complain("%s.writelines: %r" % (self.name, e)) raise if real_stdout: sys.stdout = UnicodeOutput(hStdout, None, STDOUT_FILENO, '<Unicode console stdout>') else: sys.stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno, '<Unicode redirected stdout>') if real_stderr: sys.stderr = UnicodeOutput(hStderr, None, STDERR_FILENO, '<Unicode console stderr>') else: sys.stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno, '<Unicode redirected stderr>') except Exception as e: _complain("exception %r while fixing up sys.stdout and sys.stderr" % (e,))
()
28,708
wget
win32_utf8_argv
Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode strings. Versions 2.x of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'.
def win32_utf8_argv(): """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode strings. Versions 2.x of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'. """ from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) argnum = argc.value sysnum = len(sys.argv) result = [] if argnum > 0: # Remove Python executable and commands if present start = argnum - sysnum for i in range(start, argnum): result.append(argv[i].encode('utf-8')) return result
()
28,709
eliza_gpt.api
ElizaGPT
null
class ElizaGPT(Microdot): def __init__(self, api_key=None, avg_response_time=2): super().__init__() self.mount(api_v1, '/v1') self.api_key = api_key or os.environ.get('OPENAI_API_KEY') self.avg_response_time = avg_response_time
(api_key=None, avg_response_time=2)
28,710
microdot.asgi
__call__
null
def __init__(self): super().__init__() self.embedded_server = False
(self, scope, receive, send)
28,711
eliza_gpt.api
__init__
null
def __init__(self, api_key=None, avg_response_time=2): super().__init__() self.mount(api_v1, '/v1') self.api_key = api_key or os.environ.get('OPENAI_API_KEY') self.avg_response_time = avg_response_time
(self, api_key=None, avg_response_time=2)
28,712
microdot.microdot
abort
Abort the current request and return an error response with the given status code. :param status_code: The numeric status code of the response. :param reason: The reason for the response, which is included in the response body. Example:: from microdot import abort @app.route('/users/<int:id>') def get_user(id): user = get_user_by_id(id) if user is None: abort(404) return user.to_dict()
@staticmethod def abort(status_code, reason=None): """Abort the current request and return an error response with the given status code. :param status_code: The numeric status code of the response. :param reason: The reason for the response, which is included in the response body. Example:: from microdot import abort @app.route('/users/<int:id>') def get_user(id): user = get_user_by_id(id) if user is None: abort(404) return user.to_dict() """ raise HTTPException(status_code, reason)
(status_code, reason=None)
28,713
microdot.microdot
after_error_request
Decorator to register a function to run after an error response is generated. The decorated function must take two arguments, the request and response objects. The return value of the function must be an updated response object. The handler is invoked for error responses generated by Microdot, as well as those returned by application-defined error handlers. Example:: @app.after_error_request def func(request, response): # ... return response
def after_error_request(self, f): """Decorator to register a function to run after an error response is generated. The decorated function must take two arguments, the request and response objects. The return value of the function must be an updated response object. The handler is invoked for error responses generated by Microdot, as well as those returned by application-defined error handlers. Example:: @app.after_error_request def func(request, response): # ... return response """ self.after_error_request_handlers.append(f) return f
(self, f)
28,714
microdot.microdot
after_request
Decorator to register a function to run after each request is handled. The decorated function must take two arguments, the request and response objects. The return value of the function must be an updated response object. Example:: @app.after_request def func(request, response): # ... return response
def after_request(self, f): """Decorator to register a function to run after each request is handled. The decorated function must take two arguments, the request and response objects. The return value of the function must be an updated response object. Example:: @app.after_request def func(request, response): # ... return response """ self.after_request_handlers.append(f) return f
(self, f)
28,715
microdot.asgi
asgi_app
An ASGI application.
def __init__(self): super().__init__() self.embedded_server = False
(self, scope, receive, send)
28,716
microdot.microdot
before_request
Decorator to register a function to run before each request is handled. The decorated function must take a single argument, the request object. Example:: @app.before_request def func(request): # ...
def before_request(self, f): """Decorator to register a function to run before each request is handled. The decorated function must take a single argument, the request object. Example:: @app.before_request def func(request): # ... """ self.before_request_handlers.append(f) return f
(self, f)
28,717
microdot.microdot
default_options_handler
null
def default_options_handler(self, req): allow = [] for route_methods, route_pattern, route_handler in self.url_map: if route_pattern.match(req.path) is not None: allow.extend(route_methods) if 'GET' in allow: allow.append('HEAD') allow.append('OPTIONS') return {'Allow': ', '.join(allow)}
(self, req)
28,718
microdot.microdot
delete
Decorator that is used to register a function as a ``DELETE`` request handler for a given URL. :param url_pattern: The URL pattern that will be compared against incoming requests. This decorator can be used as an alias to the ``route`` decorator with ``methods=['DELETE']``. Example:: @app.delete('/users/<int:id>') def delete_user(request, id): # ...
def delete(self, url_pattern): """Decorator that is used to register a function as a ``DELETE`` request handler for a given URL. :param url_pattern: The URL pattern that will be compared against incoming requests. This decorator can be used as an alias to the ``route`` decorator with ``methods=['DELETE']``. Example:: @app.delete('/users/<int:id>') def delete_user(request, id): # ... """ return self.route(url_pattern, methods=['DELETE'])
(self, url_pattern)
28,720
microdot.microdot
errorhandler
Decorator to register a function as an error handler. Error handler functions for numeric HTTP status codes must accept a single argument, the request object. Error handler functions for Python exceptions must accept two arguments, the request object and the exception object. :param status_code_or_exception_class: The numeric HTTP status code or Python exception class to handle. Examples:: @app.errorhandler(404) def not_found(request): return 'Not found' @app.errorhandler(RuntimeError) def runtime_error(request, exception): return 'Runtime error'
def errorhandler(self, status_code_or_exception_class): """Decorator to register a function as an error handler. Error handler functions for numeric HTTP status codes must accept a single argument, the request object. Error handler functions for Python exceptions must accept two arguments, the request object and the exception object. :param status_code_or_exception_class: The numeric HTTP status code or Python exception class to handle. Examples:: @app.errorhandler(404) def not_found(request): return 'Not found' @app.errorhandler(RuntimeError) def runtime_error(request, exception): return 'Runtime error' """ def decorated(f): self.error_handlers[status_code_or_exception_class] = f return f return decorated
(self, status_code_or_exception_class)
28,721
microdot.microdot
find_route
null
def find_route(self, req): method = req.method.upper() if method == 'OPTIONS' and self.options_handler: return self.options_handler(req) if method == 'HEAD': method = 'GET' f = 404 for route_methods, route_pattern, route_handler in self.url_map: req.url_args = route_pattern.match(req.path) if req.url_args is not None: if method in route_methods: f = route_handler break else: f = 405 return f
(self, req)
28,722
microdot.microdot
get
Decorator that is used to register a function as a ``GET`` request handler for a given URL. :param url_pattern: The URL pattern that will be compared against incoming requests. This decorator can be used as an alias to the ``route`` decorator with ``methods=['GET']``. Example:: @app.get('/users/<int:id>') def get_user(request, id): # ...
def get(self, url_pattern): """Decorator that is used to register a function as a ``GET`` request handler for a given URL. :param url_pattern: The URL pattern that will be compared against incoming requests. This decorator can be used as an alias to the ``route`` decorator with ``methods=['GET']``. Example:: @app.get('/users/<int:id>') def get_user(request, id): # ... """ return self.route(url_pattern, methods=['GET'])
(self, url_pattern)
28,724
microdot.microdot
mount
Mount a sub-application, optionally under the given URL prefix. :param subapp: The sub-application to mount. :param url_prefix: The URL prefix to mount the application under.
def mount(self, subapp, url_prefix=''): """Mount a sub-application, optionally under the given URL prefix. :param subapp: The sub-application to mount. :param url_prefix: The URL prefix to mount the application under. """ for methods, pattern, handler in subapp.url_map: self.url_map.append( (methods, URLPattern(url_prefix + pattern.url_pattern), handler)) for handler in subapp.before_request_handlers: self.before_request_handlers.append(handler) for handler in subapp.after_request_handlers: self.after_request_handlers.append(handler) for handler in subapp.after_error_request_handlers: self.after_error_request_handlers.append(handler) for status_code, handler in subapp.error_handlers.items(): self.error_handlers[status_code] = handler
(self, subapp, url_prefix='')
28,725
microdot.microdot
patch
Decorator that is used to register a function as a ``PATCH`` request handler for a given URL. :param url_pattern: The URL pattern that will be compared against incoming requests. This decorator can be used as an alias to the ``route`` decorator with ``methods=['PATCH']``. Example:: @app.patch('/users/<int:id>') def edit_user(request, id): # ...
def patch(self, url_pattern): """Decorator that is used to register a function as a ``PATCH`` request handler for a given URL. :param url_pattern: The URL pattern that will be compared against incoming requests. This decorator can be used as an alias to the ``route`` decorator with ``methods=['PATCH']``. Example:: @app.patch('/users/<int:id>') def edit_user(request, id): # ... """ return self.route(url_pattern, methods=['PATCH'])
(self, url_pattern)