# How to use traits - 10 common examples

## 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. enthought / traitsui / examples / demo / Advanced / Auto_editable_readonly_table_cells.py View on Github 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) &lt;= n:
j = n // i
if (i * j) == n: capn-freako / PyBERT / pybert / pybert.py View on Github @cached_property
def _get_f(self):
"""
Calculate the frequency vector appropriate for indexing non-shifted FFT output, in Hz.
# (i.e. - [0, f0, 2 * f0, ... , fN] + [-(fN - f0), -(fN - 2 * f0), ... , -f0]
"""

t = self.t

npts = len(t)
f0 = 1.0 / (t * npts)
half_npts = npts // 2

return array([i * f0 for i in range(half_npts + 1)] + [(half_npts - i) * -f0 for i in range(1, half_npts)]) NMGRL / pychron / pychron / messaging / testclient.py View on Github # from timeit import Timer
import time
# import os
# from datetime import timedelta
import random
from six.moves import range
from six.moves import input

# import struct

class Client(HasTraits):
command = Property(String('GetData', enter_set=True, auto_set=False),
depends_on='_command')
_command = Str
resend = Button
response = String
port = Int(1069)
#    port = Int(8080)
# host = Str('192.168.0.65')
#    host = Str('129.138.12.145')
host = 'localhost'
path = None
kind = Enum('IPC', 'UDP', 'TCP')

period = Float(100)
periodic = Event
periodic_label = Property(depends_on='_alive') enthought / chaco / chaco / tools / range_selection.py View on Github left_button_selects = Bool(False)

# Disable all left-mouse button interactions?
disable_left_mouse = Bool(False)

# Allow the tool to be put into the deselected state via mouse clicks
allow_deselection = Bool(True)

# The minimum span, in pixels, of a selection region.  Any attempt to
# select a region smaller than this will be treated as a deselection.
minimum_selection = Int(5)

# The key which, if held down while the mouse is being dragged, will
# indicate that the selection should be appended to an existing selection
# as opposed to overwriting it.
append_key = Instance(KeySpec, args=(None, "control"))

#------------------------------------------------------------------------
# Private traits
#------------------------------------------------------------------------

# The value of the override plot to use, if any.  If None, then uses
# self.component.
_plot = Trait(None, Any)

# The value of the override mapper to use, if any.  If None, then uses the
# mapper on self.component.
_mapper = Trait(None, Any)

# Shadow trait for the **axis_index** property.
_axis_index = Trait(None, None, Int) enthought / mayavi / mayavi / core / module_manager.py View on Github lut_data_mode = Trait('auto',
TraitPrefixList(LUT_DATA_MODE_TYPES),
desc='specify the data type used by the lookup tables',
)

# The scalar lookup table manager.
scalar_lut_manager = Instance(LUTManager, args=(), record=True)

# The vector lookup table manager.
vector_lut_manager = Instance(LUTManager, args=(), record=True)

# The name of the ModuleManager.
name = Str('Colors and legends')

# The icon
icon = Str('modulemanager.ico')

# The human-readable type for this object
type = Str(' colors and legends')

# Information about what this object can consume.
input_info = PipelineInfo(datasets=['any'])

# Information about what this object can produce.
output_info = PipelineInfo(datasets=['any'])

######################################################################
# object interface
######################################################################
def __get_pure_state__(self):
d = super(ModuleManager, self).__get_pure_state__() enthought / envisage / envisage / plugins / remote_editor / communication / server.py View on Github The only instance methods that should be called in ordinary use are
'init' and 'main'. Communication should be done through the methods on
'Client' objects.
"""

spawn_commands = Dict(Str, Str)

_port = Int
_sock = Instance(socket.socket)
_port_map = Dict(Int, Instance(PortInfo))
_orphans = List(Instance(PortInfo))
_pairs = Dict(Instance(PortInfo), Instance(PortInfo))

# Commands that have been queued for spawned process
# desired_type -> list of (command, arguments)
_queue = Dict(Str, List(Tuple(Str, Str)))

def init(self, pref_path='', pref_node=''):
""" Read a configuration file and attempt to bind the server to the
specified port.
"""
# Bind to port and write port to lock file
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.bind(('localhost', 0))
self._port = self._sock.getsockname()
f = open(LOCK_PATH, 'w')
f.write(str(self._port))
f.close()

if not pref_path:
return acoular / acoular / acoular / environments.py View on Github field with non-uniform velocities that depend on the location. The
algorithm for the calculation uses a ray-tracing approach that bases on
rays cast from every microphone position in multiple directions and traced
backwards in time. The result is interpolated within a tetrahedal grid
spanned between these rays.
"""
#: The flow field, must be of type :class:~acoular.environments.FlowField.
ff = Trait(FlowField,
desc="flow field")

#: Number of rays used per solid angle :math:\Omega, defaults to 200.
N = Int(200,
desc="number of rays per Om")

#: The maximum solid angle used in the algorithm, defaults to :math:\pi.
Om = Float(pi,
desc="maximum solid angle")

# internal identifier
digest = Property(
depends_on=['ff.digest', 'N', 'Om'],
)

traits_view = View(
[
['ff{Flow field}', 'N{Max. number of rays}', 'Om{Max. solid angle }'],
'|[General Flow]'
]
)

@cached_property
def _get_digest( self ): enthought / enable / enable / savage / compliance / comparator.py View on Github # The currently selected SVG file.
current_file = Str()
abs_current_file = Property(depends_on=['current_file'])

# The current XML ElementTree root Element and its XMLTree view model.
current_xml = Any()
current_xml_view = Any()

# The profilers.
profile_this = Instance(ProfileThis, args=())

#### GUI traits ############################################################

# The text showing the current mouse coordinates over any of the components.
mouse_coords = Property(Str, depends_on=['ch_controller.svg_coords'])

# Move forward and backward through the list of SVG files.
move_forward = Button('&gt;&gt;')
move_backward = Button('&lt;&lt;')

# The description of the test.
description = HTML()

document = Instance(document.SVGDocument)

# The components to view.
kiva_component = ComponentTrait(klass=SVGComponent)
ref_component = ComponentTrait(klass=ImageComponent, args=())
ch_controller = Instance(MultiController)

# The profiler views. NMGRL / pychron / pychron / envisage / browser / base_browser_model.py View on Github args = name.split(' ')
ms = ' '.join(args[1:]).lower()
return ms

class BaseBrowserModel(PersistenceLoggable, ColumnSorterMixin):
dvc = Instance('pychron.dvc.dvc.DVC')
plot_selected = Event

selected_principal_investigators = Any
principal_investigators = List
principal_investigator_names = List

projects = List
oprojects = List
repositories = List
orepositories = List
samples = List
osamples = List

include_recent = True
project_enabled = Bool(True)
repository_enabled = Bool(True)
principal_investigator_enabled = Bool(True)

analysis_groups = List

identifier = IdentifierStr(enter_set=True, auto_set=False) enthought / chaco / chaco / axis.py View on Github tick_label_color = ColorTrait("black")

# The rotation of the tick labels.
tick_label_rotate_angle = Float(0)

# Whether to align to corners or edges (corner is better for 45 degree rotation)
tick_label_alignment = Enum('edge', 'corner')

# The margin around the tick labels.
tick_label_margin = Int(2)

# The distance of the tick label from the axis.
tick_label_offset = Float(8.)

# Whether the tick labels appear to the inside or the outside of the plot area
tick_label_position = Enum("outside", "inside")

# A callable that is passed the numerical value of each tick label and
# that returns a string.
tick_label_formatter = Callable(DEFAULT_TICK_FORMATTER)

# The number of pixels by which the ticks extend into the plot area.
tick_in = Int(5)

# The number of pixels by which the ticks extend into the label area.
tick_out = Int(5)

# Are ticks visible at all?
tick_visible = Bool(True)

# The dataspace interval between ticks.
tick_interval = Trait('auto', 'auto', Float)

## traits

Observable typed attributes for Python classes GitHub BSD-2-Clause Latest version published 10 months ago

74 / 100

## Popular Python code snippets

Find secure code to use in your application or website