示例#1
0
 def __init__(self):
     FreeCAD.Console.PrintMessage( 'MyDockWidget init begin\n')
     self.taskmode = Base.getParam("UiMode")
     self.paramcolor = Base.getParam("color")>>8
     self.color = QtGui.QColor(self.paramcolor)
     self.facecolor = QtGui.QColor(204, 204, 204)
     self.linewidth = Base.getParam("linewidth")
     self.fontsize = Base.getParam("textheight")
     self.paramconstr = Base.getParam("constructioncolor")>>8
     self.constrMode = False
     self.continueMode = False
     self.state = None
     self.textbuffer = []
     self.crossedViews = []
     self.tray = None
     self.sourceCmd = None
     self.dockWidget = QtGui.QDockWidget()
     self.mw = getMainWindow()
     self.mw.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.dockWidget)
     self.centralWidget = QtGui.QWidget()
     #self.label = QtGui.QLabel(self.dockWidget)
     #self.label.setText("abc")
     self.dockWidget.setWidget(self.centralWidget)
     self.dockWidget.setVisible(False)
     self.dockWidget.toggleViewAction().setVisible(False)
     self.layout = QtGui.QHBoxLayout(self.centralWidget)
     self.layout.setObjectName("layout")
     self.setupToolBar()
     self.setupTray()
     self.setupStyle()
     FreeCAD.Console.PrintMessage( 'MyDockWidget init done\n')
示例#2
0
 def getDefaultColor(self, type, rgb=False):
     "gets color from the preferences or toolbar"
     if type == "snap":
         color = Base.getParam("snapcolor")
         r = ((color >> 24) & 0xFF) / 255
         g = ((color >> 16) & 0xFF) / 255
         b = ((color >> 8) & 0xFF) / 255
     elif type == "ui":
         r = float(self.color.red() / 255.0)
         g = float(self.color.green() / 255.0)
         b = float(self.color.blue() / 255.0)
     elif type == "face":
         r = float(self.facecolor.red() / 255.0)
         g = float(self.facecolor.green() / 255.0)
         b = float(self.facecolor.blue() / 255.0)
     elif type == "constr":
         color = QtGui.QColor(Base.getParam("constructioncolor") >> 8)
         r = color.red() / 255.0
         g = color.green() / 255.0
         b = color.blue() / 255.0
     else: print "draft: error: couldn't get a color for ", type, " type."
     if rgb:
         return("rgb(" + str(int(r * 255)) + "," + str(int(g * 255)) + "," + str(int(b * 255)) + ")")
     else:
         return (r, g, b)
示例#3
0
 def Activated(self, name="None"):
     FreeCAD.Console.PrintMessage( 'Creator activing\n')
     if FreeCAD.activeDDACommand:
         FreeCAD.activeDDACommand.finish()
     self.doc = FreeCAD.ActiveDocument
     self.view = FreeCADGui.ActiveDocument.ActiveView
     
     import Base
     Base.changeStage('DC')
     
     # activate  DC Panel
     global __currentDDAPanel__
     if __currentDDAPanel__ != None :
         __currentDDAPanel__.hide()
     __currentDDAPanel__ = self.ui
     __currentDDAPanel__.show()
     
     self.featureName = name
     
     if not self.doc:
         FreeCAD.Console.PrintMessage( Base.translate('DDA_DC','FreeCAD.ActiveDocument get failed\n'))
         self.finish()
     else:
         FreeCAD.activeDDACommand = self  # FreeCAD.activeDDACommand 在不同的时间会接收不同的命令 
         self.ui.show()
示例#4
0
    def Activated(self, name="None"):
        FreeCAD.Console.PrintMessage( 'Creator activing\n')
        if FreeCAD.activeDDACommand:
            FreeCAD.activeDDACommand.finish()
        self.doc = FreeCAD.ActiveDocument
        self.view = FreeCADGui.ActiveDocument.ActiveView
        if not self.doc:
            FreeCAD.Console.PrintMessage( 'FreeCAD.ActiveDocument get failed\n')
            self.finish()
        else:
            FreeCAD.activeDDACommand = self  # FreeCAD.activeDDACommand 在不同的时间会接收不同的命令 
            if not self.ui.isVisible():
                self.ui.show()
#                import DDAToolbars
#                DDAToolbars.lineToolbar.on()
            
        import Base
        Base.changeStage('PreDL')
        Base.changeStep4Stage('FirstStep')
        self.refreshButtons()
            
        # activate  DL Panel
        global __currentDDAPanel__
        print __currentDDAPanel__
        if __currentDDAPanel__ != None :
            __currentDDAPanel__.hide()
        __currentDDAPanel__ = self.ui
        __currentDDAPanel__.show()
        print 'panel shown  ' , __currentDDAPanel__
	def core(self, repeats=1, w=None, data=None):
					
		self.timestamps['core'] = prectime()
		sleep_msec = 1.0
		self.timestamps['before'] = []
		self.timestamps['after'] = []
		preplay_done = False

		subs = [slice(None),slice(None)]
		nsamp = Base.samples(data)
		start = 0
		while repeats != 0:
			start %= nsamp
			while start < nsamp:
				while True:
					if not self.keepgoing or self.timedout(): self.keepgoing=False; break
					towrite = self.stream.get_write_available()
					nleft = (float(nsamp) - float(start)) / float(self.speed)
					if towrite >= nleft: break
					if towrite >= self.buffersize: break
					sleep(sleep_msec/1000.0)
				if not self.keepgoing: break
				
				speed = float(self.speed)
				if speed == 1.0:
					start = int(round(start))
					stop = start + towrite
					if repeats == 1: stop = min(nsamp, stop)
					subs[across_samples] = slice(start,stop)
					dd = data[subs]
				else:
					start = float(start)
					stop = start + float(speed) * float(towrite)
					if repeats == 1: stop = min(float(nsamp), stop)
					xi = numpy.linspace(start=start, stop=stop, endpoint=False, num=towrite)
					xi %= float(nsamp)
					dd = Base.interpsamples(data, xi)

				vols = float(self.vol) * Base.panhelper(self.pan, nchan=dd, norm=self.norm)
				dd = dd * vols  #   *= won't work for broadcasting here

				raw = w.dat2str(data=dd)
				if not preplay_done and self.preplay != None and self.preplay['func'] != None:
					self.preplay['func'](*self.preplay['pargs'], **self.preplay['kwargs'])
					preplay_done = True
				if len(self.timestamps['before']) < 100: self.timestamps['before'].append(prectime())	
				self.stream.write(raw)
				if len(self.timestamps['after']) < 100:  self.timestamps['after'].append(prectime())
				start = stop
			if not self.keepgoing: break
			repeats -= 1

		if self.postplay != None and self.postplay['func'] != None:
			self.postplay['func'](*self.postplay['pargs'], **self.postplay['kwargs'])
		self.__playing = False
		towrite = self.stream.get_write_available()	
		bytes_per_frame = self.interface.get_sample_size(self.format) * self.stream._channels
		if towrite > 0: self.stream.write('\0' * towrite * bytes_per_frame)
		while self.stream.get_write_available() < self.stream._frames_per_buffer: sleep(0.001)
		sleep(float(self.stream._frames_per_buffer) / float(self.stream._rate) + self.stream.get_output_latency())
	def play(self, repeats=1, bg=True, w=None, data=None, timeout=None, vol=None, pan=None):
		"""
		plays a wav object w, which defaults to the currently loaded instance p.wav

		Set repeats=-1 to loop forever.  Set bg=False to play synchronously.
		
		p.play(w=w2) sets p.wav = w2 and then plays it (which may involve closing and
		re-opening the stream if the bit depth, sampling rate or number of channels
		differs between w2 and the old p.wav).

		p.play(data=d) uses the raw data in numpy.array d instead of the default w.y,
		playing it at the sampling frequency and bit depth dictated by w.
		"""###
		if self.playing: return
		self.timestamps['play'] = prectime()
		self.open(w)
		w = self.wav
		if w == None: return
		if data == None: data = w.y
		if Base.channels(data) != Base.channels(w): raise ValueError, 'data array and wav object have mismatched numbers of channels'
		self.timeout=timeout
		self.kwargs = {'w':w, 'data':data, 'repeats':repeats}
		if vol != None: self.vol = vol
		if pan != None: self.pan = pan
		self.__playing = True
		self.go(bg=bg)
示例#7
0
def checkFile(file):
    import os
    if not os.path.exists(file):
        import Base
        Base.showErrorMessageBox('FileError', 'file \"%s\" not found'%file)
        return False
    return True
示例#8
0
    def addToTab(self):
        '''
        add selected joints into the tabwidget.
        '''
        
        if not self.ui.listWidget.currentRow() >=0 \
            and self.ui.listWidget.currentRow()< self.ui.listWidget.size():
            import Base
            Base.showErrorMessageBox('Wrong Index', \
                    'Please select a joint first.')
            return

        self.ui.pushButton.pressed.disconnect(self.addToTab)
        text = str(self.ui.listWidget.currentItem().text()).strip()
        
        dialog = chooseJointType()
        dialog.exec_()
        
        if dialog.accepted:
        
            tabName = dialog.slection

            for i in range(7):
                if self.enumList[i] == tabName:
                    self.ui.tabWidget.setCurrentIndex(i)
                    flag = self.checkElements(text, i)
                    if flag == 1:
                        break
                    tempItem = PySide.QtGui.QListWidgetItem(text)
                    self.ui.tabWidget.currentWidget().children()[0].addItem(tempItem)
                    item = self.ui.listWidget.takeItem(self.ui.listWidget.currentRow()) 
                    item = None 

        self.ui.pushButton.pressed.connect(self.addToTab)
示例#9
0
 def __parseParaSchema(self):
     '''
     parse parameters from DF parameters file
     :param infile:
     '''
     
     for i in range(7):
         line = self.__file.getNextLine()  
         t =self.parseFloatNum(line)
         if t==None: return False
     
         if   i==0:     self.paras.ifDynamic = float(t)
         elif i==1:     self.paras.stepsNum = int(t)
         elif i==2:     self.paras.blockMatsNum = int(t)
         elif i==3:     self.paras.jointMatsNum = int(t)
         elif i==4:     self.paras.ratio = t
         elif i==5:     self.paras.OneSteptimeLimit = t
         else:          self.paras.springStiffness = int(t)
     
     from DDADatabase import df_inputDatabase as dfDB
     if self.paras.blockMatsNum != len(dfDB.blockMatCollections) \
         or self.paras.jointMatsNum != len(dfDB.jointMatCollections):
         import Base
         Base.showErrorMessageBox("ParametersError", "Numbers of block materials or joint materials are not equal to that of data.df")
         return False
     
     print 'DF Para : IfDynamic: %d  steps: %d  blockMats: %d  JointMats: %d  Ratio: %f  timeInterval: %d  stiffness: %d'\
         %(self.paras.ifDynamic, self.paras.stepsNum , self.paras.blockMatsNum , self.paras.jointMatsNum \
           , self.paras.ratio, self.paras.OneSteptimeLimit, self.paras.springStiffness)
         
     print 'Df parameters schema done'
     return True
示例#10
0
 def Activated(self):
     from Base import __currentProjectPath__
     Base.changeStage('PreDL')
     FreeCADGui.runCommand('DDA_LoadDLInputData')
     graph = DLInputGraph()
     graph.showGraph4File()
     FreeCADGui.runCommand('DDA_ViewFitAll')
示例#11
0
 def write2DLFile(self):
     print 'storing DL data'
     import Base
     filename = None
     try:
         filename = Base.__currentProjectPath__ + '/data.dl'
         file = open( filename , 'wb' , True)  #  使用缓存,flush时再写入硬盘
         print 'begin writing data to file %s'%filename
     except:
         FreeCAD.Console.PrintError(' %s open failed\n'%filename)
         return
         
     Base.setGraphRevised()  #  graph of active document has
         
     self.writePandect( file )
     self.writeJointSetsAndSlope(file)
     file.flush()
     self.writeBoundaryNodes(file)
     file.flush()        
     self.writeTunnels(file)
     self.writeLines( file )
     file.flush()
     self.writePoints( file )
         
     file.close()
     
     import Base
     
     wholePath = Base.__workbenchPath__ + '\\Ff.c'
     file = open( wholePath , 'wb' )            #保存文件名
     file.write(filename)
     file.close()
     print 'file save done'
示例#12
0
    def action(self, arg):
        "scene event handler"
        if arg["Type"] == "SoKeyboardEvent":
            if arg["CtrlDown"] and arg["Key"] == 'z':
                if arg['State'] == 'DOWN' and not self.zDown:
                    print 'ctrl z'
                    import Base
                    database = Base.getDatabaser4CurrentStage()
                    self.RedrawObject(database.undo())
            if arg["CtrlDown"] and arg["Key"] == 'y':
                if arg['State'] == 'DOWN' and not self.yDown:
                    print 'ctrl y'
                    import Base
                    database = Base.getDatabaser4CurrentStage()
                    self.RedrawObject(database.redo())
            if arg["Key"] == 'DELETE':
                if arg['State'] == 'UP':
                    print 'Delete pressed'
#                    self.handleDelete()

            if arg["Key"] == 'z':
                if arg['State'] == 'DOWN': self.zDown = True
                elif arg['State'] == 'UP': self.zDown = False
                
            if arg["Key"] == 'y':
                if arg['State'] == 'DOWN': self.yDown = True
                elif arg['State'] == 'UP': self.yDown = False
示例#13
0
    def getPoints(self):
        view=FreeCADGui.ActiveDocument.ActiveView
        objs = view.getObjectsInfo(view.getCursorPos())
        obj = None
        for o in objs:
            if o['Object']=='ShapeModifier' or o['Object']=='ShapeMover':
                obj = o
                break
        self.__selectedAssistantNodeName = obj['Object']
        assert obj
        name , idx = Base.getRealTypeAndIndex(obj['Object'])
        print 'jointline modifier triggered by %s -> %d'%(name,idx)
        pName , pIdx = Base.getRealTypeAndIndex(obj['Component'])
        print 'jointline modifier triggered by subelement %s -> %d'%(pName,pIdx)
        object = FreeCAD.getDocument(self.docName).getObject(self.objName)
        subName , subIdx = Base.getRealTypeAndIndex(self.subElement)
        print 'jointline modifier selected sub line %s -> %d'%(subName,subIdx)

        from DDADatabase import dc_inputDatabase
        from loadDataTools import DDALine
        tmpLine = dc_inputDatabase.jointLines[subIdx-1]

        p1 = None 
        p2 = None
        if pIdx==2:
            p1 = FreeCAD.Vector(tmpLine.startPoint)
            p2 = FreeCAD.Vector(tmpLine.endPoint)
        else:  
            # pIdx==1 maybe ShapeMover or ShapeModifier, 
            # but ShapeMover doesn't care about order of p1 and p2
            p1 = FreeCAD.Vector(tmpLine.endPoint)
            p2 = FreeCAD.Vector(tmpLine.startPoint)
        return p1 , p2
示例#14
0
    def finish(self):
        if self.center:
            import Base
            view=FreeCADGui.ActiveDocument.ActiveView
            obj = view.getObjectInfo(view.getCursorPos())
            objName , objIdx = Base.getRealTypeAndIndex(obj['Object'])
            assert objName == 'Block'
            subName , subIdx = Base.getRealTypeAndIndex(obj['Component'])
            from DDADatabase import df_inputDatabase
            df_inputDatabase.blocks[subIdx-1].materialNo=11
            df_inputDatabase.blocks[subIdx-1].holePointsCount+=1
#            Base.__blocksMaterials__[subIdx-1] = 11 # white color, same to the background
            FreeCAD.ActiveDocument.getObject('Block').ViewObject.RedrawTrigger=1 # trigger colors changes
            print 'Block with hole point hided'
            
            
            ###############################
            # temporary code , for speech
            
            fps = df_inputDatabase.fixedPoints
            if len(fps)>0:
                if subIdx-1 < fps[0].blockNo:
                    for p in fps:
                        p.blockNo -=1
            
            # tepmorary code ends
            ###############################
            
        super(HolePoint,self).finish()
示例#15
0
    def checkDataValid(self,text):
        if not self.xValue.hasFocus() and not self.yValue.hasFocus():
            return
        
        tmpError = False
        try:
            tmp = float(self.xValue.text())
        except ValueError:
            self.xValue.setStyleSheet(__errorStyleSheet__)
            tmpError = True
        else:
            self.xValue.setStyleSheet(__normalStyleSheet__)

        try:
            tmp = float(self.yValue.text())
        except ValueError:
            self.yValue.setStyleSheet(__errorStyleSheet__)
            tmpError = True
        else:
            self.yValue.setStyleSheet(__normalStyleSheet__)
            
        if not tmpError:
            import Base
            Base.showErrorMessageBox('ValueError', 'please input float number')
            return
        else:
            self.validatePoint()
	def __init__(self, seconds=None, nchan=None, fs=None, bits=None, w=None, callback=None, packetRateHz=100):
		Background.ongoing.__init__(self)
		if isinstance(w,player): w = p.wav
		if w == None:
			if not nchan: nchan = 2
			if not fs: fs = 44100
			if not bits: bits = 16
			w = Base.wav(fs=fs,bits=bits,nchan=nchan)
			if seconds: w.y = Base.silence(round(seconds*w.fs), nchan)
		else:
			if not seconds: seconds = w.duration()
			if not nchan: nchan = w.channels()
			if not fs: fs = int(w.fs)
			if not bits: bits = w.bits
			w.fs = fs
			w.bits = bits # nbytes should be updated automatically	
		
		self.wav = w
		self.seconds = seconds
		self.nchan = nchan
		self.packetRateHz = packetRateHz
		
		if callback != None:
			self.handle_data = callback
			
		self.samples_recorded = 0
		self.packets_recorded = 0
示例#17
0
 def Activated(self):
     self.parse()
     import Base
     Base.changeStep4Stage('SpecialStep')
     
     import Base
     database = Base.getDatabaser4CurrentStage()
     database.clearRedoUndoList()
示例#18
0
文件: InitGui.py 项目: sgnannan/DDA
    def Deactivated(self):
#        if DDAGui.__currentPanel__ != None :
#            DDAGui.__currentPanel__.hide()
#        FreeCADGui.DDADockWidget.Deactivated()
        import Base
        Base.enableSeletionObserver(False)
        import DDADatabase
        DDADatabase.enableOperationObverser(False)
示例#19
0
 def handleDelete(self):
     import Base
     sels=FreeCADGui.Selection.getSelectionEx()
     sel = sels[0]
     objName = sel.ObjectName
     assert len(sel.SubElementNames)==1
     type , idx = Base.getRealTypeAndIndex(sel.SubElementNames[0])
     database =  Base.getDatabaser4CurrentStage()
     database.remove(objName, [idx], args=None, ifRecord=True)
示例#20
0
文件: InitGui.py 项目: sgnannan/DDA
 def setDefaultWorkbench(self):
     import FreeCAD,Base
     def setDDAasDefault():
         p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/General")
         bench = ''
         p.GetString('AutoloadModule' , bench)
         if bench !='DDA':
             p.SetString('AutoloadModule' , 'DDA')
             
     Base.delaycommand(setDDAasDefault)
示例#21
0
文件: DDAShapes.py 项目: sgnannan/DDA
    def Activated(self):
        print 'JointLineModifier Activating'
        if self.lineModifier:
            del self.lineModifier
        self.lineModifier = None
        self.getPointsAndCreateNodes()
#        self.__addCallback()
#        return
        import Base
        Base.delaycommand(self.__addCallback)
示例#22
0
文件: InitGui.py 项目: sgnannan/DDA
 def setBackgroundColor(self):
     import FreeCAD
     def setWhiteBackground():
         p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View")
         white = 4294967295
         p.SetUnsigned('BackgroundColor',white)
         p.SetBool('Simple',1)
         p.SetBool('Gradient',0)
         
     import Base
     Base.delaycommand(setWhiteBackground)
示例#23
0
    def Activated(self):

        from interfaceTools import dxf2DDA, importDXF
        dxfDict = dxf2DDA()
        if dxfDict:
#             print "dxfDict:", dxfDict
            
            Base.changeStage('DL')
            dialog = importDXF()
            dialog.realImport(dxfDict)
            
            dialog.exec_()
def validUrl(url):
    x = int(0)
    while x < int(11):
        x += 1
        try:
            r = doHeadRequest(url)
            r.raise_for_status()
            Base.info('%s might be a valid url' % url)
            return True
        except Exception:
            Base.warning('encountered a minor error going to retry')
    return False
示例#25
0
文件: InitGui.py 项目: sgnannan/DDA
    def loadSettings(self):
        from PySide import QtCore , QtGui
        import Base , FreeCAD
        settings = QtCore.QSettings('ECS' , 'easyDDA')
#        Base.__currentProjectPath__ = str(settings.value('ProjectPath' , None).toString())
        path = str(settings.value('ProjectPath' , None))
        Base.setCurrentProjectPath(path)

        FreeCAD.Console.PrintMessage ('current project path**** : %s'% Base.__currentProjectPath__)
        
        import DDAPanel
        QtCore.QTimer.singleShot(0, DDAPanel.hideDLAndDCPanel)
示例#26
0
    def finish(self):
        print 'LineModifier finish'
        if self.linetrack:
            self.linetrack.finalize()
            self.linetrack = None
            super(LineModifier,self).finish()
#        self.owner.finish()
            import Base
            Base.removeShapeModifier()
            Base.removeShapeMover()
        self.p1 = None
        self.p2 = None
示例#27
0
 def getNextLine(self):
     line = self.__file.readline()
     while len(line)!=0:
         line = line.strip()
         if len(line)==0: # blank line with '\n'
             line = self.__file.readline()
         else:
             break   # this line is not blank
     if len(line)==0:  # file already ends
         import Base
         Base.showErrorMessageBox('file error' , 'unvalid data')
         raise
     return line
示例#28
0
 def parse(self , path=None):
     self.refreshBlocksData()
     import Base
     if not path : path = Base.__currentProjectPath__+'/data.df'
     if not checkFileExists(path):
         return False
     
     file = open(path , "rb")
     if not self.__parseDataSchema(file) or not self.__parseBlocks(file) or \
         not self.__parseBlockVertices(file) or  not self.__parsePoints(file):
         Base.showErrorMessageBox("DataError", 'Data input unvalid')
         return False
     
     return True
示例#29
0
def syllableMatches(syl, form):
	""" eg. syllableMatches('rte', '[V]VCe')
	capital 'V' or 'C' match vowels and consonants respectively
	letters in []'s shows optional letters. checks from the end of the word"""
	# FIXME this is not necessarily done on a syllable by syllable basis. sometimes it
	# can overlap boundaries
	sylMatches = False

	# better handling of 'ng' and other double letters
	syl = Base.explode(syl)
	form = Base.explode(form)

	syl = syl[::-1]
	form = form[::-1]

	#FIXME need to write test about if form longer than syl has correct behavior
	#FIXME optional '[]' letters should not increment i
	inBrackets = False
	j = 0

	if len(syl) > 0 and len(syl) >= len(form):
		for i in range(len(form)):
			if i <= j:
				if inBrackets:
					# FIXME not sure if there is really anything to do but ignore
					if form[i] == '[':
						inBrackets = False
						j += 1
				else:
					if form[i] == 'V' and Alphabet.isVowel(syl[j]):
						sylMatches = True
						j += 1
					elif form[i] == 'C' and Alphabet.isConsonant(syl[j]):
						sylMatches = True
						j += 1
					elif form[i] == syl[j]:
						#FIXME this may have some false positives
						sylMatches = True
						j += 1
					elif form[i] == ']':
						# we are reversed, so close brackets = open brackets
						inBrackets = True
					else:
						sylMatches = False
						break
			else:
				break
	return sylMatches
示例#30
0
 def onSkip(self, button, params):
     global starting_new_game, plist_monologue
     PreIntroRoom.onSkip(self, button, params)
     #DoStartNewGame(self, params)
     starting_new_game = True
     VS.musicPlayList(plist_monologue)
     Base.SetCurRoom(intro_guiroom.getIndex())
示例#31
0
    def node_up(self, node):
        if self.is_empty():
            raise Base.Empty("Top is empty")
        e = self._delete_node(node._prev)
        self._insert_between(e, node, node._next)

        return node
示例#32
0
 def __init__(self, *pats):
     l, p = [], []
     for pat in pats:
         p.append(Base.asStream(pat))
         l.append(len(p[-1]))
     length = op.LCM(*l)
     self.data = zip(*[p[i].stretch(length) for i in range(len(p))])
示例#33
0
	def open(self, w=None, dev=None):
		if isinstance(w,str): w = Base.wav(w)
		if w == None: w = self.wav
		self.wav = w
		if self.interface == None:
			self.interface = grab_interface(self.verbose)
		if not self.ready(w): self.openstream(w, dev=dev)
示例#34
0
    def Activated(self):
        super(ShapeModifierTrigger , self).Activated()
        import Base
        if Base.__currentStage__ != 'DL' : # not 'DL' stage
            print Base.__currentStage__
            self.finish() 
            return

        sels=FreeCADGui.Selection.getSelectionEx()
        if len(sels)!=1  : # select more than 2 objects
            return
        s = sels[0]
        count = 0
        for subName in sels[0].SubElementNames:
            if 'Edge' in subName :  # FreeCAD may get error object selected, this code confirm the object is valid
                count+=1
        if count>1 :
            return 
        
        if s.ObjectName=='ShapeMover' or s.ObjectName=='ShapeModifier':
            return
        
        import Base
        obj = sels[0].Object
        name , idx = Base.getRealTypeAndIndex(obj.Label)    
        print 'trigger modifier for %s --> %d'%(name , idx)

        self.docName = s.DocumentName
        self.objName = s.ObjectName
        self.subElement = s.SubElementNames[0]
        Base.__shapeBeModifying__ = [self.docName , self.objName , self.subElement]
        print 'prepare done in ShapeModifierTrigger'
        
        if name=='JointLine':
            FreeCADGui.runCommand('DDA_JointLineModifier')
示例#35
0
 def test_base(self):
     temp = Base.Base()
     self.assertEqual(type(temp), Base.Base, 'Base doesn`t work correctly')
     self.assertTrue(temp.hit_points == 10, 'Base doesn`t work correctly')
     self.assertTrue(temp.place == [0, 0], 'Base doesn`t work correctly')
     self.assertFalse(temp.destroyed, 'Base doesn`t work correctly')
     self.assertTrue(temp.type == 'Base', 'Base doesn`t work correctly')
示例#36
0
    def __init__(self, field_size, width, height):
        self.base = Base.Base()

        self.name = ''
        self.fraction_name = ''

        self.units = Units()

        self.unit_list = []
        self.name_units = []
        self.button_list = []
        self.name_units_text = []
        self.highlighted_cells_list = []
        self.player_list = []
        self.units_behave_list = []
        self.field_info = [[None for i in range(field_size)]
                           for j in range(field_size)]

        self.field_size = field_size
        self.next_turn = False
        self.sound = False
        self.money = 0

        self.width = width
        self.height = height

        self.unit_info_x_coef = 0.6
        self.unit_info_y_coef = 0.2

        self.unit_info = Text.Text('', self.width * self.unit_info_x_coef,
                                   self.height * self.unit_info_y_coef)
示例#37
0
文件: fans.py 项目: oscsalga/devnet
def fan(listaIP):
    listaIP2 = []
    listaIP2.append(listaIP)
    for ip in listaIP2:
        print(ip)
        for i in range(2):
            try:
                esperar = random.randint(1, 2)
                #print("ESPERANDO: " + str(esperar))
                time.sleep(esperar)
                conexion = db.Drops(ip)
            except:
                continue  # retrying
            else:
                break
        else:
            continue

        hostname = conexion.findHostname()
        print(hostname)
        fans = conexion.ejecutarComando(comando)
        print(fans.split())

        if str("0") in fans.split():
            print("ZERO ON A FAN")
            conexion.correo(hostname, ['*****@*****.**'], fans)
        else:
            print("no hay cero")
            #conexion.correo(hostname, ['*****@*****.**'], fans)
        conexion.desconectar()
示例#38
0
    def test_edit_file_content(self):

        file_name = "ipsum.txt"
        new_content = "updated the contents"
        update_content = {"files": {file_name: {"content": new_content}}}
        gist_obj = base.get_gist(ID)
        files = gist_obj['files']
        content_updated = False
        for f in files:
            f_name = files[f]['filename']
            if f_name == file_name:
                base.update_gist(ID, update_content)
                content_updated = True
                break

        assert content_updated, "File not found. Content not updated"
示例#39
0
    def showStress(self):
        assert len(self.__times) == len(self.__stresses)
        texts = ['StressX', 'StressY', 'StressXY']
        colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 1.0, 0.0, 1.0),
                  (0.0, 0.0, 1.0, 1.0)]
        tmp1 = [p[0] for p in self.__stresses]
        tmp2 = [p[1] for p in self.__stresses]
        tmp3 = [p[2] for p in self.__stresses]

        # add Coordiante axis
        xMin, xMax, yMin, yMax = getMinAndMax([self.__times],
                                              [tmp1, tmp2, tmp3])
        self.__stressRange = [yMin, yMax]
        self.__timeRange = [xMin, xMax]
        times = scaleVertices2Axis(self.__times, xMin, xMax, __graphWidth__)
        self.addAxisForDoc('Stress', xMin, xMax, yMin, yMax,
                           'Stress graph for block %d' % self.__blockNumber,
                           texts, colors)

        tmp1 = scaleVertices2Axis(tmp1, yMin, yMax, __graphHeight__)
        pts1 = [(k, v, 0) for k, v in zip(times, tmp1)]
        tmp2 = scaleVertices2Axis(tmp2, yMin, yMax, __graphHeight__)
        pts2 = [(k, v, 0) for k, v in zip(times, tmp2)]
        tmp3 = scaleVertices2Axis(tmp3, yMin, yMax, __graphHeight__)
        pts3 = [(k, v, 0) for k, v in zip(times, tmp3)]

        self.showPolyLine('Stress', texts[0], pts1, colors[0])
        self.showPolyLine('Stress', texts[1], pts2, colors[1])
        self.showPolyLine('Stress', texts[2], pts3, colors[2])

        import Base
        Base.ViewFitScene('Stress')
示例#40
0
    def loadDataCampaign(self, campaign):

        self.dataCampaign = campaign
        configuration = Configuration.ConfigurationReader(campaign)
        for run in self.dataCampaign.runs:
            print "Looking at run " + str(run.runNumber)
            settings = configuration.loadSettings(run.runNumber)
            vth = settings.getVTh()
            for discModRun in self.discModuleRuns:
                discModule = DiscriminatorModule()
                discModule.setVThreshold(vth)
                discModRun.modules.append(discModule)
                print "Added a disc module with vth = " + str(vth)
        i = 0
        for run in self.dataCampaign.runs:
            run.setup()
            settings = configuration.loadSettings(run.runNumber)
            vth = settings.getVTh()
            readeri = Base.DATEReader(self.dataCampaign.fileNames[i])
            print "Starting to analyse file:"
            print self.dataCampaign.fileNames[i]
            readeri.readBinary(run)
            for channel in run.channelRuns:
                discModRun = self.findDiscriminatorModuleRun(
                    channel.board, channel.module, channel.trip)
                discMod = discModRun.getDiscriminatorModule(vth)
                discMod.addChannelFiredRatio(channel.getDiscriminatorRatio())
                if (channel.getDiscriminatorRatio() != 0.0):
                    print "ratio = " + str(channel.getDiscriminatorRatio())
            i = i + 1
            run.clear()
示例#41
0
    def showAnalysis(self):
        import Base, Graph
        # graph must be new, to clear former polylines
        if self.__graph:
            self.__graph.clearLines()
            self.clearAxises()
        else:
            self.__graph = Graph.AnalysisGraph()

        print '111  ', Base.getCurrentTime()
        if self.__ifAnalysesDisplacement: self.showDisplacement()
        print '222  ', Base.getCurrentTime()
        if self.__ifAnalysesMPs: self.showMPDists()
        print '333  ', Base.getCurrentTime()
        if self.__ifAnalysesStress: self.showStress()
        print '444  ', Base.getCurrentTime()
示例#42
0
def apostrophePurpose(word):
	"""is the apostrophe being used for gemination, separate 'n' and 'g', etc."""
	exp = Base.explode(word)
	purpose = -1
	for i in range(len(exp)):
		if i > 0 and exp[i] == '\'':
			if i < len(exp) - 1:
				if Alphabet.isVowel(exp[i - 1]):
					if Alphabet.isVowel(exp[i + 1]):
						purpose = APOS_PREVENT_GEMMINATION
						break
					elif exp[i + 1] == 'r':
						purpose = APOS_DISRUPT_STRESS
						break
				else:
					if Alphabet.isVowel(exp[i + 1]):
						purpose = APOS_GEMINATION_MARKER
						break
					elif exp[i - 1] == 'n' and exp[i + 1] == 'g':
						purpose = APOS_NG_SEPARATOR
						break
					else:
						# FIXME need to test if a catch-all is appropriate. technically the only
						# other valid use of a \' is whenever auto-devoicing occurs. (stop + nasal || fric)
						#FIXME need to do research on autodevoicing to make sure this ^^ is acurate
						# FIXME will need to write a test to make sure cases without auto devoicing are not matched
						purpose = APOS_PREVENT_DEVOICING
						break
			else:
				purpose = APOS_SHORT_WORD
	return purpose
示例#43
0
def GNormPlus_parser(outputfile):
    gnor = normalization.gene_normor('../data/hgnc_complete_set.txt')
    with open(outputfile, 'r') as f:
        gene_results = [i.split('\n') for i in f.read().split('\n\n') if i]
    for article_result in gene_results:
        text = ''
        pmid = False
        mutation_entry_ls = []
        for record in article_result:
            is_text = re.match(r'(\d+)\|a\|(.+)$', record)
            if is_text:
                # id, string
                text = is_text.group(2)
                pmid = int(is_text.group(1))
            else:
                pmid, start, end, string, _type, ids = record.split('\t')
                if not re.match('gene|protein', _type, re.IGNORECASE):
                    continue
                pmid = int(pmid)
                start = int(start)
                end = int(end)
                for did in ids.split(';'):
                    '''one tring map to mutil-gene'''
                    try:
                        norm = gnor.norm(did)
                    except KeyError as e:
                        print('gene {0} skip: no gene in hgnc'.format(string))
                        continue
                    yield (pmid,
                           Base.BioEntry(start, end, _type, string, id, norm))
示例#44
0
def update_base_list():
    if -337 < base_list[0].x < -334:
        new_base = Base.Base()
        base_list.append(new_base)

    if base_list[0].x < -336:
        base_list.pop(0)
def Najlepsza_zdawalnosc(filtr, rok):
    if filtr==2:
        print('Wynik podawany dla kobiet')
    elif filtr==3:
        print('Wynik podawany dla mężczyzn')
    wojewodztwa=[]
    zdawalnosc_we_wszystkich_wojew=[]
    only_rate=[]
    wynik=[]
    for i in range(len(dane)):
        wojewodztwa.append(dane[i][0])
    wojewodztwa=list(set(wojewodztwa))
    wojewodztwa.remove('Polska') 
    wojewodztwa.remove('Terytorium')
    
    for wojew in wojewodztwa:
        zdawalnosc_we_wszystkich_wojew.append(Base.Zdawalnosc(filtr,wojew,rok))
    for x in range (len(zdawalnosc_we_wszystkich_wojew)):
        only_rate.append(zdawalnosc_we_wszystkich_wojew[x][0][2])    
    max_rate=max(only_rate)
    for i in range(len(zdawalnosc_we_wszystkich_wojew)):
        if zdawalnosc_we_wszystkich_wojew[i][0][2]==max_rate:
            wynik.append(zdawalnosc_we_wszystkich_wojew[i])
            print('rok: ', zdawalnosc_we_wszystkich_wojew[i][0][1], 'wojewodztwo: ', zdawalnosc_we_wszystkich_wojew[i][0][0])
    return wynik
示例#46
0
def __GNormPlus_parser_old(outputdir):
    '''output: pmid, gene_entry, article_part'''
    gnor = normalization.gene_normor('../data/hgnc_complete_set.txt')
    for root, dirs, files in os.walk(outputdir):
        for fn in files:
            with open(os.path.join(root, fn), 'r') as f:
                records = [i for i in f.read().split('\n') if i]
                for r in records:
                    is_text = re.match(r'\d+\|a\|(.+)$', r)
                    if is_text:
                        continue
                    else:
                        pmid, start, end, string, type, ids = r.split('\t')
                        if not re.match('gene|protein', type, re.IGNORECASE):
                            continue
                        pmid = int(pmid)
                        start = int(start)
                        end = int(end)
                        for did in ids.split(';'):
                            '''one tring map to mutil-gene'''
                            try:
                                norm = gnor.norm(did)
                            except KeyError as e:
                                print('gene {0} skip: no gene in hgnc'.format(
                                    string))
                                continue
                            yield (pmid,
                                   Base.BioEntry(start, end, type, string, id,
                                                 norm), fn)
示例#47
0
class TextField(BaseField):
    """
        A field with a textbox as the input
    """
    inputElement = Inputs.TextBox
    properties = BaseField.properties.copy()
    Base.addChildProperties(properties, Inputs.TextBox, 'userInput')
示例#48
0
def record(seconds=None, nchan=None, fs=None, bits=None, w=None):
	"""
	If a wav object w is supplied, its data array w.y is replaced by newly recorded sound.
	Parameters such as duration, number of channels are taken from w by default, but may
	be explicitly overridden by the other arguments.
	
	If w is not supplied, then a new wav object is constructed.
	"""###
	
	if isinstance(w,player): w = p.wav
	if w == None:
		if not seconds: raise ValueError, "please specify number of seconds for which to record"
		if not nchan: nchan = 2
		if not fs: fs = 44100
		if not bits: bits = 16
		w = Base.wav(fs=fs,bits=bits,nchan=nchan)
	else:
		if not seconds: seconds = w.duration()
		if not nchan: nchan = w.channels()
		if not fs: fs = int(w.fs)
		if not bits: bits = w.bits
		w.fs = fs
		w.bits = bits # nbytes should be updated automatically	
	interface = grab_interface()
	format = interface.get_format_from_width(w.nbytes)	
	nsamp = int(0.5 + seconds * float(fs))
	recorder = interface.open(format=format, channels=nchan, rate=fs, input=True)				
	print "recording"
	strdat = recorder.read(nsamp)
	print "done"
	recorder.close()
	release_interface(interface)
	w.y = w.str2dat(strdat, nsamp, nchan)
	#if w.bits==8: w.__dict__.update({'signed':True, 'dtype':'<i1',})
	return w
示例#49
0
def revlookup(name):
    "convenience routine for doing a reverse lookup of an address"
    a = string.split(name, '.')
    a.reverse()
    b = string.join(a, '.') + '.in-addr.arpa'
    # this will only return one of any records returned.
    return Base.DnsRequest(b, qtype='ptr').req().answers[0]['data']
示例#50
0
    def Activated(self):
        import FreeCAD, FreeCADGui
        if hasattr(FreeCADGui, "draftToolBar"):
            FreeCADGui.draftToolBar.Deactivated()

        if not FreeCAD.ActiveDocument:
            FreeCAD.newDocument('DDA')

        import Base
        Base.enableSeletionObserver(True)
        import DDADatabase
        DDADatabase.enableOperationObverser(True)

        FreeCADGui.runCommand('DDA_ResetCamera')

        self.resetWorkbench()
示例#51
0
    def accepted(self):
        import Base
        from extractDGData import DGExtracter
        import os
        from PySide import QtCore, QtGui
        bar = QtGui.QProgressDialog('extracting data...', 'stop Analysis', 0,
                                    100, None, QtCore.Qt.WindowModal)
        bar.canceled.connect(self.__stopAnalysis)
        bar.setValue(0)
        bar.setVisible(True)

        self.__setStopAnalysisFlag(False)
        if not self.__ui.ui.checkBox_useExistingData.isChecked():
            extracter = DGExtracter()
            extracter.setFile(
                os.path.join(Base.__currentProjectPath__, 'data.dg'))
            if self.__ui.ui.checkBox_stress.isChecked():
                extracter.saveStress4Block(self.__ui.ui.spinBox_No.value())
            extracter.setSaveMPMovements(self.__ui.ui.checkBox_MP.isChecked())
            extracter.setSaveDists(
                self.__ui.ui.checkBox_displacement.isChecked())
            print 'extracting data  ', Base.getCurrentTime()
            extracter.extractData()
            print 'extracting data done  ', Base.getCurrentTime()
            if self.__getStopAnalysisFlag(): return
            bar.setValue(20)
            bar.setLabelText('outputing data...')
            print 'outputing extracting data  ', Base.getCurrentTime()
            extracter.outputExtractedData()
            print 'outputing extracting data done  ', Base.getCurrentTime()
            if self.__getStopAnalysisFlag(): return
        bar.setValue(40)

        if not self.__analysiser:
            self.__analysiser = DGAnalysiser()
        else:
            self.__analysiser.uninstallToolbar()
        self.__analysiser.setAnalysesDisplacement(
            self.__ui.ui.checkBox_displacement.isChecked())
        self.__analysiser.setAnalysesMPs(self.__ui.ui.checkBox_MP.isChecked())
        self.__analysiser.setAnalysesStress(
            self.__ui.ui.checkBox_stress.isChecked())
        self.__analysiser.setBlockNumber(self.__ui.ui.spinBox_No.value())
        self.__analysiser.setUseExistingData(
            self.__ui.ui.checkBox_useExistingData.isChecked())
        bar.setLabelText('loading outputed data...')
        print 'loading data   ', Base.getCurrentTime()
        self.__analysiser.loadData()
        print 'loading data  done   ', Base.getCurrentTime()
        if self.__getStopAnalysisFlag(): return
        bar.setValue(50)
        bar.setLabelText('analysesing and showing data...')
        self.__analysiser.setupToolbar()
        print 'show analysising ', Base.getCurrentTime()
        self.__analysiser.showAnalysis()
        print 'show analysising done ', Base.getCurrentTime()
        bar.setValue(100)
示例#52
0
def HandleDraw():
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

  angle = Base.timer_step * 100.0
  glRotate(angle, 3, 1, 1)
  RenderCube()

  Base.HandleDraw()
示例#53
0
 def agregarBase(self, nuevo: Base):
     if self.primero is None:
         self.primero = nuevo
         self.ultimo = nuevo
     else:
         self.ultimo.siguiente = nuevo
         nuevo.anterior = self.ultimo
         self.ultimo = nuevo
示例#54
0
 def __init__(self, start, target, strategy):
     self.target = target
     self.start = Base(None, start, Direction(5), 0)
     self.strategy = strategy
     self.maxDepth = 0
     if (self.start.state != self.target):
         self.frontier.put(self.start.state)
         self.explored[str(self.start.state)] = self.start
示例#55
0
def show_genres(call):
    """
    If user push the button "Genres" in menu, bot uses this commands and send all genres, which he found in Base.
    :param call:
    :return: Inline buttons, each shows unique genre from Base
    """
    chat_id = call.message.chat.id
    message_id = call.message.message_id
    text = call.message.text
    if Base.double_click_protection(chat_id, text):
        clear_screen(chat_id, Base.show_message_current(chat_id), message_id, call.data)

        games = Base.show_all_genres()

        generate_inline_buttons_row_double(chat_id, "<b>Список жанров:</b>                                        "
                                                    "\U0000200C", *games)
        show_menu(chat_id, 0)
示例#56
0
 def createDataBase(self, basedatos: str, modo: int = 1):
     #0: exitoso, 1: error en la operación, 2: base de datos existente
     if self.lista_bases.existeBaseDatos(basedatos):
         return 2
     else:
         self.lista_bases.agregarBase(Base.Base(basedatos))
         return 0
     return 1
示例#57
0
def AssignMission():
    fixers.DestroyActiveButtons()
    fixers.CreateChoiceButtons(Base.GetCurRoom(), [
        fixers.Choice("bases/fixers/yes.spr", "bases/fixers/iso_mission.py",
                      "Accept This Agreement"),
        fixers.Choice("bases/fixers/no.spr", "bases/fixers/iso_decline.py",
                      "Decline This Agreement")
    ])
示例#58
0
    def preview(self):
        print '#############################\n############  preview##########\n#####################\n'
        
        import Base
        re = Base.showWaringMessageBox('Warning', 'Joint lines will calculated again. All changes made manually will be lost, are your sure?')

        if re== QtGui.QMessageBox.Ok:
            FreeCADGui.runCommand('DDA_DLCalculate')
示例#59
0
 def iterate(self, nam=str()):
     """Will execute the next stage of the conversation, ie create the relevant
     textual message and response buttons, given the conversation string, and
     the reference to the next possible nodes."""
     name = str(nam)
     if name == str():
         name = self.ROOT_KEY
     DestroyActiveButtons()
     text, choices = self.getNewInfo(name)
     if choices:
         choices = list(choices)
         for i in range(len(choices)):
             choices[i] = choices[i].split('|')
             choices[i] = Choice(choices[i][0], choices[i][1], choices[i][2])
         CreateChoiceButtons(Base.GetCurRoom(),choices)
     if text:
         Base.Message(text)
示例#60
0
 def __init__(self, *patterns):
     self.data = []
     item = [Base.asStream(p) for p in patterns]
     size = op.LCM(*[len(i) for i in item])
     for n in range(size):
         for i in item:
             self.data.append(op.modi(i, n))
     self.make()