コード例 #1
0
class _RolesView(HasTraits):
    """This represents the view used to select a role."""

    #### '_UsersView' interface ###############################################

    # The list of roles to select from.
    model = List(_Role)

    # The selected user.
    selection = Instance(_Role)

    # The editor used by the view.
    table_editor = TableEditor(
        columns=[ObjectColumn(name='name'),
                 ObjectColumn(name='description')],
        selected='selection',
        sort_model=True,
        configurable=False)

    # The default view.
    traits_view = View(Item('model', show_label=False, editor=table_editor),
                       title="Select a Role",
                       style='readonly',
                       kind='modal',
                       buttons=OKCancelButtons)
コード例 #2
0
class Parameter(HasTraits):
    name = String('name')
    value = Float
    def __str__(self): return '{%s:%f}' %(self.name,self.value)
    def __repr__(self): return '{%s:%f}' %(self.name,self.value)
    editor = TableEditor(
        auto_size=False,
        columns=[ObjectColumn(name='name', label='Name', editable=False),
                 ObjectColumn(name='value', label='Value',
            editor=TextEditor(evaluate=float, enter_set=True, auto_set=False)),
            ])
コード例 #3
0
class Equalizers(HasTraits):
    eqs = List(Equalizer, [Equalizer()])
    h = Array(dtype=np.complex, transient=True)

    # Equalizer列表eqs的编辑器定义
    table_editor = TableEditor(columns=[
        ObjectColumn(name="freq", width=0.4, style="readonly"),
        ObjectColumn(name="Q", width=0.3, style="readonly"),
        ObjectColumn(name="gain", width=0.3, style="readonly"),
    ],
                               deletable=True,
                               sortable=True,
                               auto_size=False,
                               show_toolbar=True,
                               edit_on_first_click=False,
                               orientation='vertical',
                               edit_view=View(Group(
                                   Item("freq",
                                        editor=EnumEditor(values=EQ_FREQS)),
                                   Item("freq", editor=scrubber(1.0)),
                                   Item("Q", editor=scrubber(0.01)),
                                   Item("gain", editor=scrubber(0.1)),
                                   show_border=True,
                               ),
                                              resizable=True),
                               row_factory=Equalizer)

    view = View(Item("eqs", show_label=False, editor=table_editor),
                width=0.25,
                height=0.5,
                resizable=True)

    @on_trait_change("eqs.h")
    def recalculate_h(self):
        '''计算多组均衡器级联时的频率响应'''
        try:
            tmp = np.array([
                eq.h for eq in self.eqs if eq.h != None and len(eq.h) == len(W)
            ])
            self.h = np.prod(tmp, axis=0)
        except:
            pass

    def export(self, path):
        '''将均衡器的系数输出为C语言文件'''
        f = file(path, "w")
        f.write("double EQ_PARS[][5] = {\n")
        f.write("//b0,b1,b2,a1,a2 // frequency, Q, gain\n")
        for eq in self.eqs:
            eq.export_parameters(f)
        f.write("};\n")
        f.close()
コード例 #4
0
class Parameter(HasTraits):
    name = String
    value = Float
    unit = String
    pattern = String
    cmd = String
    editor = TableEditor(
        auto_size=False,
        #row_height=20,
        columns=[ObjectColumn(name='name', editable=False, label='Parameter'),
                     ObjectColumn(name='value', label='Value', editor=TextEditor(evaluate=float, enter_set=True, auto_set=False)),
                     ObjectColumn(name='unit', editable=False, label='Unit')
                    ])
コード例 #5
0
class TableTest(HasStrictTraits):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    #people = Instance( Person )
    people = List(Person)

    #---------------------------------------------------------------------------
    #  Traits view definitions:
    #---------------------------------------------------------------------------

    _valid_states = List(["AL", "AR", "AZ", "AK"])

    _state_editor = EnumEditor(name="_valid_states",
                               evaluate=evaluate_value,
                               object='table_editor_object')

    table_editor = TableEditor(columns=[
        ObjectColumn(name='name'),
        ObjectColumn(name='age'),
        ObjectColumn(name='phone'),
        ObjectColumn(name='state', editor=_state_editor),
    ],
                               editable=True,
                               deletable=True,
                               sortable=True,
                               sort_model=True,
                               show_lines=True,
                               orientation='vertical',
                               show_column_labels=True,
                               edit_view=View(
                                   ['name', 'age', 'phone', 'state', '|[]'],
                                   resizable=True),
                               filter=None,
                               filters=filters,
                               row_factory=Person)

    traits_view = View(
        [Item('people', id='people', editor=table_editor), '|[]<>'],
        title='Table Editor Test',
        id='enthought.traits.ui.tests.table_editor_test',
        dock='horizontal',
        width=.4,
        height=.3,
        resizable=True,
        buttons=NoButtons,
        kind='live')
コード例 #6
0
class Constraint(HasTraits):
    name = String
    runcase = Any
    constraint_variables_available = Property(List(String), depends_on='runcase.constraint_variables')
    @cached_property
    def _get_constraint_variables_available(self):
        return self.runcase.constraint_variables.keys()
    #constraint = Instance(ConstraintVariable)
    constraint_name = String
    value = Float
    pattern = String
    cmd = String
    editor = TableEditor(
        auto_size=False,
        columns=[ ObjectColumn(name='name', editable=False, label='Parameter'),
                     ObjectColumn(name='constraint_name', label='Constraint', editor=EnumEditor(name='constraint_variables_available')),
                     ObjectColumn(name='value', label='Value', editor=TextEditor(evaluate=float, enter_set=True, auto_set=False))
                    ])
コード例 #7
0
class ParameterConfig(HasTraits):
    parameter = Instance(Parameter)
    expr = Expression()

    def __init__(self, *args, **kwargs):
        super(ParameterConfig, self).__init__(*args, **kwargs)
        self.expr = str(self.parameter.value)

    editor = TableEditor(auto_size=False,
                         columns=[
                             ObjectColumn(name='parameter.name',
                                          editable=False,
                                          label='Parameter'),
                             ObjectColumn(name='expr', label='Expression'),
                             ObjectColumn(name='parameter.unit',
                                          editable=False,
                                          label='Unit')
                         ])
コード例 #8
0
class ConstraintConfig(HasTraits):
    constraint = Instance(Constraint)
    expr = Expression()

    def __init__(self, *args, **kwargs):
        super(ConstraintConfig, self).__init__(*args, **kwargs)
        self.expr = str(self.constraint.value)

    constraint_variables_available = DelegatesTo('constraint')
    editor = TableEditor(
        auto_size=False,
        columns=[
            ObjectColumn(name='constraint.name',
                         editable=False,
                         label='Parameter'),
            ObjectColumn(
                name='constraint.constraint_name',
                label='Constraint',
                editor=EnumEditor(name='constraint_variables_available')),
            ObjectColumn(name='expr', label='Expression')
        ])
コード例 #9
0
ファイル: tvtk_base_handler.py プロジェクト: sjl421/code-2
class TVTKBaseHandler(Handler):
   """ A handler for the TVTKBase object. 
   """

   # A reference to the UIInfo object.
   info = Instance(UIInfo)
   
   # Type of view (of info.object) to display.
   view_type = Enum(['Basic', 'Advanced'])

   # The view for the object (that is, info.object)
   view = Property(depends_on='view_type')

   # List of TraitsViewObject items, where each item contains information 
   # about the trait to display as a row in a table editor.
   _full_traits_list = Property(List, editor = TableEditor(columns = 
                                           [ObjectColumn(name='name'), 
                                            ValueColumn(name='value')]))

   def init_info(self, info):
       """ Informs the handler what the UIInfo object for a View will be.
       Overridden here to save a reference to the info object.
       """
       self.info = info
       return


   def _get__full_traits_list(self):  
       """ Returns a list of objects to be included in the table editor for 
       the full traits view.
       """       
       return [TraitsViewObject(name=name, parent = self.info.object) 
                          for name in self.info.object._full_traitnames_list_]

   def _get_view(self):
      """ Returns the view (for info.object) to be displayed in the 
      InstanceEditor.
      """
      if self.view_type ==  "Basic":
           view = self.info.object.trait_view('view')
      else:
           view = self.info.object.trait_view('full_traits_view')
      # This method is called when the default traits view for the object is
      # displayed. The default traits view already has a title, so do not 
      # display a title for the contained view.
      view.title = ''
      return view
   

#### EOF ###################################################################
コード例 #10
0
class Foo(HasTraits):

    # arbitrary string containing spaces
    input = Str

    # input split on space
    parsed = List

    def _input_changed(self):
        words = self.input.split()

        for word in self.parsed[:]:
            if word.word in words:
                words.remove(word.word)
            else:
                self.parsed.remove(word)

        for word in words:
            self.parsed.append(Word(word=word))

        return

    table_editor = TableEditor(columns=[ObjectColumn(name='word')],
                               editable=True)

    help = Str("""Type in the 'input' box before clicking the Parsed tab.
The first non-whitespace character will cause changes to the parsed trait
and therefore changes to the table rows.  That is expected.

BUG: the table grabs the focus from 'input' and thus subsequent typing goes
into one of the table cells. 

If you click the 'Parsed' tab, to view the table, and then the 'Inputs' tab
the focus will stay with the 'input' box.
""")

    traits_view = View(Group(Item('help', style='readonly'),
                             Item('input'),
                             label='Input'),
                       Group(Item('parsed', editor=table_editor),
                             label='Parsed'),
                       dock='tab',
                       resizable=True,
                       width=320,
                       height=240)
コード例 #11
0
ファイル: gui.py プロジェクト: danginsburg/cmp
from cmp.helpgui import HelpDialog

#class CMPThread( threading.Thread ):
#
#    def __init__(self, gconf):
#        threading.Thread.__init__(self)
#        self.gconf = gconf
#
#    def run(self):
#        print "Starting CMP Thread..."
#        cmp.connectome.mapit(self.gconf)
#        print "Ended CMP Thread."
#        # release

table_editor = TableEditor(columns=[
    ObjectColumn(name='key', width=0.2),
    ObjectColumn(name='value', width=0.6),
],
                           editable=True,
                           deletable=True,
                           sortable=True,
                           sort_model=True,
                           auto_size=False,
                           row_factory=KeyValue)


class CMPGUIHandler(Handler):
    def object_run_changed(self, info):
        object = info.object
        if info.initialized:
            # first do a consistency check
コード例 #12
0
ファイル: Property_List_demo.py プロジェクト: sjl421/code-2
class PropertyListDemo ( HasPrivateTraits ):
    """ Displays a random list of Person objects in a TableEditor that is
        refreshed every 3 seconds by a background thread.
     """

    # An event used to trigger a Property value update:
    ticker = Event
    
    # The property being display in the TableEditor:
    people = Property( List, depends_on = 'ticker' )
    
    # Tiny hack to allow starting the background thread easily:
    begin = Int
    
    #-- Traits View Definitions ------------------------------------------------
    
    view = View(
        Item( 'people',
              show_label = False,
              editor = TableEditor(
                  columns = [
                      ObjectColumn( name = 'name',   editable = False,
                                    width = 0.50 ),
                      ObjectColumn( name = 'age',    editable = False,
                                    width = 0.15 ),
                      ObjectColumn( name = 'gender', editable = False,
                                    width = 0.35 )
                  ],
                  auto_size    = False,
                  show_toolbar = False
              )
        ),
        title     = 'Property List Demo',
        width     = 0.25,
        height    = 0.33,
        resizable = True
    )
    
    #-- Property Implementations -----------------------------------------------
    
    @cached_property
    def _get_people ( self ):
        """ Returns the value for the 'people' property.
        """
        return [ Person(
            name = '%s %s' % (
                choice( [ 'Tom', 'Dick', 'Harry', 'Alice', 'Lia', 'Vibha' ] ),
                choice( [ 'Thomas', 'Jones', 'Smith', 'Adams', 'Johnson' ] ) ),
            age    = randint( 21, 75 ),
            gender = choice( [ 'Male', 'Female' ] ) )
            for i in xrange( randint( 10, 20 ) )
        ]
            
    #-- Default Value Implementations ------------------------------------------
    
    def _begin_default ( self ):
        """ Starts the background thread running.
        """
        thread = Thread( target = self._timer )
        thread.setDaemon( True )
        thread.start()
        
        return 0
        
    #-- Private Methods --------------------------------------------------------
    
    def _timer ( self ):
        """ Triggers a property update every 3 seconds for 30 seconds.
        """
        for i in range( 10 ):
            sleep( 3 )
            self.ticker = True
コード例 #13
0
    Person(name='Joe', age=34, phone='555-6943'),
    Person(name='Tom', age=22, phone='555-7586'),
    Person(name='Dick', age=63, phone='555-3895'),
    Person(name='Harry', age=46, phone='555-3285'),
    Person(name='Sally', age=43, phone='555-8797'),
    Person(name='Fields', age=31, phone='555-3547')
]

#-------------------------------------------------------------------------------
#  Table editor definition:
#-------------------------------------------------------------------------------

filters = [EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate]

table_editor = TableEditor(columns=[
    ObjectColumn(name='name'),
    ObjectColumn(name='age'),
    ObjectColumn(name='phone')
],
                           editable=True,
                           deletable=True,
                           sortable=True,
                           sort_model=True,
                           filters=filters,
                           search=RuleTableFilter(),
                           row_factory=Person)

#-------------------------------------------------------------------------------
#  'ListTraitTest' class:
#-------------------------------------------------------------------------------
コード例 #14
0
ファイル: template_data_names.py プロジェクト: sjl421/code-2
                           selection_bg_color=None)

# The standard columns:
std_columns = [
    ResolvedColumn(name='resolved',
                   label='?',
                   editable=False,
                   width=20,
                   horizontal_alignment='center',
                   cell_color=0xFF8080),
    OptionalColumn(name='optional',
                   label='*',
                   editable=False,
                   width=20,
                   horizontal_alignment='center'),
    ObjectColumn(name='description', editor=TextEditor(), width=0.47)
]

#-------------------------------------------------------------------------------
#  'TemplateDataNames' class:
#-------------------------------------------------------------------------------


class TemplateDataNames(HasPrivateTraits):

    #-- Public Traits ----------------------------------------------------------

    # The data context to which bindings are made:
    context = Instance(ITemplateDataContext)

    # The current set of data names to be bound to the context:
コード例 #15
0
    age = Int
    phone = Regex(value='000-0000', regex='\d\d\d[-]\d\d\d\d')

    traits_view = View('first_name',
                       'last_name',
                       'age',
                       'phone',
                       title='Create new employee',
                       width=0.18,
                       buttons=['OK', 'Cancel'])


# The definition of the demo TableEditor:
table_editor = TableEditor(
    columns=[
        ObjectColumn(name='first_name', width=0.20),
        ObjectColumn(name='last_name', width=0.20),
        ExpressionColumn(label='Full Name',
                         width=0.30,
                         expression="'%s %s' % (object.first_name, "
                         "object.last_name )"),
        ObjectColumn(name='age', width=0.10, horizontal_alignment='center'),
        ObjectColumn(name='phone', width=0.20)
    ],
    deletable=True,
    sort_model=True,
    auto_size=False,
    orientation='vertical',
    edit_view=View(Group('first_name',
                         'last_name',
                         'age',
コード例 #16
0
 def _get_exdesign_table_columns(self):
     return [ObjectColumn(name=ps[2],
                          editable=False,
                          width=0.15) for ps in self.exdesign_spec.factors]
コード例 #17
0
from enthought.traits.api import HasTraits, Unicode, Int, List, Instance
from enthought.traits.ui.api import View, Item, TableEditor, ListEditor, HGroup
from enthought.traits.ui.table_column import ObjectColumn


class Employee(HasTraits):
    name = Unicode(label=u"姓名")
    department = Unicode(label=u"部门")
    salary = Int(label=u"薪水")
    bonus = Int(label=u"奖金")
    view = View("name", "department", "salary", "bonus")


table_editor = TableEditor(columns=[
    ObjectColumn(name="name", label=u"姓名"),
    ObjectColumn(name="department", label=u"部门"),
    ObjectColumn(name="salary", label=u"薪水"),
    ObjectColumn(name="bonus", label=u"奖金")
],
                           row_factory=Employee,
                           deletable=True,
                           show_toolbar=True)

list_editor = ListEditor(style="custom")
tab_editor = ListEditor(use_notebook=True, deletable=True, page_name=".name")


class EmployeeList(HasTraits):
    employees = List(Instance(Employee, factory=Employee))
    view = View(HGroup(Item("employees", editor=table_editor),
コード例 #18
0
ファイル: table_filter.py プロジェクト: jtomase/matplotlib
    #---------------------------------------------------------------------------

    def get_editor ( self, object ):
        """ Returns the traits editor of the column for a specified object.
        """
        return object.value_editor

#-------------------------------------------------------------------------------
#  Defines the columns to display in the generic filter rule table:
#-------------------------------------------------------------------------------

# Columns to display in the table for generic filter rules.
generic_table_filter_rule_columns = [
    GenericTableFilterRuleAndOrColumn( name = 'and_or', label = 'or' ),
    GenericTableFilterRuleNameColumn(  name = 'name' ),
    ObjectColumn(                      name = 'operation' ),
    GenericTableFilterRuleValueColumn( name = 'value' )
]

#-------------------------------------------------------------------------------
#  'RuleTableFilter' class:
#-------------------------------------------------------------------------------

class RuleTableFilter ( TableFilter ):
    """ A table filter based on rules.
    """
    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # Overrides the default **name** trait
コード例 #19
0
    gender = Enum('Male', 'Female')
    phone = Regex(value='000-0000', regex='\d\d\d[-]\d\d\d\d')

    traits_view = View('name',
                       'age',
                       'phone',
                       title='Create new employee',
                       width=0.18,
                       buttons=['OK', 'Cancel'])


# For readability, the parameters of the demo TableEditor are set here, rather
# than in the View:
table_editor = TableEditor(
    columns=[
        ObjectColumn(name='name', width=0.30),
        ObjectColumn(name='age', width=0.20),
        ObjectColumn(name='gender', width=0.25),
        ObjectColumn(name='phone', width=0.25)
    ],
    auto_size=False,
    deletable=True,
    sort_model=True,
    orientation='vertical',
    edit_view=View(Group('name', 'age', 'phone', show_border=True),
                   resizable=True),
    filters=[EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate],
    search=RuleTableFilter(),
    row_factory=Employee)

コード例 #20
0
        MatchesColumn2( name        = 'matches',
                        width       = 0.35,
                        format_func = lambda x: (x + [ '' ])[0].strip(),
                        editor      = CodeEditor( line =
                                          'object.live_search.selected_match',
                                        selected_line = 
                                          'object.live_search.selected_match' ),
                        style       = 'readonly',
                        edit_width  = 0.95,
                        edit_height = 0.33 ),
        FileColumn(     name        = 'base_name',
                        label       = 'Name',
                        width       = 0.30,
                        editable    = False ),
        ObjectColumn(   name        = 'ext_path',
                        label       = 'Path',
                        width       = 0.30,
                        editable    = False ),
    ],
    filter_name        = 'filter',
    auto_size          = False,
    show_toolbar       = False,
    selected           = 'selected',
    selection_color    = 0x000000,
    selection_bg_color = 0xFBD391
)    
    
#-- LiveSearch class -----------------------------------------------------------

class LiveSearch ( HasTraits ):
    
    # The currenty root directory being searched:
コード例 #21
0
people = [
    Person(name='Dave', age=39, phone='555-1212'),
    Person(name='Mike', age=28, phone='555-3526'),
    Person(name='Joe', age=34, phone='555-6943'),
    Person(name='Tom', age=22, phone='555-7586'),
    Person(name='Dick', age=63, phone='555-3895'),
    Person(name='Harry', age=46, phone='555-3285'),
    Person(name='Sally', age=43, phone='555-8797'),
    Person(name='Fields', age=31, phone='555-3547')
]

# Table editor definition:
filters = [EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate]

table_editor = TableEditor(columns=[
    ObjectColumn(name='name', width=0.4),
    ObjectColumn(name='age', width=0.2),
    ObjectColumn(name='phone', width=0.4)
],
                           editable=True,
                           deletable=True,
                           sortable=True,
                           sort_model=True,
                           auto_size=False,
                           filters=filters,
                           search=RuleTableFilter(),
                           row_factory=Person)


# 'ListTraitTest' class:
class ListTraitTest(HasStrictTraits):
コード例 #22
0
ファイル: tvtk_interface.py プロジェクト: sflarkin/yt-agora
class CameraControl(HasTraits):
    # Traits
    positions = List(CameraPosition)
    yt_scene = Instance('YTScene')
    center = Delegate('yt_scene')
    scene = Delegate('yt_scene')
    camera = Instance(tvtk.OpenGLCamera)
    reset_position = Instance(CameraPosition)
    fps = Float(25.0)
    export_filename = 'frames'
    periodic = Bool

    # UI elements
    snapshot = Button()
    play = Button()
    export_frames = Button()
    reset_path = Button()
    recenter = Button()
    save_path = Button()
    load_path = Button()
    export_path = Button()

    table_def = TableEditor(columns=[
        ObjectColumn(name='position'),
        ObjectColumn(name='focal_point'),
        ObjectColumn(name='view_up'),
        ObjectColumn(name='clipping_range'),
        ObjectColumn(name='num_steps')
    ],
                            reorderable=True,
                            deletable=True,
                            sortable=True,
                            sort_model=True,
                            show_toolbar=True,
                            selection_mode='row',
                            selected='reset_position')

    default_view = View(
        VGroup(
            HGroup(Item('camera', show_label=False),
                   Item('recenter', show_label=False),
                   label='Camera'),
            HGroup(Item('snapshot', show_label=False),
                   Item('play', show_label=False),
                   Item('export_frames', show_label=False),
                   Item('reset_path', show_label=False),
                   Item('save_path', show_label=False),
                   Item('load_path', show_label=False),
                   Item('export_path', show_label=False),
                   Item('export_filename'),
                   Item('periodic'),
                   Item('fps'),
                   label='Playback'),
            VGroup(Item('positions', show_label=False, editor=table_def),
                   label='Camera Path'),
        ),
        resizable=True,
        title="Camera Path Editor",
    )

    def _reset_position_changed(self, old, new):
        if new is None: return
        cam = self.scene.camera
        cam.position = new.position
        cam.focal_point = new.focal_point
        cam.view_up = new.view_up
        cam.clipping_range = new.clipping_range
        self.scene.render()

    def __init__(self, **traits):
        HasTraits.__init__(self, **traits)

    def take_snapshot(self):
        cam = self.scene.camera
        self.positions.append(
            CameraPosition(position=cam.position,
                           focal_point=cam.focal_point,
                           view_up=cam.view_up,
                           clipping_range=cam.clipping_range,
                           distance=cam.distance,
                           orientation_wxyz=cam.orientation_wxyz))

    def _export_path_fired(self):
        dlg = pyface.FileDialog(
            action='save as',
            wildcard="*.cpath",
        )
        if dlg.open() == pyface.OK:
            print "Saving:", dlg.path
            self.export_camera_path(dlg.path)

    def export_camera_path(self, fn):
        to_dump = dict(positions=[],
                       focal_points=[],
                       view_ups=[],
                       clipping_ranges=[],
                       distances=[],
                       orientation_wxyzs=[])

        def _write(cam):
            to_dump['positions'].append(cam.position)
            to_dump['focal_points'].append(cam.focal_point)
            to_dump['view_ups'].append(cam.view_up)
            to_dump['clipping_ranges'].append(cam.clipping_range)
            to_dump['distances'].append(cam.distance)
            to_dump['orientation_wxyzs'].append(cam.orientation_wxyz)

        self.step_through(0.0, callback=_write)
        pickle.dump(to_dump, open(fn, "wb"))

    def _save_path_fired(self):
        dlg = pyface.FileDialog(
            action='save as',
            wildcard="*.cpath",
        )
        if dlg.open() == pyface.OK:
            print "Saving:", dlg.path
            self.dump_camera_path(dlg.path)

    def dump_camera_path(self, fn):
        to_dump = dict(positions=[],
                       focal_points=[],
                       view_ups=[],
                       clipping_ranges=[],
                       distances=[],
                       orientation_wxyzs=[],
                       num_stepss=[])
        for p in self.positions:
            to_dump['positions'].append(p.position)
            to_dump['focal_points'].append(p.focal_point)
            to_dump['view_ups'].append(p.view_up)
            to_dump['clipping_ranges'].append(p.clipping_range)
            to_dump['distances'].append(p.distance)
            to_dump['num_stepss'].append(p.num_steps)  # stupid s
            to_dump['orientation_wxyzs'].append(p.orientation_wxyz)
        pickle.dump(to_dump, open(fn, "wb"))

    def _load_path_fired(self):
        dlg = pyface.FileDialog(
            action='open',
            wildcard="*.cpath",
        )
        if dlg.open() == pyface.OK:
            print "Loading:", dlg.path
            self.load_camera_path(dlg.path)

    def load_camera_path(self, fn):
        to_use = pickle.load(open(fn, "rb"))
        self.positions = []
        for i in range(len(to_use['positions'])):
            dd = {}
            for kw in to_use:
                # Strip the s
                dd[kw[:-1]] = to_use[kw][i]
            self.positions.append(CameraPosition(**dd))

    def _recenter_fired(self):
        self.camera.focal_point = self.center
        self.scene.render()

    def _snapshot_fired(self):
        self.take_snapshot()

    def _play_fired(self):
        self.step_through()

    def _export_frames_fired(self):
        self.step_through(save_frames=True)

    def _reset_path_fired(self):
        self.positions = []

    def step_through(self, pause=1.0, callback=None, save_frames=False):
        cam = self.scene.camera
        frame_counter = 0
        if self.periodic:
            cyclic_pos = self.positions + [self.positions[0]]
        else:
            cyclic_pos = self.positions
        for i in range(len(cyclic_pos) - 1):
            pos1 = cyclic_pos[i]
            pos2 = cyclic_pos[i + 1]
            r = pos1.num_steps
            for p in range(pos1.num_steps):
                po = _interpolate(pos1.position, pos2.position, p, r)
                fp = _interpolate(pos1.focal_point, pos2.focal_point, p, r)
                vu = _interpolate(pos1.view_up, pos2.view_up, p, r)
                cr = _interpolate(pos1.clipping_range, pos2.clipping_range, p,
                                  r)
                _set_cpos(cam, po, fp, vu, cr)
                self.scene.render()
                if callback is not None: callback(cam)
                if save_frames:
                    self.scene.save("%s_%0.5d.png" %
                                    (self.export_filename, frame_counter))
                else:
                    time.sleep(pause * 1.0 / self.fps)
                frame_counter += 1
コード例 #23
0
        """
        setattr(object, self.name, getattr(object, self.name) + 1)

    def sub(self, object):
        """ Decrement the affected player statistic.
        """
        setattr(object, self.name, getattr(object, self.name) - 1)


# The 'players' trait table editor:
player_editor = TableEditor(editable=True,
                            sortable=True,
                            auto_size=False,
                            columns=[
                                ObjectColumn(name='name',
                                             editable=False,
                                             width=0.28),
                                AffectsAverageColumn(name='at_bats',
                                                     label='AB'),
                                AffectsAverageColumn(name='strike_outs',
                                                     label='SO'),
                                AffectsAverageColumn(name='singles',
                                                     label='S'),
                                AffectsAverageColumn(name='doubles',
                                                     label='D'),
                                AffectsAverageColumn(name='triples',
                                                     label='T'),
                                AffectsAverageColumn(name='home_runs',
                                                     label='HR'),
                                AffectsAverageColumn(name='walks', label='W'),
                                ObjectColumn(name='average',
コード例 #24
0
            if (i * j) == n:
                result.append(Integer(n=i))
                if i != j:
                    result.append(Integer(n=j))
            i += 1

        result.sort(lambda l, r: cmp(l.n, r.n))

        return result


#-- The table editor used for the pop-up view ----------------------------------

factor_table_editor = TableEditor(columns=[
    ObjectColumn(name='n',
                 width=1.0,
                 editable=False,
                 horizontal_alignment='center')
],
                                  sortable=False,
                                  auto_size=False,
                                  show_toolbar=False,
                                  show_column_labels=False)

#-- The table editor used for the main view ------------------------------------

factors_view = View(
    Item('factors', id='factors', show_label=False,
         editor=factor_table_editor),
    id='enthought.traits.examples.demo.Advanced.factors_view',
    kind='info',
    height=0.30,
コード例 #25
0
    if "__table_editor__" in row_factory_kw:
        graph = row_factory_kw["__table_editor__"].object
        ID = make_unique_name("n", [node.ID for node in graph.nodes])
        del row_factory_kw["__table_editor__"]
        return godot.node.Node(ID)
    else:
        return godot.node.Node(uuid.uuid4().hex[:6])


#------------------------------------------------------------------------------
#  Node table editor:
#------------------------------------------------------------------------------

node_table_editor = TableEditor(
    columns=[
        ObjectColumn(name="ID"),
        ObjectColumn(name="label"),
        ObjectColumn(name="shape"),
        ObjectColumn(name="fixedsize"),
        ObjectColumn(name="width"),
        ObjectColumn(name="height"),
        ObjectColumn(name="pos"),
        ObjectColumn(name="style"),
        ObjectColumn(name="_draw_")
    ],
    other_columns=[  # not initially displayed
        ObjectColumn(name="sides")
    ],
    show_toolbar=True,
    deletable=True,
    filters=[EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate],
コード例 #26
0
                return (self.x >= self.xmin) & (self.x <= self.xmax)
            else:
                return (self.x >= self.xmin)
        elif self.xmax is not None:
            return (self.x <= self.xmax)
        else:
            return None


# The 'parameters' trait table editor:
parameters_editor = TableEditor(sortable=False,
                                configurable=False,
                                auto_size=False,
                                columns=[
                                    ObjectColumn(name='name',
                                                 editable=False,
                                                 horizontal_alignment='left'),
                                    ObjectColumn(name='value'),
                                    ObjectColumn(name='sigma_str',
                                                 editable=False,
                                                 label='Sigma'),
                                    CheckboxColumn(name='is_constant',
                                                   label='Constant'),
                                ])


class FitFunction(HasTraits):
    """Simplified curve_fit, allows to set constant parameters: 

    >>> fit = FitFunction(function = general.linear) #puts a valid function to fit object
    >>> fit.description
コード例 #27
0
ファイル: nirvana.py プロジェクト: hbwzhsh/foxengine
OPTIONAL = 0
MUST_NOT = 1
MUST_HAVE = 2



class DataUnit(HasTraits):
    name = Unicode()    #显示的名称
    sname = Str         #sif中的属性名
    value = Int         #值
    display = Trait(OPTIONAL,MUST_NOT,MUST_HAVE)
   

utable_editor = TableEditor(
        columns = [
                ObjectColumn(name='name'),
                ObjectColumn(name='value'),
        ],
        editable = False,
        show_column_labels = False,
    )


class DataUnits(HasTraits):
    data_units = List(Instance(DataUnit))

    def transfer_units(self,sif,xindex):
        for du in self.data_units:
            du.value = sif.__dict__[du.sname][xindex]

    view = View(