Beispiel #1
0
    def __init__(self, parent = None):
        Component.__init__(self, parent)
        self.vertical = False

        # range
        self.__valueStart = 0
        self.__valueEnd = 1
        
        # value
        self.__value = 0
        
        # snap
        self.snap = 0
                
        # thumb
        self.thumb = Thumb(self)
        self.bindData('gamma', self.thumb, 'gamma', dir = '->')
        self._thumbStartAnim = koan.anim.AnimTarget('decay', 0, 0, 0, self)
        self.thumbImage = ''
        self.thumbEffect = None
        #self.bindData('thumbImage', self.thumb, 'background')
        self.autoDirty( ['thumbImage'] )

        # drag / drop thumb
        # self.changeEvent('snap', self.__updateValue)
        self.autoRemove( self.thumb.bind('Capture Begin', self.onSlideStart) )
        self.autoRemove( self.thumb.bind('Capture Offset', self.onSlideMove) )
        self.autoRemove( self.thumb.bind('Capture End', self.onSlideStop) )
        # click to
        self.bind('Mouse Down', self.onSlideTo)

        self.__updateThumbSize()
        self.bind('Size Change', self.__updateThumbSize)
Beispiel #2
0
	def __init__(self):
		Component.__init__(self)
		self.output = O()
		self.x = 0
		self.y = 0
		self.width = 100
		self.height = 100
Beispiel #3
0
    def __init__(self, parent = None, longFormat = False):        
        Component.__init__(self, parent)
        TextBase.__init__(self)

        self.iPlatform = subsys.GetLatestInterface('IPlatform')
        self.date = 2007, 1, 1
        self.margin = (2, 2, 2, 2)
        self.longFormat = longFormat
        self.bind('Mouse Down', koan.action.PureAction(self.setFocus))

        self.__datePicker = koan.platform.CreateDatePicker(callback = self.callback, longFormat = self.longFormat)
        self.window._window.AttachChild2( self.__datePicker.GetHWND() )

        #self.__datePicker.Show( False )
        self.changeEvent('text', self.invoke, 'Value Change', self)
        self.changeEvent('date', self.__onDateChange)
        self.changeEvent('font', self.__onFontChanged, sync = False)
        self.changeEvent('fontSize', self.__onFontChanged, sync = False)
        #koan.anim.Execute(0.3, self.__datePicker.Show, True)
        
        # font
        self.bind('Visible Change', self.__onEditVisibleChange)        
        self.bind('Size Change', self.__updateEditWndPos)
        self.bind('Position Change', self.__updateEditWndPos)
        self.bind('Parent Position Change', self.__updateEditWndPos)
        self.bind('Focus Change', self.__onEditVisibleChange)
        
        child = self
        while parent != None:
            child.autoRemove(parent.bind('Parent Position Change', child.invoke, 'Parent Position Change', postevent = False))
            child = parent
            parent = child.parent
Beispiel #4
0
 def __init__(self, parent):
     Component.__init__(self, parent)
     TextBase.__init__(self)
     CheckBase.__init__(self)
     TipBase.__init__(self)
     self.command = ''
     self.changeEvent('checked', self.__onCheckChanged, postevent = False)
Beispiel #5
0
 def get_dash_dash_state_from_string(self, state, state_str, state_id=None, loc_not_modifier=None):
     """
     Complete Association or Intraprotein state from str.
     Returns State object.
     """
     comp = state_str.split('--') 
     compA_name = comp[0].split('_')[0]
     compA_domain = self.df.get_association_domain_from_str(state_str, 'A') 
     compB_name = comp[1].split('_')[0]
     compB_domain = self.df.get_association_domain_from_str(state_str, 'B')
     if compB_name.startswith('['):
         state.type = 'Intraprotein' # A_[a]--[b]
         comp_object = Component(compA_name, compA_domain)
         comp_object.second_domain = re.sub('[\[\]]', '', compB_name)
         state.components = [comp_object]
     else:
         state.type = 'Association' # A--B
         if state_id:
             idA = state_id.split('--')[0]
             idB = state_id.split('--')[1]
         else:
             idA = None
             idB = None
         compA_object = Component(compA_name, compA_domain, idA)
         compB_object = Component(compB_name, compB_domain, idB)
         state.components = [compA_object, compB_object]
         if compA_name == compB_name:
             state.homodimer = True
     return state
Beispiel #6
0
    def __init__(self, transfer_func, transfer_func_params, time_const_RC,
                 time_const_output, debug=False):
        Component.__init__(self, transfer_func, transfer_func_params,
                           0, time_const_output, debug)

        self.time_const_RC = time_const_RC
        self.input_pre = 0
Beispiel #7
0
    def __init__(self, parent=None):
        Component.__init__(self, parent)
        CaptureObject.__init__(self)
        self.vertical = True

        self.autoHide = False
        self.setRange(100, 10)
        self.changeEvent("autoHide", self.__fixVisible)
        self.changeEvent("fullSize", self.__fixVisible)
        self.changeEvent("viewSize", self.__fixVisible)

        self.__offset = 0  # 0 ~ 1
        self.thumbEffect = None
        self.thumbMinSize = 50
        self.thumbImage = ""
        self.isMouseOverThumb = False
        self.capture = False

        self.autoDirty(["viewSize", "fullSize", "thumbImage"])
        self.changeEvent("fullSize", self.__fixScroll)
        self.changeEvent("viewSize", self.__fixScroll)

        self.bind("Capture Begin", self.__onBeginScroll, postevent=False)
        self.bind("Capture Offset", self.__onScroll, postevent=False)
        self.bind("Capture End", self.__onEndScroll, postevent=False)
        self.bind("Mouse Move", self.__onMouseMove)
        self.bind("Mouse Leave", setattr, self, "isMouseOverThumb", False)
        self.__thumbStartAnim = koan.anim.AnimTarget("decay", 0, 0, 0, self)
    def __init__(self, dData):   #sComponentID, textureGrid, fDelay, iFrameWidth, iFrameHeight, iFramesWide, iFramesHigh):
        Component.__init__(self, "ANIMATION:%s"%(dData['componentID']), True, 2)

        #This animation starts off as inactive and will await a trigger from a system function
        self._bActive = False

        #This will denote the time in-between each frame of the animation in the textureGrid.
        self._fDelay = dData['delay']

        #This will tell us when it is time to update the frame.
        self._fAnim_Time = 0.0

        #The current frame on the texture grid (top-left)
        self._iCurrent_Frame = [0,0]

        #The texture grid details
        self._iFrame_Width = dData['frameWidth']
        self._iFrame_Height = dData['frameHeight']
        self._iFrames_Wide = dData['framesWide']
        self._iFrames_High = dData['framesHigh']

        #This holds the texture for the animation!
        self._Animation_Sprite = sf.Sprite(dData['Texture'][0])

        self._Animation_Sprite.set_texture_rect(sf.IntRect(0,0,self._iFrame_Width, self._iFrame_Height))
Beispiel #9
0
    def __init__(self, parent = None):        
        Component.__init__(self, parent)
        TextBase.__init__(self)
        self.vscroll = False
        self.hscroll = False
        self.maxlen = -1
        self.bgColor = color.white

        self.margin = (2, 2, 2, 2)
        self.bind('Mouse Down', koan.action.PureAction(self.setFocus))

        self.__edit = koan.platform.CreateEdit(callback = self.callback)
        self.changeEvent('text', self.__onTextChanged, sync = False)
        self.changeEvent('text', self.invoke, 'Value Change', self)
        self.changeEvent('align', self.__onEditStyleChange)
        self.changeEvent('vscroll', self.__onEditStyleChange)
        self.changeEvent('hscroll', self.__onEditStyleChange)
        self.changeEvent('maxlen', self.__onEditMaxlenChange, sync = False)
        
        # font
        self.changeEvent('font', self.__onFontChanged, sync = False)
        self.changeEvent('fontSize', self.__onFontChanged, sync = False)
        self.changeEvent('fontColor', self.__onFontColorChange, sync = False)
        self.changeEvent('bgColor', self.__onBgColorChange, sync = False)
        self.bind('Visible Change', self.__onEditVisibleChange)        
        self.bind('Size Change', self.__updateEditWndPos)
        self.bind('Position Change', self.__updateEditWndPos)
        self.bind('Parent Position Change', self.__updateEditWndPos)
        self.bind('Focus Change', self.__onEditVisibleChange)
        
        child = self
        while parent != None:
            child.autoRemove(parent.bind('Parent Position Change', child.invoke, 'Parent Position Change', postevent = False))
            child = parent
            parent = child.parent
Beispiel #10
0
 def __init__(self, dData):
     Component.__init__(self, "BOX:%s"%(dData['componentID']), False, 1)
     self._box = sf.RectangleShape((int(dData['width']),int(dData['height'])))
     self._box.position = (int(dData['x']),int(dData['y']))
     self._box.fill_color = sf.Color.WHITE
     self._box.outline_color = sf.Color.RED
     self._box.outline_thickness = 3.0
Beispiel #11
0
 def __init__(self, scheme = 'axisymmetric', **kwargs):
     # Initialize scheme-dependent attributes
     if scheme not in ['axisymmetric','two_column']:
         raise ValueError,'\n \n ++++ CliMT.dynamics: Scheme %s unknown' % scheme
     exec('self.__%s_dynamics__init__()' % string.lower(scheme))
     # Initialize fields etc. 
     Component.__init__(self, **kwargs)
 def __init__(self):
     Component.__init__(self)
     self.tailNodes = []
     self.previousHeadX = 1
     self.previousHeadY = 1
     self.tailIndex = 0
     self.addNodeOnUpdate = False
Beispiel #13
0
    def __init__(self, scheme='slab', **kwargs):
        # Initialize scheme-dependent attributes
        if   scheme == 'slab': self.__slab__init__()
        else: raise ValueError,'\n \n ++++ CliMT.ocean: Scheme %s unknown' % scheme

        # Initialize parameters, grid, fields etc
        Component.__init__(self, **kwargs)
Beispiel #14
0
    def __init__(self, scheme = 'hard', **kwargs):
        # Initialize scheme-dependent attributes
        try: exec('self.__%s__init__()' % string.lower(scheme))
        except: raise ValueError,'\n \n ++++ CliMT.convection: Scheme "%s" unknown' % scheme

        # Initialize fields etc. 
        Component.__init__(self, **kwargs)
Beispiel #15
0
def determineFitOffset(components, full, shelled):
  '''
  This function will take a list of components and an object body,
  and will then determine how far components must be set back from the surface
  to prevent intersection with it.
  '''
  # figure out how far back we need to set each component to make it
  # not intersect the body of the object.
  for comp in components:
    if comp['type'] in Component.no_offset():
      continue
    loc = comp['coords']
    normal = comp['threed_normal']
    ct = 0
    print 'original:', loc
    while True:
      mod_comp = dict(comp)
      mod_comp['coords'] = [c_i - n_i for c_i, n_i in zip(loc, normal)]
      writeOpenSCAD(CHECK_INTERSECT_SCRIPT, [mod_comp], object_body=shelled)
      empty = createsEmptySTL(CHECK_INTERSECT_SCRIPT, SCRATCH)
      ct += 1
      if empty:
        break
      if ct > Component.max_offset(mod_comp['type']):
        raise Exception(''.join(["can't fit component",str(mod_comp),"into body"]))
      loc = mod_comp['coords']
    comp['coords'] = loc
    comp['offset'] = ct # note that this is in units of mm, for button caps
    print 'new:', loc
  return components
Beispiel #16
0
 def test_should_return_list_of_lists(self):
     """
     Should return list of lists if components registered
     """
     subject = Component()
     subject.register_component(Component())
     self.assertEqual(req.components_of_list(subject.components), [[]])
Beispiel #17
0
    def __init__(self, cShape, cBody, dData):
        Component.__init__(self, "CSHAPE:%s"%(dData['componentID']), False, 0)

        self._sDependent_Comp_Name = dData["dependentComponentName"]

        self._cShape = cShape

        self._cBody = cBody
Beispiel #18
0
 def __init__(self, owner, playergroup, enemygroup):
     Component.__init__(self, owner)
     
     self.playergroup = playergroup
     self.enemygroup = enemygroup
     
     # All entity list
     self.entitylist = []
Beispiel #19
0
 def __init__(self, parent = None):
     Component.__init__(self, parent)
     self.stretch = 'Fill'
     self.tabStop = False
     #self.scalemode = 'Both'        #wpf: StretchDirection
     self.__scale = 1, 1
     self.__offset = 0, 0
     self.autoStretch(['stretch'], ['Size Change', 'Child Add', 'Child Size Change'])
Beispiel #20
0
    def __init__(self, scheme = 'simple', **kwargs):

        # Initialize scheme-dependent attributes
        try: exec('self.__%s__init__()' % string.lower(scheme))
        except: raise ValueError,'\n \n ++++ CliMT.turbulence: Scheme %s unknown' % scheme

        # Initialize parameters, grid, fields etc
        Component.__init__(self, **kwargs)
Beispiel #21
0
 def set_visible(self, flag):
     """ Set container visible/invisible. Set all components in container visible/invisible.
     
     :param flag: True - visible, False - invisible
     """        
     Component.set_visible(self, flag)
     for comp in self.components:
         if comp: comp.set_visible(flag)
Beispiel #22
0
 def do_set_property(self, pspec, value):
     name = pspec.name.replace('-', '_')
     if name in ['descriptions', 'ids', 'path']:
         if value != getattr(self, name):
             self.propvalues[name] = value
             self.emit('changed', Change(name))
         return
     Component.do_set_property(self, pspec, value) 
Beispiel #23
0
 def __init__(self, **traits):
     Component.__init__(self, **traits)
     self._update_component_view_bounds()
     if 'zoom_tool' not in traits:
         self.zoom_tool = ViewportZoomTool(self)
     if self.enable_zoom:
         self._enable_zoom_changed(False, True)
     return
Beispiel #24
0
 def __init__(self, **traits):
     if v_width == 0:
         self._init_images()
     Component.__init__(self, **traits)
     self._scrolling = self._zone = NO_SCROLL
     self._line_up_suffix = self._line_down_suffix = self._slider_suffix = ''
     self._style_changed(self.style)
     return
 def __init__(self):
     Component.__init__(self)
     self.controls = {
         b'M': messages.MOVE_RIGHT,
         b'K': messages.MOVE_LEFT,
         b'H': messages.MOVE_UP,
         b'P': messages.MOVE_DOWN,
         b'x': messages.ADD_NODE
     }
Beispiel #26
0
    def __init__(self, scheme = 'ccm3', **kwargs):
        # Initialize scheme-dependent attributes
        if scheme in ['gray','grey','graygas']: scheme='greygas'
        if scheme not in ['greygas','chou','ccm3','cam3', 'rrtm']:
            raise ValueError,'\n \n ++++ CliMT.radiation: Scheme %s unknown' % scheme
        exec('self.__%s__init__()' % string.lower(scheme))

        # Initialize fields etc. 
        Component.__init__(self, **kwargs)
Beispiel #27
0
 def __init__(self, time_const_RC, time_const_output, debug=False):
     """
     Initializes a LowpassFilter-object.
     @param time_const_RC Time constant as in a electrical low-pass filter.
     @param dt Based on wikipedia's description of a low-pass filter, the
     time-step dt is required for the transfer function.
     """
     Component.__init__(self, identity, [], 0, time_const_output, debug)
     self.time_const_RC = time_const_RC
Beispiel #28
0
    def __init__( self, dData ):
        Component.__init__(self, "TILE:%s"%(dData['componentID']), False, 0)
        #Tells whether or not the tile is visible or not
        self._is_Active = False

        #Identifies the type of tile that is drawn (denotes tile IDs on the tile_atlas.)
        self._tileID = 0

        self._isTransparanent = True
Beispiel #29
0
	def __init__(self, _id, _label, _cap, _device1, _device2):
		Component.__init__(self, _id, _label)
		self.compType = 'link'
		self.totalCap = _cap
		self.availableCapUp = 0
		self.availableCapDown = 0
		self.device1 = _device1
		self.device2 = _device2
		self.flows = []
Beispiel #30
0
    def __init__(self, dData):
        Component.__init__(self, "MESH:%s"%(dData["componentID"]), False, 0)
        self._mesh = [ [] for layer in xrange(config.CHUNK_LAYERS) ]

        #This is for linking this mesh with a texture within the Asset_Manager.
        self._lTileAtlas = []

        for i in xrange(config.CHUNK_LAYERS):
            self._lTileAtlas.append(dData.get("TileAtlas"+str(i), None))
Beispiel #31
0
 def terminate(self, status):
     self.services.log('Really Calling terminate()')
     Component.terminate(self, status)
 def __init__(self, services, config):
     Component.__init__(self, services, config)
     print 'Created %s' % (self.__class__)
Beispiel #33
0
 def __init__(self, services, config):
     Component.__init__(self, services, config)
Beispiel #34
0
 def __init__(self, **kwargs):
     self.command = "mv"
     self.name = "mv"
     Component.__init__(self, **kwargs)
Beispiel #35
0
# Copyright 2016-2018, Pulumi Corporation.  All rights reserved.

from component import Component

component_a = Component("a", echo=42)
component_b = Component("b", echo=component_a.echo)
component_c = Component("c", echo=component_a.childId)
Beispiel #36
0
 def __init__(self, services, config):
     print('dakota_model_driver: Construct')
     Component.__init__(self, services, config)
Beispiel #37
0
 def __init__(self, **kwargs):
     Component.__init__(self, **kwargs)
     self.command = "stdhep_" + self.name
 def __init__(self, services, config):
     print('test_framework_driver: Construct')
     Component.__init__(self, services, config)
     self.running_components = {}
     self.ports = {}
Beispiel #39
0
 def __init__(self, **kwargs):
     self.command = "gunzip"
     self.name = "gunzip"
     Component.__init__(self, **kwargs)
Beispiel #40
0
 def __init__(self, value):
     Component.__init__(self, value)
Beispiel #41
0
 def __init__(self, ID, protocolname, protocoldescr, dependentprotoname, dependencypattern):
     Component.__init__(self, ID, 'start_field', None)
     self.PROTOCOLNAME = protocolname
     self.PROTOCOLDESCR = protocoldescr
     self.DEPENDENTPROTONAME = dependentprotoname
     self.DEPENDENCYPATTERN = dependencypattern
Beispiel #42
0
def deformShell(components, full, shelled):
    '''
  If certain types of components intersect each other (e.g., non-input
  components like processing boards), we can deform an object's shell
  to make space for them. This function pushes the objects out along
  their normals and creates a bounding box addition.
  '''
    oname = shelled
    print 'your components intersect. now deforming shell...'
    warn_user = False
    # figure out how far FORWARD we need to set each component to make it
    # not intersect with each other.
    no_skipped_comps = 0
    for comp in components:
        curr_type = comp['type']
        print "CURR COMP IS ", curr_type
        if comp['type'] in Component.no_moving():
            no_skipped_comps += 1
            continue
        if no_skipped_comps == len(components):
            warn_user = True
            print 'we skipped all the components!'
            break
        loc = comp['coords']
        normal = comp['threed_normal']
        ct = 0
        while True:
            mod_comp = dict(comp)
            mod_comp['coords'] = [c_i + n_i for c_i, n_i in zip(loc, normal)]
            print "new coords checking is ", mod_comp['coords']
            print "currently we are on ", curr_type
            mod_comp_list = [
                comp for comp in components
                if not (curr_type == comp.get('type'))
            ]
            #create a new list w/ the modified coordinates
            mod_comp_list.append(mod_comp)
            print "checking intersections!"
            if not checkIntersections(
                    mod_comp_list):  #if there are no intersections
                print "sweet, no intersections"
                break
            if ct > 30:
                warn_user = True
                break
            loc = mod_comp['coords']
            ct += 1
        comp['coords'] = loc
        print 'new:', loc, ' for ', comp['type']
        if warn_user:
            raise Exception(
                "Components intersect beyond an aesthetically pleasing fix. Try a redesign?"
            )

        #just for the mainboard
        for comp in components:
            #add more objects here
            if comp['type'] == Component.main_board:
                global pushed_comp
                pushed_comp.append(comp['type'])
                print 'adding a bounding box to the main board...'
                writeOpenSCAD(DEFORM_SHELL_SCRIPT,
                              comp,
                              object_body=shelled,
                              full_body=full)
                oname = shelled.replace('.stl', '-deformed.stl')
                callOpenSCAD(DEFORM_SHELL_SCRIPT, oname)
                print 'done!'
                return oname
    return oname
Beispiel #43
0
def writeOpenSCAD(script,
                  components={},
                  object_body='',
                  deflated='',
                  full_body='',
                  top='',
                  boss=None,
                  bosses=[],
                  topbot='',
                  debug=False):
    '''
  This horrifying function actually puts together the scripts necessary to do
  the openSCAD operations that Makers' Marks relies on. It can write scripts
  for deforming shells, checking intersections, and more, based on the
  script name passed in. It's bad, though.
  '''
    text = 'union() {\n'

    if script == DEFORM_SHELL_SCRIPT:
        text += '''
  difference() {
    import("%(obj_body)s");
    %(solid_bb_clearance)s
  }
    ''' % {
            'obj_body': object_body,
            'solid_bb_clearance': placeBoundingBoxSCAD(components,
                                                       geom='bbsolid')
        }  #subtracts translated solid bounding box from body

        text += '''
    difference() {
     rotate([180,0,0])translate([0,0,7.5])%(shelled_bb)s
      import("%(solid_obj_body)s");
       }
    ''' % {
            'shelled_bb': placeBoundingBoxSCAD(components, geom='bbshell'),
            'solid_obj_body': full_body
        }  #subtracts solid body from hollow bounding box

    if script == CHECK_INTERSECT_SCRIPT and object_body == '':
        text += '''
intersection() {
  %(comp_0)s
  %(comp_1)s
}
''' % {
            'comp_0': placeCompOpenSCAD(components[0], geom='clearance'),
            'comp_1': placeCompOpenSCAD(components[1], geom='clearance'),
        }
    if script == CHECK_INTERSECT_SCRIPT and not object_body == '':
        text += '''
intersection() {
  %(comp_0)s
  import("%(obj)s");
}
''' % {
            'comp_0': placeCompOpenSCAD(components[0], geom='clearance'),
            'obj': object_body,
        }

    if script == SUB_COMPONENT_SCRIPT:
        comps_sub = ''
        comps_add = ''
        for component in components:
            if component['type'] == Component.parting_line or component[
                    'type'] == Component.parting_line_calculated:
                # these will be dealt with in a special step later
                continue
            comps_sub += placeCompOpenSCAD(component, geom='sub')
            if Component.no_trim(component['type']):
                comps_add += placeCompOpenSCAD(component, geom='add')
            elif component['type'] in pushed_comp:
                comps_add += internalOnlyBoundingBox(
                    placeCompOpenSCAD(component, geom='add'), full_body,
                    component)
            else:
                comps_add += internalOnly(
                    placeCompOpenSCAD(component, geom='add'), full_body)
        text += '''
difference() {
\timport("%(obj)s");
// first we need to subtract everything
\t%(comps_sub)s
}
// now we add mounting points back in (they are cut to size of the body)
%(comps_add)s
''' % {
            'obj': object_body,
            'comps_sub': comps_sub,
            'comps_add': comps_add,
        }

    if script == PART_SCRIPT:
        pline = 'cube(1);'
        for comp in components:
            if comp['type'] is Component.parting_line_calculated:
                pline = placePLineOpenSCAD(comp)
                break
        if pline == '':
            print 'wtf? no parting line?'
        if top == True:
            text += '''
difference(){
\timport("%(obj)s");
\t%(pline)s
}
''' % {
                'obj': object_body,
                'pline': pline,
            }
        if top == False:
            text += '''
intersection(){
\timport("%(obj)s");
\t%(pline)s
}
''' % {
                'obj': object_body,
                'pline': pline,
            }

    if script == BUTTON_CAP_SCRIPT:
        print "cutting button caps by ", components['offset']
        text += '''
difference() {
import("stls/button-cap.stl");
translate([0,0,-%(z)s])import("stls/button-cap-sub.stl");
}
''' % {
            'z': components['offset'],
        }

    if script == BOSS_CHECK_COMPS_SCRIPT:
        all_comp_union = 'union(){'
        for comp in components:
            placecomp = placeCompOpenSCAD(comp, geom='clearance')
            all_comp_union += (placecomp)
        all_comp_union += '}'
        text += '''
intersection() {
\t%(boss)s
\t%(comps)s
}
''' % {
            'boss': placeBossOpenSCAD(boss, 'add'),
            'comps': all_comp_union,
        }

    if script == BOSS_PUT_SCRIPT:
        bosses_add = ''
        bosses_sub = ''
        for boss in bosses:
            bosses_add += placeBossOpenSCAD(boss, 'add', topbot)
            bosses_sub += placeBossOpenSCAD(boss, 'sub', topbot)
        text += '''
difference() {
  // add together bosses and hollowed body
  union() {
    // make sure we only take boss parts inside the body
    intersection() {
      union() {
        %(bosses_add)s
      }
      import("%(full)s");
    }
    // ok, here is the hollowed body
    import("%(obj)s");
  }

  // now here is the part we subtract: all the boss middles
  union() {
    %(bosses_sub)s
  }
}
''' % {
            'bosses_add': bosses_add,
            'bosses_sub': bosses_sub,
            'full': full_body,
            'obj': object_body,
        }

    if script == SHELL_SCRIPT:
        text += '''
difference() {
  import("%(obj)s");
  import("%(deflated)s");
}
''' % {
            'obj': object_body,
            'deflated': deflated
        }

    if script == MINKOWSKI_TOP or script == MINKOWSKI_BOT:
        for comp in components:
            if comp['type'] is Component.parting_line_calculated:
                parting_line = comp
                break
        topbot = 'top'
        diffint = 'difference'
        orig = '''
        linear_extrude(height = 4) { // so we translate -2 and extrude 4
            difference() { // we are just going to take the area between the two profiles
                offset(r=-2.25) { // we can offset from the full body part by -2.25 and -3.
                    projection(cut=true) {
                        position_original();
                    }
                }
                offset(r=-3.25) {
                    projection(cut=true) {
                        position_original();
                    }
                }
            }
        }
'''
        if script != MINKOWSKI_TOP:
            topbot = 'bot'
            diffint = 'intersection'
            orig = '''
        linear_extrude(height = 4) { // just need a little lip on the bottom piece
            difference() { // we are just going to take the area between the two profiles
                projection(cut=true) {
                    position_original();
                }
                offset(r=-2) {
                    projection(cut=true) {
                        position_original();
                    }
                }
            }
        }
'''
        text = '''
module position_original() {
    rotate([-90,0,0]) { // need this
      rotate(%(axis)s) { // negate these, too
        rotate(%(z_rotation)s) { // negate and do Z first
          rotate(%(xy_rotation)s) { // negate and do Z first
            translate(%(translation)s) { // negate numbers
                import("%(full_body)s");
            }
        }
      }
    }
}

module position_%(topbot)s() {
    rotate([-90,0,0]) { // need this
      rotate(%(axis)s) { // negate these, too
        rotate(%(z_rotation)s) { // negate and do Z first
          rotate(%(xy_rotation)s) { // negate and do Z first
            translate(%(translation)s) { // negate numbers
                import("%(object_body)s");
            }
        }
      }
    }
}

module xy_cutbox() {
    translate([-1000,-1000,0]) {
        cube(2000);
    }
}

union() {
    translate([0,0,1]) { // move back into place after cut happens
        %(diffint)s() { // we need to cut off a bit of the base model to make this work
            translate([0,0,-1]) {
                position_%(topbot)s();
            }
            xy_cutbox();
        }
    }
    translate([0,0,-2]) {// we want to go down 2 and up 2
        %(orig)s
    }
    ''' % {
            'topbot': topbot,
            'diffint': diffint,
            'translation': str([-t for t in parting_line['coords']]),
            'z_rotation': str([0, 0, -parting_line['rotations'][-1]]),
            'xy_rotation': str([0, -parting_line['rotations'][1], 0]),
            'axis': str([-r for r in parting_line['axis']]),
            'orig': orig,
            'object_body': object_body,
            'full_body': full_body,
        }

    text += '\n} // close union'
    if debug:
        print text
    else:
        #print 'writing this: ', text, '\n for this: ', script
        f = open(script, 'w+')
        f.write(text)
        f.close()
Beispiel #44
0
# Copyright 2016-2021, Pulumi Corporation.  All rights reserved.

from component import Component

component = Component("component")
result = component.get_message("hello")
# pylint: disable=invalid-name
import sys
import os
from copy import deepcopy
from component import Component

path = os.path.join(sys.path[0], "day24_input")
file = open(path, "r")

components = []

for line in file:
    a,b = [int(d) for d in line.split("/")]
    components.append(Component(a, b))

def find_zeros_and_rest(components):
    pairs = []

    for i in range(len(components) - 1, -1, -1):
        component = components[i]
        if component.has_zero():
            components_copy = deepcopy(components)
            if component.a != 0:
                component.rotate()
            del components_copy[i]

            pairs.append((component, components_copy))

    return pairs

def find_strongest_subcomponents(start, rest_of_components):
Beispiel #46
0
 def __init__(self, minevents=0, **kwargs):
     self.name = "lhe_count"
     self.minevents = minevents
     Component.__init__(self, **kwargs)
Beispiel #47
0
 def __init__(self, dData):
     Component.__init__(self, "MISC:%s"%(dData['componentID']), False, 0)
     self._storage = dData['storage']
Beispiel #48
0
 def terminate(self, status):
     #pytau.start(self.timer)
     self.services.log('Really Calling terminate()')
     #pytau.stop(self.timer)  #need to stop the timer here because Component.terminate() will call sys.exit
     #pytau.dbDumpIncr('worker')
     Component.terminate(self, status)
Beispiel #49
0
 def __init__(self, **kwargs):
     self.name = "Tar files"
     self.command = "python"
     Component.__init__(self, **kwargs)
Beispiel #50
0
class Process:
    def __init__(self, coil, tube):
        self.coil = coil
        coil.tube = tube
        self.tube = tube
        tube.coil = coil
        self.component = Component()

        self._units = {
            'wire diameter': 'm',
            'length': 'm',
            'volume': u"m\u00B3",
            'mass': 'g',
            'resistance': u"\u2126",
            'current': 'A',
            'voltage': 'V',
            'power': 'W',
            'force': 'N',
            'wire_d': 'mm',
            'extension': 'm',
            'layers': ''
        }

    def explore_wire_diameter(self, debug=False, resolution=0.01):
        options = [
            'resistance', 'length', 'mass', 'volume', 'current', 'voltage',
            'power'
        ]

        _analyser = Analyser()
        _analyser.units = self._units

        def create_graph(val):
            clear_output(wait=True)
            output_notebook(hide_banner=True)

            if val is None:
                pass
            elif val[
                    'owner'].layout.grid_area == "explore":  # disable unused selects
                _analyser.data["explore"] = val['new']
                for key, child in _analyser.unit_children.items():
                    child.disabled = key not in _analyser.data["explore"]
            else:
                _analyser.data[val['owner'].layout.grid_area] = val['new']
            display(_analyser.gui)
            for i in range(1):
                import time
                time.sleep(1)
            _analyser.explore_wire_diameter(
                self.coil,
                self.tube,
                params=list(_analyser.data["explore"]),
                units=_analyser.units,
                _start_d=_analyser.data["wire_d_range"][0],
                _end_d=_analyser.data["wire_d_range"][1] + resolution,
                _increment_d=resolution,
                _coil_layer_height=_analyser.data["coil_layer_height"],
                debug=debug)

        def update_units(val):
            _analyser.units[val.owner.layout.grid_area] = val.new
            create_graph(None)  # update

        # create unit selections
        units = ["G", "M", "k", "", "c", "m", '\u03BC', "n"]
        _analyser.unit_children = {
            opt: self.component.select(
                update_units,
                _analyser,
                options=[s + self._units[opt] for s in units],
                variable=opt,
                index=3,
                width='35px',
                height='13px',
                disabled=True)
            for opt in options
        }

        unit_layout = ('"%s"\n' * len(options)) % tuple(options)

        template_rows = (("%.1f" % (100. / len(options)) + "% ") *
                         len(options))[:-1]
        unit_gui = self.component.pack(children=list(
            _analyser.unit_children.values()),
                                       layout=unit_layout,
                                       template_columns='100%',
                                       template_rows=template_rows,
                                       width="55px")

        children = [
            unit_gui,
            self.component.multi_select(create_graph,
                                        _analyser,
                                        options=options,
                                        description="Explore Coil ",
                                        variable="explore",
                                        width='100%',
                                        rows=len(options)),
            self.component.title('Wire Diameter (mm)', name='wire_title'),
            self.component.range_slider(create_graph,
                                        _analyser,
                                        description="Range",
                                        variable="wire_d_range",
                                        range=(0.2, 1.2),
                                        step=resolution,
                                        max=2,
                                        readout_format='.{}f'.format(
                                            str(resolution).count("0"))),
            self.component.title('Coil Height (mm)', name='coil_title'),
            self.component.slider(create_graph,
                                  _analyser,
                                  description="Value",
                                  variable="coil_layer_height",
                                  increment=14)
        ]  # increment = start value

        _analyser.gui = self.component.pack(
            children=children,
            layout='".. .. .. .."' + ('"explore grid .. .."' * len(options)) +
            '''
                                            ".. .. .. .."
                                            "wire_title .. .. .."
                                            "wire_d_range wire_d_range wire_d_range wire_d_range"
                                            ".. .. .. .."
                                            "coil_title .. .. .."
                                            "coil_layer_height coil_layer_height coil_layer_height coil_layer_height"
                                            ".. .. .. .."
                                            ''',
            template_columns='30% 12.5% 12.5% 45%',
            width='650px')

        create_graph(None)  # trigger update

    def explore_actuator_force(self):
        _analyser = Analyser()
        if self.coil.get_layer_count():
            display(
                self.component.title(
                    'Coil Layers set to %i. Please unset this if you wish to explore.'
                    % self.coil.layer_count))
            b = self.component.button('Unset Coil Layers')

            def on_click_cb(b):
                self.coil.set_layer_count(None)
                self.explore_actuator_force()
                return

            display(b)
            b.on_click(on_click_cb)

            _analyser.explore_actuator_force(self.coil, self.tube, self._units)
            return

        def create_graph(val):
            clear_output(wait=True)
            output_notebook(hide_banner=True)

            if val is None:
                pass
            else:
                _analyser.data[val['owner'].layout.grid_area] = val['new']
            display(_analyser.gui)

            _analyser.explore_actuator_force(
                self.coil,
                self.tube,
                self._units,
                _start=_analyser.data["Range"][0],
                _end=_analyser.data["Range"][1] + 1,
                _increment=_analyser.data["Increment"])

        children = [
            self.component.title('Coil Layers'),
            self.component.range_slider(create_graph,
                                        _analyser,
                                        description="Range",
                                        variable="Range",
                                        range=(0, 10),
                                        max=100),
            self.component.slider(create_graph,
                                  _analyser,
                                  description="Increment",
                                  variable="Increment",
                                  increment=10,
                                  min=1)
        ]

        _analyser.gui = self.component.pack(children=children,
                                            layout='''
                            ".. .. .."
                            "title title title"
                            "Range Range Range"
                            "Increment Increment Increment"
                            ''')

        create_graph(None)  # trigger update

    def out(self, s):
        return self.component.title(s)
Beispiel #51
0
    def __call__(self, name, max_len, reuse=False):
        component_scope = self._variable_scope + name
        with tf.variable_scope(component_scope) as scope:
            if reuse:
                scope.reuse_variables()
            max_len = max_len + 2 if self._word_delimiters else max_len
            word_lens_source = tf.placeholder(dtype=tf.int32,
                                              shape=[None],
                                              name='source/word_lens')
            word_lens_target = tf.placeholder(dtype=tf.int32,
                                              shape=[None],
                                              name='source/word_target')

            chars_p_s = tf.placeholder(dtype=tf.int32,
                                       shape=[max_len, None],
                                       name='source/char_sequence%i' % max_len)
            chars_p_t = tf.placeholder(dtype=tf.int32,
                                       shape=[max_len, None],
                                       name='target/char_sequence%i' % max_len)

            chars_s = tf.nn.embedding_lookup(self.Wchar_s, chars_p_s)
            chars_s = tf.transpose(chars_s, [1, 0, 2])
            chars_t = tf.nn.embedding_lookup(self.Wchar_t, chars_p_t)
            chars_t = tf.transpose(chars_t, [1, 0, 2])
            chars = tf.concat([chars_s, chars_t], 2)

            enc_output_infer, enc_state_infer = tf.nn.dynamic_rnn(
                self.char_rnn_cell_infer,
                chars,
                dtype=tf.float32,
                sequence_length=tf.cast(word_lens_source, dtype=tf.int64),
                swap_memory=True,
                scope='encoder')
            attn_keys, attn_values, attn_score_fn, attn_construct_fn = attention_decoder_fn.prepare_attention(
                enc_output_infer, 'luong',
                self.char_rnn_cell_infer.output_size)
            dec_fn_inf = attention_decoder_fn.attention_decoder_fn_train(
                enc_state_infer, attn_keys, attn_values, attn_score_fn,
                attn_construct_fn)
            outputs_infer, _, _ = seq2seq.dynamic_rnn_decoder(
                self.char_rnn_cell_infer,
                dec_fn_inf,
                inputs=chars,
                sequence_length=word_lens_target,
                swap_memory=True,
                scope='decoder')

            scope.reuse_variables()
            enc_output, enc_state = tf.nn.dynamic_rnn(self.char_rnn_cell_train,
                                                      chars,
                                                      dtype=tf.float32,
                                                      sequence_length=tf.cast(
                                                          word_lens_source,
                                                          dtype=tf.int64),
                                                      swap_memory=True,
                                                      scope='encoder')
            attn_keys, attn_values, attn_score_fn, attn_construct_fn = attention_decoder_fn.prepare_attention(
                enc_output, 'luong', self.char_rnn_cell_infer.output_size)
            dec_fn = attention_decoder_fn.attention_decoder_fn_train(
                enc_state, attn_keys, attn_values, attn_score_fn,
                attn_construct_fn)
            outputs, _, _ = seq2seq.dynamic_rnn_decoder(
                self.char_rnn_cell_train,
                dec_fn,
                inputs=chars,
                sequence_length=word_lens_target,
                swap_memory=True,
                scope='decoder')

            output = _get_last_state_dyn(self.max_norm, word_lens_target,
                                         outputs)
            output_infer = _get_last_state_dyn(self.max_norm, word_lens_target,
                                               outputs_infer)
            inputs = [chars_p_s, word_lens_source, chars_p_t, word_lens_target]

            char_feature_extractor1 = CharLevelInputExtraction(
                self._char_vocab_source, max_len, component_scope + 'source/')
            char_feature_extractor2 = CharLevelInputExtraction(
                self._char_vocab_target, max_len, component_scope + 'target/')
            char_feature_extractor = CombineFeatureExtraction(
                char_feature_extractor1, char_feature_extractor2)
            return Component(inputs,
                             output,
                             output_infer=output_infer,
                             feature_extractor=char_feature_extractor,
                             name='c_rnn_joint')
Beispiel #52
0
 def __init__(self, services, config):
     #self.timer = pytau.profileTimer('XL_worker', "", str(os.getpid()))
     #pytau.start(self.timer)
     Component.__init__(self, services, config)
     print('Created %s' % (self.__class__))
Beispiel #53
0
 def __init__(self, **kwargs):
     self.command = "java"
     Component.__init__(self, **kwargs)
Beispiel #54
0
    def __call__(self, name, max_len, reuse=False):
        component_scope = self._variable_scope + name
        with tf.variable_scope(component_scope) as scope:
            if reuse:
                scope.reuse_variables()
            max_len = max_len + 2 if self._word_delimiters else max_len
            word_lens_source = tf.placeholder(dtype=tf.int32,
                                              shape=[None],
                                              name='source/word_lens')
            word_lens_target = tf.placeholder(dtype=tf.int32,
                                              shape=[None],
                                              name='source/word_target')

            chars_p_s = tf.placeholder(dtype=tf.int32,
                                       shape=[max_len, None],
                                       name='source/char_sequence%i' % max_len)
            chars_p_t = tf.placeholder(dtype=tf.int32,
                                       shape=[max_len, None],
                                       name='target/char_sequence%i' % max_len)

            chars_s = tf.nn.embedding_lookup(self.Wchar_source, chars_p_s)
            chars_t = tf.nn.embedding_lookup(self.Wchar_target, chars_p_t)

            chars = tf.concat(2, [chars_s, chars_t])
            chars = [
                tf.squeeze(j, [0])
                for j in tf.split(0,
                                  chars.get_shape()[0], chars)
            ]

            word_lens = tf.maximum(word_lens_source, word_lens_target)
            outputs_infer, _, _ = tf.contrib.static_bidirectional_rnn(
                self.rnn_cell_fw_train,
                self.rnn_cell_bw_infer,
                chars,
                dtype=tf.float32,
                sequence_length=tf.cast(word_lens, dtype=tf.int64))
            if self.rnn_cell_other_layers_infer:
                outputs_infer, _ = tf.contrib.static_rnn(
                    self.rnn_cell_other_layers_infer,
                    chars,
                    dtype=tf.float32,
                    sequence_length=tf.cast(word_lens, dtype=tf.int64))
            scope.reuse_variables()
            outputs, _, _ = tf.contrib.static_bidirectional_rnn(
                self.rnn_cell_fw_train,
                self.rnn_cell_fw_train,
                chars,
                dtype=tf.float32,
                sequence_length=tf.cast(word_lens, dtype=tf.int64))
            if self.rnn_cell_other_layers_train:
                outputs, _ = tf.contrib.static_rnn(
                    self.rnn_cell_other_layers_train,
                    chars,
                    dtype=tf.float32,
                    sequence_length=tf.cast(word_lens, dtype=tf.int64))
            output = _get_last_state(self.max_norm, word_lens_source, outputs)
            output_infer = _get_last_state(self.max_norm, word_lens_source,
                                           outputs_infer)
            inputs = [chars_p_s, word_lens_source, chars_p_t, word_lens_target]

            char_feature_extractor1 = CharLevelInputExtraction(
                self._char_vocab_source, max_len, component_scope + 'source/')
            char_feature_extractor2 = CharLevelInputExtraction(
                self._char_vocab_target, max_len, component_scope + 'target/')
            char_feature_extractor = CombineFeatureExtraction(
                char_feature_extractor1, char_feature_extractor2)
            return Component(inputs,
                             output,
                             output_infer=output_infer,
                             feature_extractor=char_feature_extractor,
                             name='c_bidir_rnn_joint')
Beispiel #55
0
 def __init__(self, **kwargs):
     self.name = "HPS DST Maker"
     self.command = "dst_maker"
     Component.__init__(self, **kwargs)
Beispiel #56
0
            4: cls.generate_topright_complement_45,
            5: cls.generate_topleft_complement_45
        }
        style_num = len(style_dict)
        s = style % style_num
        return style_dict[s]()

    # not a working component - base class for 45 degree
    # angle components

    def __init__(self, (w, h), coord=(0, 0), b=0, autooutline=True):

        self.m = float(h) / w
        self.b = b

        Component.__init__(self, (w, h), coord=coord, autooutline=autooutline)
        self.name = 'angle'

    def create(self):

        for y in range(self.h):
            for x in range(self.w):
                if self.on_angle(x, y):
                    self.add_pixel((x, y))

    def on_angle(self, x, y):
        if self.line(x) <= y:
            return True
        else:
            return False
Beispiel #57
0
# Copyright 2016-2021, Pulumi Corporation.  All rights reserved.

from component import Component

Component("component", children=5)
 def __init__(self, services, config):
     Component.__init__(self, services, config)
     self.vmec_worker = {}
Beispiel #59
0
    def load(self, filename, host="localhost", port=6499):
        print "Tuner.load " + str(port)
        basename = os.path.basename(str(filename))
        fileroot, ext = os.path.splitext(basename)

        if filename == "":
            error = QtGui.QErrorMessage(self)
            error.showMessage(
                "Error, you must specify an autopilot config file name")
            return
        elif not os.path.exists(filename):
            error = QtGui.QErrorMessage(self)
            error.showMessage(filename + ": does not exist")
            return

        try:
            props_json.load(filename, root)
        except:
            error = QtGui.QErrorMessage(self)
            error.showMessage(filename + ": parse error:\n" +
                              str(sys.exc_info()[1]))
            return

        self.filename = str(filename)
        self.fileroot, ext = os.path.splitext(self.filename)

        # L1 Route follow parameters
        self.L1 = L1Controller(changefunc=self.onChange, host=host, port=port)
        L1_node = getNode('/L1_controller', create=True)
        self.L1.parse(L1_node)
        self.tabs.addTab(self.L1.get_widget(), "L1")

        # TECS parameters
        self.TECS = TECS(changefunc=self.onChange, host=host, port=port)
        TECS_node = getNode('/TECS', create=True)
        self.TECS.parse(TECS_node)
        self.tabs.addTab(self.TECS.get_widget(), "TECS")

        # PID controller parameters
        print root.getChild('component')
        len = root.getLen('component')
        #comp_node = getNode('/component', create=True)
        for i in range(len):
            node_name = 'component[%d]' % i
            print node_name
            node = root.getChild(node_name)
            comp_type = node.getString('module')
            if comp_type == 'pid_component':
                pid = Component(index=i,
                                changefunc=self.onChange,
                                host=host,
                                port=port,
                                type="pid")
            elif comp_type == 'pid_vel_component':
                pid = Component(index=i,
                                changefunc=self.onChange,
                                host=host,
                                port=port,
                                type="vel")
            elif comp_type == 'summer':
                pid = Component(index=i,
                                changefunc=self.onChange,
                                host=host,
                                port=port,
                                type="sum")
            else:
                print "unknown ..."
                next
            pid.parse(node)
            self.components.append(pid)
            self.tabs.addTab(pid.get_widget(), pid.get_name())
Beispiel #60
0
 def __init__(self, **kwargs):
     self.name = "Make ROOT tree"
     Component.__init__(self, **kwargs)