How to use the traitlets.Integer function in traitlets

To help you get started, we’ve selected a few traitlets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dask / dask-gateway / dask-gateway-server / dask_gateway_server / traitlets.py View on Github external
from traitlets import TraitError, TraitType, Integer, List, Unicode, Type as _Type
from traitlets.config import Application


# Override default values for logging
Application.log_level.default_value = "INFO"
Application.log_format.default_value = (
    "%(log_color)s[%(levelname)1.1s %(asctime)s.%(msecs).03d "
    "%(name)s]%(reset)s %(message)s"
)


# Adapted from JupyterHub
class MemoryLimit(Integer):
    """A specification of a memory limit, with optional units.

    Supported units are:
      - K -> Kibibytes
      - M -> Mebibytes
      - G -> Gibibytes
      - T -> Tebibytes
    """

    UNIT_SUFFIXES = {"K": 2 ** 10, "M": 2 ** 20, "G": 2 ** 30, "T": 2 ** 40}

    def validate(self, obj, value):
        if isinstance(value, (int, float)):
            return int(value)

        try:
github yatsu / react-tornado-graphql-example / tornado / tornado_graphql_example / app.py View on Github external
allow_credentials = Bool(
        True, config=True,
        help='Set the Access-Control-Allow-Credentials: true header'
    )

    ip = Unicode(
        '', config=True,
        help='The IP address the server will listen on.'
    )

    def _ip_changed(self, name, old, new):
        if new == u'*':
            self.ip = u''

    port = Integer(
        4000, config=True,
        help='The port the server will listen on.'
    )

    tornado_settings = Dict(
        config=True,
        help='tornado.web.Application settings.'
    )

    subcommand = Unicode()

    def init_logging(self):
        self.log.propagate = False

        for log in app_log, access_log, gen_log:
            log.name = self.log.name
github pylada / pylada-light / espresso / pwscf_namelists.py View on Github external
    @input_transform
    def __ecutwfc_is_required(self, dictionary, **kwargs):
        from .. import error
        if dictionary.get('ecutwfc', None) is None:
            raise error.ValueError("ecutwfc has not been set. It is a required parameter")


class Electrons(Namelist):
    """ Electrons namelist """
    electron_maxstep = Integer(default_value=None, allow_none=True,
                               help="Maximum number of scf iterations")
    itermax = alias(electron_maxstep)
    conv_thr = Float(allow_none=True, default_value=None,
                     help="Convergence criteria for self consistency")
    mixing_ndim = Integer(allow_none=True, default_value=None, min=0,
                          help="Number of iterations used in mixing")
    mixing_mode = Enum(['plain', 'TF', 'local-TF'], allow_none=True, default_value=None,
                       help="Mixing mode")
    mixing_beta = Float(allow_none=True, default_value=None, help="Mixing factor")
    diagonalization = Enum(['david', 'cg', 'cg-serial'], allow_none=True, default_value=None,
                           help="Diagonalization method")
    diago_cg_max_iter = Integer(allow_none=True, default_value=None, min=0,
                                help="Max number of iterations for CG diagonalization")
    diago_david_ndim = Integer(allow_none=True, default_value=None, min=2,
                               help="Dimension of workspace in David diagonalization")
    diago_full_acc = Bool(allow_none=True, default_value=None,
                          help="Whether to diagonalize empty-states at the same level"
                          "as occupied states")
    startingpot = CaselessStringEnum(['file', 'atomic'], default_value=None, allow_none=True,
                                     help="Start from existing charge density file\n\n"
                                     "Generally, pylada will handle this value on its own."
github timkpaine / aat / aat / backup / config.py View on Github external
class ExecutionConfig(HasTraits):
    trading_type = Instance(klass=TradingType, args=('NONE',), kwargs={})


class StrategyConfig(HasTraits):
    clazz = Type()
    args = Tuple(default_value=())
    kwargs = Dict(default_value={})


class TradingEngineConfig(HasTraits):
    type = Instance(klass=TradingType, args=('NONE',), kwargs={})
    print = Bool(default_value=False)
    port = Integer(default_value=8080)
    sql_url = Unicode(default_value="sqlite:///aat.db")
    exchange_options = Instance(klass=ExchangeConfig, args=(), kwargs={})
    backtest_options = Instance(klass=BacktestConfig, args=(), kwargs={})
    risk_options = Instance(klass=RiskConfig, args=(), kwargs={})
    execution_options = Instance(klass=ExecutionConfig, args=(), kwargs={})
    strategy_options = List(trait=Instance(StrategyConfig), default_value=[])  # List of strategy options
github jupyter / nbgrader / nbgrader / preprocessors / limitoutput.py View on Github external
from . import NbGraderPreprocessor

from traitlets import Integer
from nbformat.notebooknode import NotebookNode
from nbconvert.exporters.exporter import ResourcesDict
from typing import Tuple


class LimitOutput(NbGraderPreprocessor):
    """Preprocessor for limiting cell output"""

    max_lines = Integer(
        1000,
        help="maximum number of lines of output (-1 means no limit)"
    ).tag(config=True)

    max_traceback = Integer(
        100,
        help="maximum number of traceback lines (-1 means no limit)"
    ).tag(config=True)

    def _limit_stream_output(self, cell: NotebookNode) -> NotebookNode:
        if self.max_lines == -1 or cell.cell_type != "code":
            return cell

        length = 0
        new_outputs = []
        for output in cell.outputs:
github ipython / ipython / IPython / terminal / ptshell.py View on Github external
else:
        return 'notepad' # same in Windows!


if sys.stdin and sys.stdout and sys.stderr:
    _is_tty = (sys.stdin.isatty()) and (sys.stdout.isatty()) and  (sys.stderr.isatty())
else:
    _is_tty = False


_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)

class TerminalInteractiveShell(InteractiveShell):
    colors_force = True

    space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
                                                  'to reserve for the completion menu'
                            ).tag(config=True)

    def _space_for_menu_changed(self, old, new):
        self._update_layout()

    pt_cli = None
    debugger_history = None

    simple_prompt = Bool(_use_simple_prompt,
        help="""Use `raw_input` for the REPL, without completion, multiline input, and prompt colors.

            Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
            IPython own testing machinery, and emacs inferior-shell integration through elpy.

            This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
github Zsailer / phylovega / phylovega / chart.py View on Github external
from traitlets.config import Configurable
from traitlets import (
    Integer,
    default
)
from phylovega.traitlets import VegaConfigurable


class BaseTreeChart(VegaConfigurable):
    """Object for specifying chart styling.
    """
    padding = Integer(5, help="Padding around tree chart.", config=True)
    width = Integer(300, help="Width of the tree chart.", config=True)

    height = Integer(help="Height of the tree chart.", config=True)

    @default('height')
    def _default_height(self):
        leafs = [el for el in self.data if el['type'] == 'leaf']
        return len(leafs) * 12

    def __init__(self, data, config=None, **kwargs):
        super().__init__(config=config, **kwargs)
        self.data = data

    def get_spec(self):
        return { 
            'width' : self.width,
            'height': self.height,
github dask / dask-gateway / dask-gateway-server / dask_gateway_server / backends / yarn.py View on Github external
principal = Unicode(
        None,
        help="Kerberos principal for Dask Gateway user",
        allow_none=True,
        config=True,
    )

    keytab = Unicode(
        None,
        help="Path to kerberos keytab for Dask Gateway user",
        allow_none=True,
        config=True,
    )

    app_client_cache_max_size = Integer(
        10,
        help="""
        The max size of the cache for application clients.

        A larger cache will result in improved performance, but will also use
        more resources.
        """,
        config=True,
    )

    def async_apply(self, f, *args, **kwargs):
        return get_running_loop().run_in_executor(None, lambda: f(*args, **kwargs))

    def _get_security(self, cluster):
        return skein.Security(cert_bytes=cluster.tls_cert, key_bytes=cluster.tls_key)
github jupyter / repo2docker / repo2docker / utils.py View on Github external
)?  # optionally have the above group

        )   # end capturing name

        (?::([\w][\w.-]{0,127}))?    # optional capture =':'
        # optionally capture ='@'
        (?:@[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][A-Fa-f0-9]{32,})?
        $
        """,
        re.VERBOSE,
    )

    return reference_regex.match(image_name) is not None


class ByteSpecification(Integer):
    """
    Allow easily specifying bytes in units of 1024 with suffixes

    Suffixes allowed are:
      - K -> Kilobyte
      - M -> Megabyte
      - G -> Gigabyte
      - T -> Terabyte

    Stolen from JupyterHub
    """

    UNIT_SUFFIXES = {
        "K": 1024,
        "M": 1024 * 1024,
        "G": 1024 * 1024 * 1024,
github pylada / pylada-light / espresso / pwscf_namelists.py View on Github external
class Electrons(Namelist):
    """ Electrons namelist """
    electron_maxstep = Integer(default_value=None, allow_none=True,
                               help="Maximum number of scf iterations")
    itermax = alias(electron_maxstep)
    conv_thr = Float(allow_none=True, default_value=None,
                     help="Convergence criteria for self consistency")
    mixing_ndim = Integer(allow_none=True, default_value=None, min=0,
                          help="Number of iterations used in mixing")
    mixing_mode = Enum(['plain', 'TF', 'local-TF'], allow_none=True, default_value=None,
                       help="Mixing mode")
    mixing_beta = Float(allow_none=True, default_value=None, help="Mixing factor")
    diagonalization = Enum(['david', 'cg', 'cg-serial'], allow_none=True, default_value=None,
                           help="Diagonalization method")
    diago_cg_max_iter = Integer(allow_none=True, default_value=None, min=0,
                                help="Max number of iterations for CG diagonalization")
    diago_david_ndim = Integer(allow_none=True, default_value=None, min=2,
                               help="Dimension of workspace in David diagonalization")
    diago_full_acc = Bool(allow_none=True, default_value=None,
                          help="Whether to diagonalize empty-states at the same level"
                          "as occupied states")
    startingpot = CaselessStringEnum(['file', 'atomic'], default_value=None, allow_none=True,
                                     help="Start from existing charge density file\n\n"
                                     "Generally, pylada will handle this value on its own."
                                     "Users are unlikely to need set it themselves.")
    startingwfc = CaselessStringEnum(['atomic', 'atomic+random', 'random', 'file'],
                                     default_value=None, allow_none=True,
                                     help="Start from existing charge density file\n\n"
                                     "When restarting/continuing a calculation, this parameter is "
                                     "automatically set to 'file'.")