class Texture(Atom): #: Path to the texture file or image path = Str() #: If given, repeat in the u and v dimension repeat = Coerced(TextureParameters, kwargs={ 'enabled': True, 'u': 1, 'v': 1 }, coercer=coerce_texture) #: If given, adjust th eorigin to the u and v dimension origin = Coerced(TextureParameters, kwargs={ 'enabled': True, 'u': 0, 'v': 0 }, coercer=coerce_texture) #: If given, scale in the u and v dimension scale = Coerced(TextureParameters, kwargs={ 'enabled': True, 'u': 1, 'v': 1 }, coercer=coerce_texture)
class Standing(FormulaModel): constructor = Typed(Constructors) position = Coerced(int) points = Coerced(float) wins = Coerced(int) @classmethod def from_dict(cls, kwargs): kwargs.pop('positionText') # possible to have multiple constructors per driver, so we group the constructors here by default, per the api if 'Constructor' in kwargs.keys(): kwargs['constructor'] = Constructors( [Constructor.from_dict(kwargs.pop('Constructor'))]) else: kwargs['constructor'] = Constructors([ Constructor.from_dict(constructor) for constructor in kwargs.pop('Constructors') ]) return cls(**kwargs) def to_row(self): rows = [] base_row = { 'position': self.position, 'points': self.points, 'wins': self.wins } for constructor in self.constructor: row = copy.copy(base_row) row['constructor'] = constructor.constructorId rows.append(row) return rows
class JDF_Pattern(Atom): """describes a jdf pattern. has a number, location and name of file""" num=Coerced(int) x=Coerced(float) y=Coerced(float) name=Unicode() comment=Unicode() @property def xy_offset(self): return (self.x, self.y) @property def jdf_output(self): comment=format_comment(self.comment) return "P({pnum}) '{pname}.v30' ({px},{py}){com}".format( pnum=self.num, pname=self.name, px=self.x, py=self.y, com=comment) def __init__(self, **kwargs): """Processes kwargs to allow string definition to be passed as well""" tempstr=kwargs.pop("tempstr", "P(1)''.v30 (0,0)") kwargs["comment"]=kwargs.get("comment", "") kwargs["name"]=kwargs.get("name", tempstr.split("'")[1].split(".")[0]) kwargs["num"]=kwargs.get("num", tempstr.split("(")[1].split(")")[0]) kwargs["x"]=kwargs.get("x", tempstr.split("(")[2].split(")")[0].split(",")[0]) kwargs["y"]=kwargs.get("y", tempstr.split("(")[2].split(")")[0].split(",")[1]) super(JDF_Pattern, self).__init__(**kwargs)
class Driver(FormulaModel): birth_date = Typed(datetime.datetime) driverId = Unicode() shortId = Coerced(str) last = Unicode() first = Unicode() country = Unicode() url = Unicode() number = Coerced(int) seasons = Property() _seasons = Typed(Seasons) def _get_seasons(self): if not self._seasons: self.seasons = Seasons( self.api.query(driver_id=self.driverId, query_type='seasons')) return self._seasons def _set_seasons(self, seasons): self._seasons = seasons @classmethod def from_dict(cls, kwargs): if 'dateOfBirth' in kwargs.keys(): dob = kwargs.pop('dateOfBirth') if dob: kwargs['birth_date'] = datetime.datetime.strptime( dob, '%Y-%m-%d') kwargs['last'] = kwargs.pop('familyName') kwargs['first'] = kwargs.pop('givenName') kwargs['country'] = kwargs.pop('nationality') if 'permanentNumber' in kwargs.keys(): kwargs['number'] = kwargs.pop('permanentNumber') if 'code' in kwargs.keys(): kwargs['shortId'] = kwargs.pop('code', None) return cls(**kwargs) def __str__(self): return str(self.driverId) def __repr__(self): return str(self.first + ' ' + self.last) def to_row(self): return { 'birth_date': self.birth_date, 'driverId': self.driverId, 'shortId': self.shortId, 'last': self.last, 'first': self.first, 'country': self.country, 'number': self.number, 'object': self }
class Field(Atom): name = Str() datatype = Coerced(DataType.Flags) is_array = Bool() latency = Float(0.0) selector = Coerced(SelectorType.Flags) interval = Float(1.0) is_computed = Bool(False) is_reference = Bool(False)
class Demo(Atom): cint = Coerced(int) cfloat = Coerced(float) cstr = Coerced(str) #carr = Coerced(np.ndarray, coercer=np.asarray) carr = Typed(np.ndarray) @observe('carr') def _carr(self, new): print(new) print('joehoe')
class ObjectDependentInfos(Atom): """Base infos for tasks and interfaces. """ #: Id of the runtime dependency analyser to use for driver detection to add #: to the dependencies if instruments is set. DRIVER_ANALYSER = Unicode() #: Id of the runtime dependency analyser to use for profile detection to #: add to the dependencies if instruments is set. PROFILE_ANALYSER = Unicode() #: Set of instrument supported by this task. This should never be updated #: in place, it should always be copied and replaced by the new value. instruments = Coerced(set, ()) #: Runtime dependencies ids of this object. dependencies = Coerced(set, ()) #: Dict of interfaces supported by this object as {id: InterfaceInfos}. interfaces = Dict() def __init__(self, **kwargs): super(ObjectDependentInfos, self).__init__(**kwargs) if self.instruments: self._post_setattr_instruments(set(), self.instruments) def walk_interfaces(self, depth=None): """Yield all the interfaces of a task/interfaces. Parameters ---------- depth : int | None Interface depth at which to stop. """ for i_id, i in self.interfaces.items(): yield i_id, i if depth is None or depth > 0: d = depth - 1 if depth else None for ii_id, ii in i.walk_interfaces(d): yield ii_id, ii def _post_setattr_instruments(self, old, new): """Update the dependencies each time the instruments member is set. """ if new: self.dependencies |= set( (self.DRIVER_ANALYSER, self.PROFILE_ANALYSER)) else: self.dependencies -= set( (self.DRIVER_ANALYSER, self.PROFILE_ANALYSER))
class Input(Tag): name = d_(Unicode()) type = d_(Unicode()) disabled = d_(Coerced(bool)) checked = d_(Coerced(bool)) value = d_(Value()) def _default_name(self): return u'{}'.format(self.ref) @observe('name', 'type', 'disabled', 'checked', 'value') def _update_proxy(self, change): super(Input, self)._update_proxy(change)
class Image(Atom): """ An object representing an image. Once an image is created it should be treated as read only. User code should create a new image object if the parameters need to be changed. """ #: The format of the image. By default, the consumer of the image #: will probe the header to automatically infer a type. #: Base64 images need to be decoded using the base64.b64decode function #: from the standard library. format = Enum( 'auto', # Automatically determine the image format 'png', # Portable Network Graphics 'jpg', # Joint Photographic Experts Group 'gif', # Graphics Interchange Format 'bmp', # Windows Bitmap 'xpm', # X11 Pixmap 'xbm', # X11 Bitmap 'pbm', # Portable Bitmap 'pgm', # Portable Graymap 'ppm', # Portable Pixmap 'tiff', # Tagged Image File Format 'argb32', # Raw data in the 0xAARRGGBB format. # The `raw_size` of the image must be provided. ) #: The (width, height) raw size of the image. This must be provided #: for images where the size is not encoded in the data stream. raw_size = Coerced(Size, (0, 0)) #: The (width, height) size of the image. An invalid size indicates #: that the size of the image should be automatically inferred. A #: valid size indicates that the toolkit image should be scaled to #: the specified size. size = Coerced(Size, (-1, -1)) #: The aspect ratio mode to use when the toolkit scales the image. aspect_ratio_mode = Enum('ignore', 'keep', 'keep_by_expanding') #: The transform mode to use when the toolkit scales the image. transform_mode = Enum('smooth', 'fast') # XXX this needs to be augmented to support arrays. #: The bytestring holding the data for the image. data = Bytes() #: Storage space for use by a toolkit backend to use as needed. #: This should not typically be manipulated by user code. _tkdata = Value()
class DisplayItem(ToolkitObject): """ Basic display item. This represents an item in the display that has no effect on the model. """ #: Reference to the implementation control proxy = Typed(ProxyDisplayItem) #: Whether the item should be displayed display = d_(Bool(True)) #: A string representing the color of the shape. color = d_(ColorMember()).tag(view=True, group='Display') def _default_color(self): return Color(0, 0, 0) #: A tuple or list of the (x, y, z) direction of this shape. This is #: coerced into a Point. The direction is relative to the dimensions axis. position = d_(Coerced(Point, coercer=coerce_point)) def _default_position(self): return Point(0, 0, 0) #: A tuple or list of the (x, y, z) direction of this shape. This is #: coerced into a Point. The direction is relative to the dimensions axis. direction = d_(Coerced(Direction, coercer=coerce_direction)) def _default_direction(self): return Point(0, 0, 1) @observe('position', 'color', 'direction') def _update_proxy(self, change): super()._update_proxy(change) def show(self): """ Generates the display item Returns ------- item: Graphic3d item The item generated by this declaration. """ if not self.is_initialized: self.initialize() if not self.proxy_is_active: self.activate_proxy() return self.proxy.item
class dockarea(Atom): """ This class is deprecated. Use LayoutArea instead. """ geometry = Coerced(Rect, (-1, -1, -1, -1), coercer=_coerce_rect) maximized = Bool(False) maximized_item = Unicode() linked = Bool(False) child = Coerced(_areanode) def __init__(self, child, **kwargs): super(dockarea, self).__init__(child=child, **kwargs) def traverse(self): yield self for item in self.child.traverse(): yield item
class JDF_Main_Array(JDF_Array): """adds the marker locations for the main jdf array""" M1x=Coerced(int, (1500,)) M1y=Coerced(int, (1500,)) @property def jdf_output(self): array_comment=format_comment(self.comment) tl=["ARRAY ({x_start}, {x_num}, {x_step})/({y_start}, {y_num}, {y_step}){arr_com}".format( x_start=self.x_start, x_num=self.x_num, x_step=self.x_step, y_start=self.y_start, y_num=self.y_num, y_step=self.y_step, arr_com=array_comment)] tl.append("\tCHMPOS M1=({M1x}, {M1y})".format(M1x=self.M1x, M1y=self.M1y)) tl.extend([asg.jdf_output for asg in self.assigns]) tl.append("AEND\n") return tl
class OptGroup(Tag): label = d_(Unicode()) disabled = d_(Coerced(bool)) @observe('label', 'disabled') def _update_proxy(self, change): super(OptGroup, self)._update_proxy(change)
class Dummy(Model): _private = Int() computed = Int().tag(store=False) id = Int() enabled = Bool() string = Bool() list_of_int = List(int) list_of_str = List(str) list_of_any = List() list_of_tuple = List(Tuple()) list_of_tuple_of_float = List(Tuple(float)) tuple_of_any = Tuple() tuple_of_number = Tuple((float, int)) tuple_of_int_or_model = Tuple((int, Model)) tuple_of_forwarded = Tuple(ForwardTyped(lambda: NotYetDefined)) set_of_any = Tuple() set_of_number = Set(float) set_of_model = Set(AbstractModel) dict_of_any = Dict() dict_of_str_any = Dict(str) dict_of_str_int = Dict(str, int) typed_int = Typed(int) typed_dict = Typed(dict) instance_of_model = Instance(AbstractModel) forwarded_instance = ForwardInstance(lambda: NotYetDefined) coerced_int = Coerced(int) prop = Property(lambda self: True) tagged_prop = Property(lambda self: 0).tag(store=True)
class Toast(ToolkitObject): """A toast is a view containing a quick little message for the user.""" #: Text to display #: if this node has a child view this is ignored text = d_(Str()) #: Duration to display in ms duration = d_(Int(1000)) #: x position x = d_(Int()) #: y position y = d_(Int()) #: Position gravity = d_(Coerced(int, coercer=coerce_gravity)) #: Show the notification for the given duration show = d_(Bool()) #: A reference to the proxy object. proxy = Typed(ProxyToast) # ------------------------------------------------------------------------- # Observers # ------------------------------------------------------------------------- @observe("text", "duration", "show", "gravity", "x", "y") def _update_proxy(self, change): super()._update_proxy(change)
class Test(Atom): tt = Typed(subtest, ()) tc = Coerced(int) tb = Bool() ti = Int().tag(unit_factor=10, show_value=True, unit="dog", spec="sinbox") tl = ContainerList( default=[0, True, 3, 5, 6, True, False, False, 3, 4, 5, 6]).tag( no_spacer=True) te = Enum("tc", "ti").tag(spec="attribute") @property def run_funcs(self): """class or static methods to include in run_func_dict on initialization. Can be overwritten in child classes""" return [] @Callable def myc(self): print "myc called" @cached_property def te_mapping(self): return {"tc": self.tc, "ti": self.ti} def _observe_tc(self, change): print change def _observe_tb(self, change): print change def _observe_ti(self, change): print change
class TaskStatus(Atom): name = Coerced(str) running = Bool(False) started = Bool(False) completed = Bool(False) skipped = Bool(False) result = Typed(TaskResult) def _default_result(self): return TaskResult() def to_html(self): result_str = "" if not self.skipped: result_str = "<p>Result: %s</p>" % self.result.to_str() return """<h3>Task: %s (%s)</h3> %s """ % (self.name, "completed" if self.completed else "skipped", result_str) def to_dict(self): result = dict( name=self.name, completed=self.completed, skipped=self.skipped, ) tr = self.result.to_dict() if tr: result["result"] = tr return result
class Console(Container): """ Console widget """ proxy = Typed(ProxyConsole) #: Font family, leave blank for default font_family = d_(Unicode()) #: Font size, leave 0 for default font_size = d_(Int(0)) #: Default console size in characters console_size = d_(Coerced(Size,(81,25))) #: Buffer size, leave 0 for default buffer_size = d_(Int(0)) #: Display banner like version, etc.. display_banner = d_(Bool(False)) #: Code completion type #: Only can be set ONCE completion = d_(Enum('ncurses','plain', 'droplist')) #: Run the line or callabla execute = d_(Instance(object)) #: Push variables to the console #: Note this is WRITE ONLY scope = d_(Dict(),readable=False) @observe('font_family','font_size','console_size','buffer_size', 'scope','display_banner','execute','completion') def _update_proxy(self, change): super(Console, self)._update_proxy(change)
class ItemLayout(LayoutNode): """ A layout object for defining an item layout. """ #: The name of the DockItem to which this layout item applies. name = Unicode() #: Whether or not the item is floating. An ItemLayout defined as #: a toplevel item in a DockLayout should be marked as floating. floating = Bool(False) #: The geometry to apply to the item. This is expressed in desktop #: coordinates and only applies if the item is floating. geometry = Coerced(Rect, (-1, -1, -1, -1), coercer=_coerce_rect) #: Whether or not the item is linked with its floating neighbors. #: This value will only have an effect if the item is floating. linked = Bool(False) #: Whether or not the item is maximized. This value will only have #: effect if the item is floating or docked in a SplitLayout. maximized = Bool(False) def __init__(self, name, **kwargs): super(ItemLayout, self).__init__(name=name, **kwargs)
class MeasureSpy(Atom): """ Spy observing a task database and sending values update into a queue. """ observed_entries = Coerced(set) observed_database = Typed(TaskDatabase) queue = Typed(Queue) def __init__(self, queue, observed_entries, observed_database): super(MeasureSpy, self).__init__() self.queue = queue self.observed_entries = set(observed_entries) self.observed_database = observed_database self.observed_database.observe('notifier', self.enqueue_update) def enqueue_update(self, change): new = change['value'] if new[0] in self.observed_entries: self.queue.put_nowait(new) def close(self): # Simply signal the queue the working thread that the spy won't send # any more informations. But don't request the thread to exit this # is the responsability of the engine. self.queue.put(('', ''))
class Line(Edge): """ Creates a Line passing through the position and parallel to vector given by the direction. Attributes ---------- position: Tuple The position of the line. direction: Tuple The direction of the line. Examples -------- Line: position = (10, 10, 10) direction = (0, 0, 1) """ proxy = Typed(ProxyLine) #: List of points points = d_(List(Coerced(Pt, coercer=coerce_point))) @property def start(self): return coerce_point(self.proxy.curve.StartPoint()) @property def end(self): return coerce_point(self.proxy.curve.EndPoint()) @observe('points') def _update_proxy(self, change): super()._update_proxy(change)
class Option(Tag): value = d_(Unicode()) selected = d_(Coerced(bool)) @observe('value', 'selected') def _update_proxy(self, change): super(Option, self)._update_proxy(change)
class blah(Atom): a = Float(2) b = Coerced(int) #(2) c = Int(2) def _observe_a(self, change): print change
class docklayout(Atom): """ This class is deprecated. Use DockLayout instead. """ primary = Coerced(_primarynode) secondary = List(Coerced(_secondarynode)) def __init__(self, primary, *secondary, **kwargs): sup = super(docklayout, self) sup.__init__(primary=primary, secondary=list(secondary), **kwargs) def traverse(self): yield self if self.primary is not None: for item in self.primary.traverse(): yield item for secondary in self.secondary: for item in secondary.traverse(): yield item
class Input(Tag): #: Set the tag name tag = set_default('input') name = d_(Unicode()) type = d_(Unicode()) placeholder = d_(Unicode()) disabled = d_(Coerced(bool)) checked = d_(Coerced(bool)) value = d_(Value()) def _default_name(self): return u'{}'.format(self.id) @observe('name', 'type', 'disabled', 'checked', 'value', 'placeholder') def _update_proxy(self, change): super(Input, self)._update_proxy(change)
class JDF_Array(Atom): """describes a jdf array. defaults to an array centered at 0,0 with one item. array_num=0 corresponds to the main array""" array_num = Coerced(int) #Int() x_start = Coerced(int) #Int() x_num = Coerced(int, (1, )) #Int(1) x_step = Coerced(int) #Int() y_start = Coerced(int) #Int() y_num = Coerced(int, (1, )) #Int(1) y_step = Coerced(int) #Int() assigns = ContainerList().tag(no_spacer=True) # inside_type=jdf_assign) def add_assign(self, tempstr, comment): assign_type = tempstr.split("ASSIGN")[1].split("->")[0].strip().split( "+") assign_type = [unicode(at) for at in assign_type] pos_assign = [] shot_assign = "" for item in tempstr.split("->")[1].partition("(")[2].rpartition( ")")[0].split(")"): if "(" in item: xcor, ycor = item.split("(")[1].split(",") pos_assign.append((xcor, ycor)) elif "," in item: shot_assign = unicode(item.split(",")[1].strip()) self.assigns.append( JDF_Assign(assign_type=assign_type, pos_assign=pos_assign, shot_assign=shot_assign, assign_comment=comment))
class FloatArea(DockLayoutOp): """ A layout operation which creates a new floating dock area. This layout operation will create a new floating dock area using the given area layout specification. """ #: The area layout to use when building the new dock area. area = Coerced(AreaLayout)
class Rotate(TransformOperation): #: Rotation axis direction = Coerced(tuple) def _default_direction(self): return (0.0, 0.0, 1.0) #: Angle angle = Float(0.0, strict=False)
class Video(Tag): #: Set the tag name tag = set_default('video') controls = d_(Coerced(bool)) @observe('controls') def _update_proxy(self, change): super(Video, self)._update_proxy(change)
class FlowArea(Frame): """ A widget which lays out its children in flowing manner, wrapping around at the end of the available space. """ #: The flow direction of the layout. direction = d_( Enum('left_to_right', 'right_to_left', 'top_to_bottom', 'bottom_to_top')) #: The alignment of a line of items within the layout. align = d_(Enum('leading', 'trailing', 'center', 'justify')) #: The amount of horizontal space to place between items. horizontal_spacing = d_(Range(low=0, value=10)) #: The amount of vertical space to place between items. vertical_spacing = d_(Range(low=0, value=10)) #: The margins to use around the outside of the flow area. margins = d_(Coerced(Box, (10, 10, 10, 10))) #: A FlowArea expands freely in width and height by default. hug_width = set_default('ignore') hug_height = set_default('ignore') #: A reference to the ProxyFlowArea object. proxy = Typed(ProxyFlowArea) def flow_items(self): """ Get the flow item children defined on this area. """ return [c for c in self.children if isinstance(c, FlowItem)] #-------------------------------------------------------------------------- # Default Handlers #-------------------------------------------------------------------------- def _default_border(self): """ Get the default border for the flow area. The default value matches the default for Qt's QScrollArea. """ return Border(style='styled_panel', line_style='sunken') #-------------------------------------------------------------------------- # Observers #-------------------------------------------------------------------------- @observe('direction', 'align', 'horizontal_spacing', 'vertical_spacing', 'margins') def _update_proxy(self, change): """ An observer which sends state change to the proxy. """ # The superclass handler implementation is sufficient. super(FlowArea, self)._update_proxy(change)