How to use the traits.api.HasTraits function in traits

To help you get started, we’ve selected a few traits 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 enthought / traitsui / examples / demo / Advanced / Auto_editable_readonly_table_cells.py View on Github external
from traitsui.table_column \
    import ObjectColumn

#-- Integer Class --------------------------------------------------------


class Integer(HasTraits):

    # The value:
    n = Int

#-- Factor Class ---------------------------------------------------------


class Factor(HasTraits):

    # The number being factored:
    n = Int

    # The list of factors of 'n':
    factors = Property(List)

    @property_depends_on('n')
    def _get_factors(self):
        n = self.n
        i = 1
        result = []

        while (i * i) <= n:
            j = n // i
            if (i * j) == n:
github enthought / traitsui / examples / tutorials / traitsui_4.0 / editors / tabular_editor / numpy_array.py View on Github external
def _get_index_image ( self ):
        x, y, z = self.item
        if sqrt( (x - 0.5) ** 2 + (y - 0.5) ** 2 + (z - 0.5) ** 2 ) <= 0.25:
            return 'red_flag'
        return None

#--[Tabular Editor Definition]--------------------------------------------------

tabular_editor = TabularEditor(
    adapter = ArrayAdapter(),
    images  = [ ImageResource( 'red_flag', search_path = search_path ) ]
)

#--[ShowArray Class]------------------------------------------------------------

class ShowArray ( HasTraits ):

    data = Array

    view = View(
        Item( 'data', editor = tabular_editor, show_label = False ),
        title     = 'Array Viewer',
        width     = 0.3,
        height    = 0.8,
        resizable = True,
        buttons   = NoButtons
    )

#--[Example Code*]--------------------------------------------------------------

demo = ShowArray( data = random( ( 100000, 3 ) ) )
github enthought / jigna / examples / person_example_web.py View on Github external
from traits.api import HasTraits, Int, Str
from jigna.api import WebSocketView
from pyface.qt import QtGui
from pyface.timer.api import do_after

#### Domain model ####

class Person(HasTraits):
    name = Str
    age  = Int

#### UI layer ####

body_html = """
    <div>
      Name: <input>
      Age: <input type="number">
    </div>
"""

person_view = WebSocketView(body_html=body_html)

#### Entry point ####
github enthought / traitsui / examples / demo / Advanced / Adapted_tree_editor_demo.py View on Github external
if is_expanded:
            return ''

        return ''

    def can_auto_close(self):
        """ Returns whether the object's children should be automatically
            closed.
        """
        return True

#-- FileTreeDemo Class ---------------------------------------------------


class FileTreeDemo(HasTraits):

    # The path to the file tree root:
    root_path = Directory(entries=10)

    # The root of the file tree:
    root = Property

    # The traits view to display:
    view = View(
        VGroup(
            Item('root_path'),
            Item('root',
                 editor=TreeEditor(editable=False, auto_open=1)
                 ),
            show_labels=False
        ),
github scipy-lectures / scipy-lecture-notes / packages / 3d_plotting / examples / coil_application.py View on Github external
and a full-blown example of what you might want to do
"""

import numpy as np
from scipy import linalg, special
from traits.api import HasTraits, Array, CFloat, Str, List, \
   Instance, on_trait_change
from traitsui.api import Item, View, HGroup, ListEditor, \
        HSplit, VSplit, spring
from mayavi.core.ui.api import EngineView, MlabSceneModel, \
        SceneEditor

##############################################################################
# A current loop

class Loop(HasTraits):
    """ A current loop.
    """
    direction = Array(float, value=(0, 0, 1), cols=3,
                    shape=(3,), desc='directing vector of the loop',
                    enter_set=True, auto_set=False)

    # CFloat tries to convert automatically to floats
    radius    = CFloat(0.1, desc='radius of the loop',
                    enter_set=True, auto_set=False)

    position  = Array(float, value=(0, 0, 0), cols=3,
                    shape=(3,), desc='position of the center of the loop',
                    enter_set=True, auto_set=False)

    plot      = None
github enthought / pyface / pyface / resource / resource_manager.py View on Github external
# Standard library imports.
import collections, glob, inspect, os, sys, types
from os.path import join
from zipfile import is_zipfile, ZipFile

# Enthought library imports.
from traits.api import HasTraits, Instance, List
from traits.util.resource import get_path

# Local imports.
from pyface.resource.resource_factory import ResourceFactory
from pyface.resource.resource_reference import ImageReference
import six


class ResourceManager(HasTraits):
    """ The default resource manager.

    A resource manager locates and loads application resources such as images
    and sounds etc.
    """

    # Allowed extensions for image resources.
    IMAGE_EXTENSIONS = ['.png', '.jpg', '.bmp', '.gif', '.ico']

    # A list of additional search paths. These paths are fallbacks, and hence
    # have lower priority than the paths provided by resource objects.
    extra_paths = List

    # The resource factory is responsible for actually creating resources.
    # This is used so that (for example) different GUI toolkits can create
    # a images in the format that they require.
github MatthieuDartiailh / HQCMeas / measurement / instruments / instrument_manager.py View on Github external
"""
        Open confirmation dialog when the user asks to delete a profile
        """
        model = info.object
        message = cleandoc("""Are you sure want to delete this
                        instrument connection informations ?""")
        if error(message = fill(message, 80),
                title = 'Deletion confirmation',
                parent = info.ui.control):
            instr_file = model.instrs[model.selected_instr_name]
            path = os.path.abspath(info.object.instr_folder)
            fullpath = os.path.join(path, instr_file)
            os.remove(fullpath)
        model.selected_instr_name = model.instrs_name[0]

class InstrumentManager(HasTraits):
    """
    Main object used to manage the instrument profile and filter them

    This class can be used either to create/edit/delete instrument profiles
    using a GUI or to get a list of profiles according to a specified driver.

    Attributes
    ----------
    instr_folder : directory path
        Path in which the profiles are stored.
    instrs : dict(str, path)
        Dict mapping profile names to the associated filename
    instrs_name : list(str)
        List of the keys of `instrs`
    selected_instr_name : str
        Name of the selected instrumen profile
github NMGRL / pychron / pychron / extraction_line / extraction_line_canvas.py View on Github external
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================

#============= enthought library imports =======================
from traits.api import HasTraits, Any
from traitsui.api import View, Item
from enable.component_editor import ComponentEditor
#============= standard library imports ========================
#============= local library imports  ==========================
# from canvas.canvas3D.extraction_line_canvas3D import ExtractionLineCanvas3D
# from pychron.canvas.canvas3D.canvas3D_editor import Canvas3DEditor


class ExtractionLineCanvas(HasTraits):
    '''
    '''
    canvas2D = Any
    manager = Any


    def toggle_item_identify(self, name):
        '''
        '''
        self._canvas_function('toggle_item_identify', name)

    def refresh(self):
        '''
        '''
        self._canvas_function('request_redraw')
github enthought / mayavi / enthought / mayavi / tools / data_wizards / csv_loader.py View on Github external
my_name = Str
    parent=Instance(HasTraits)
    view = View(
               HGroup(
                   Item('name', style='readonly', show_label=False,
                                    resizable=False),
                   Item('my_name', style='simple', show_label=False,
                            editor=TextEditor(auto_set=False, enter_set=True),
                                    springy=True),
               )
           )

##############################################################################
# CSVLoader class
##############################################################################
class CSVLoader(HasTraits):
    """ User interface to load CSV files.
    """

    # The name of the file being loaded.
    filename  = Str

    # The comment characters
    comments  = Str(desc="The comment characters")

    # The character giving the delimiter between the columns.
    delimiter = Str(
        desc="The character giving the delimiter between the columns")

    # The number of rows to skip at the beginning of the file
    skiprows  = Int(
        desc="The number of rows to skip at the beginning of the file")
github enthought / pyface / pyface / viewer / viewer_sorter.py View on Github external
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

""" Abstract base class for all viewer sorters. """


from traits.api import HasTraits


class ViewerSorter(HasTraits):
    """ Abstract base class for all viewer sorters. """

    # ------------------------------------------------------------------------
    # 'ViewerSorter' interface.
    # ------------------------------------------------------------------------

    def sort(self, viewer, parent, elements):
        """ Sorts a list of elements IN PLACE.

        'viewer'   is the viewer that we are sorting elements for.
        'parent'   is the parent element.
        'elements' is the list of elements to sort.

        Returns the list that was sorted IN PLACE (for convenience).

        """