예제 #1
0
 def keyPressEvent(self, event):
     if event.key() == Qt.Key_Delete:
         if self.m_chooseShape != None:
             self.m_chooseShape.setColor(False)
             print 'key delete'
             History.Push(self.m_lShape)
             if self.m_chooseShape.isRect() or self.m_chooseShape.isDiamond(
             ):
                 self.RemoveRect(self.m_chooseShape.m_nId)
             elif self.m_chooseShape.isLine():
                 self.RemoveLine(self.m_chooseShape.m_nId)
         self.m_chooseShape = None
         self.update()
     elif event.modifiers() == (
             Qt.ControlModifier) and event.key() == Qt.Key_Z:
         self.m_lShape = History.Pop(self.m_lShape)
         self.update()
         if self.m_chooseShape == True:
             self.m_chooseShape.setColor(False)
             self.m_chooseShape = None
             self.m_shape = None
             self.m_perm = True
         if self.m_curAction != None:
             self.m_curAction.setChecked(False)
         self.m_curAction = None
         self.m_curShapeCode = -1
예제 #2
0
    def on_finish_loading(self, widget, frame):
        url = self.webview.get_main_frame().get_uri()

        # set the security icon
        if "https://" in url:
            self.secure_icon.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_MENU)
        else:
            self.secure_icon.set_from_stock(gtk.STOCK_STOP, gtk.ICON_SIZE_MENU)

        # set the url bar
        self.url_textbox.set_text(url)

        # add history
        title = self.webview.get_title()
        time = datetime.datetime.now().strftime("%H:%M:%S")
        date = datetime.datetime.now().date()
        h = History()
        h.insert_history(title, url, time, date)

        # check bookmark
        if title in bookmarks_list:
            image = gtk.Image()
            image.set_from_file("bookmarked.ico")
            self.bookmark_image.set_active(True)
            self.bookmark_image.set_image(image)
        else:
            image = gtk.Image()
            image.set_from_file("not_bookmarked.ico")
            self.bookmark_image.set_active(False)
            self.bookmark_image.set_image(image)
예제 #3
0
파일: VLACal.py 프로젝트: mauch/Obit
def VLAUVFITS(inUV, filename, outDisk, err, compress=False, \
              exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \
                  include=[], headHi=False):
    """ Write UV data as FITS file
    
    Write a UV data set as a FITAB format file
    History written to header
    inUV       = UV data to copy
    filename   = name of FITS file
    inDisk     = FITS directory number
    err        = Python Obit Error/message stack
    exclude    = List of table types NOT to copy
                 NB: "AIPS HI" isn't really a table and gets copied anyway
    include    = List of table types to copy (FQ, AN always done )
                 Exclude has presidence over include
    headHi     = if True move history to header, else leave in History table
    returns FITS UV data object
    """
    ################################################################
    # Checks
    if not UV.PIsA(inUV):
        raise TypeError, "inUV MUST be a Python Obit UV"
    if not OErr.OErrIsA(err):
        raise TypeError, "err MUST be an OErr"
    #
    # Set output
    outUV = UV.newPFUV("FITS UV DATA", filename, outDisk, False, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error creating FITS data")
    #Compressed?
    if compress:
        inInfo = UV.PGetList(outUV)  #
        dim = [1, 1, 1, 1, 1]
        InfoList.PAlwaysPutBoolean(inInfo, "Compress", dim, [True])
    # Copy
    UV.PCopy(inUV, outUV, err)
    if err.isErr:
        OErr.printErrMsg(err, "Error copying UV data to FITS")
    # History
    inHistory = History.History("inhistory", outUV.List, err)
    outHistory = History.History("outhistory", outUV.List, err)
    # Add history
    outHistory.Open(History.READWRITE, err)
    outHistory.TimeStamp(" Start Obit uvtab", err)
    outHistory.WriteRec(
        -1, "uvtab   / FITS file " + filename + " disk " + str(outDisk), err)
    outHistory.Close(err)
    # History in header?
    if headHi:
        History.PCopy2Header(inHistory, outHistory, err)
        OErr.printErrMsg(err, "Error with history")
        # zap table
        outHistory.Zap(err)
    # Copy Tables
    UV.PCopyTables(inUV, outUV, exclude, include, err)
    return outUV  # return new object
예제 #4
0
def CalculateSeasonWeight(recipe):
    '''
    Calculate weight factor based on season
    '''
    today = datetime.date.today()
    seasons = recipe.Seasons()
    if seasons.find('s') < 0 and History.IsSpring(today):
        return 0
    if seasons.find('u') < 0 and History.IsSummer(today):
        return 0
    if seasons.find('f') < 0 and History.IsFall(today):
        return 0
    if seasons.find('w') < 0 and History.IsWinter(today):
        return 0
    return 1
예제 #5
0
파일: Context.py 프로젝트: Nurb432/Trail
    def set_url(self, url, baseurl=None, target=None, histify=1):
        """Set loaded URL, base URL and target for the current page.

        The loaded URL is what this page was loaded from; the base URL
        is used to calculate relative links, and defaults to the
        loaded URL.  The target is the default viewer name
        where followed links will appear, and defaults to this viewer.

        HISTIFY flag, if true, adds the URL to the history stack.

        """
        if url and histify:
            # don't lose title if we have one:
            title, when = self.app.global_history.lookup_url(url)
            self.app.global_history.remember_url(url, title or '')
            if not self.page:
                self.page = History.PageInfo(url)
                self.history.append_page(self.page)
            else:
                self.page.set_url(url)
                self.page.set_title("")  # Will be reset from fresh HTML
                self.history.refresh()
        else:
            if self.future >= 0:
                self.page = self.history.page(self.future)
                self.future = -1
            else:
                self.page = None
        URIContext.set_url(self, url, baseurl=baseurl)
        self._target = target
        if self.on_top():
            self.browser.set_url(self.get_url())
        self.applet_group = None
예제 #6
0
 def manage_historyCompare(self, rev1, rev2, REQUEST,
                           historyComparisonResults=''):
     return DTMLMethod.inheritedAttribute('manage_historyCompare')(
         self, rev1, rev2, REQUEST,
         historyComparisonResults=History.html_diff(
             rev1.read(), rev2.read()
             ))
예제 #7
0
 def initUI(self):
     self.preDefined = PreDefined.myPreDefined(self)
     self.userDefined = UserDefined.myUserDefined(self)
     self.history = History.myHistory()
     self.addTab(self.preDefined, '预设风格')
     self.addTab(self.userDefined, '自定义风格')
     self.addTab(self.history, '历史记录')
예제 #8
0
def history(instrument,
            start_date,
            num_days=100000,
            host="localhost",
            port=9100):
    '''
    Generates history lines for a given instrument
    '''
    if type(start_date) == types.StringType:
        start_date = datetime.date(int(start_date[0:4]), int(start_date[5:7]),
                                   int(start_date[8:10]))

    _q = Queue.Queue()
    _qp = _QueueProducer(_q)

    client = History.HistoryClient((host, port))
    client.set_listener('', _qp)
    client.getHistory(instrument, start_date, num_days)

    while 1:
        try:
            # Wait until a new message is available
            message = _q.get()
            if message is None:
                break
            yield message
        except KeyboardInterrupt:
            break

    client.del_listener('')
def SaveNClean(defject, vertices, i, content):
    #save all there is to run from current iteration and clean up proper

    rs.Command("_SelNone")
    rs.Command("_SelPolysrf")

    index = i
    if index < 10:
        j = "0" + str(index)
    if index >= 10:
        j = index

    #Quite probably there is a purely scripted way of writing the export now
    #It would be through the Rhino and scriptcontext
    rs.Command("_-Export C:\R3\OffCenter\Walk\Temp\proto2o" + j + ".igs ENTER")
    rs.DeleteObject(defject)

    for vrtx in vertices:
        rs.AddPolyline(vrtx)

    #Again
    rs.Command("-saveas C:\\R3\OffCenter\Walk\Temp\sth" + j + ".3dm")

    objects = rs.AllObjects()
    rs.DeleteObjects(objects)

    #need a place to write our polies to!!!
    History.WritePolies(tempfolder + "\polies" + j + ".txt", content)
예제 #10
0
    def mouseMoveEvent(self, event):
        if self.m_chooseShape != None and self.m_chooseShape.hasCorner() != -1:
            self.MoveReShape(event)
            return

        #处理被选中的物体的拖动,这里线是不能被拖动的
        DeltaMoveObj = QPoint()
        if self.m_chooseShape != None and (
                self.m_chooseShape.isRect() == True
                or self.m_chooseShape.isDiamond() == True
                or self.m_chooseShape.isComment() == True):
            if self.m_bMoving == True:
                self.m_bMoving = False
                self.m_chooseShape.setColor(False)
                History.Push(self.m_lShape)
                self.m_chooseShape.setColor(True)

            self.m_curPoint = event.pos()
            DeltaMoveObj = self.m_curPoint - self.m_prePoint
            self.m_chooseShape.move(DeltaMoveObj)
            #所有线段检查是否和这个矩形有关系,如果有,移动
            for shape in self.m_lShape:
                if shape.isLine() == True:
                    shape.move(DeltaMoveObj, self.m_chooseShape.m_nId)
            self.m_prePoint = self.m_curPoint
            self.update()
            return

        if self.m_shape and self.m_perm == False:
            self.m_shape.setEnd(event.pos())
            self.update()
            return
예제 #11
0
    def show_bookmarks(self):
        if self.history_box.get_property("visible"):
            self.hide_history(self.history_box)

        if self.bookmarks_box.get_property("visible"):
            self.bookmarks_box.hide()
            self.bottom_hpan.remove(self.bookmarks_box)
            self.bookmarks_list_store.clear()
            column_list = self.bookmarks_tree_view.get_columns()
            for iter_column in column_list:
                self.bookmarks_tree_view.remove_column(iter_column)

        else:
            self.bottom_hpan.add1(self.bookmarks_box)
            h = History()
            h.cursor.execute("select title from bookmarks")
            row = h.cursor.fetchone()
            while row:
                self.bookmarks_list_store.append(row)
                row = h.cursor.fetchone()

            for i, col_title in enumerate(["Title"]):
                renderer = gtk.CellRendererText()
                column = gtk.TreeViewColumn(col_title, renderer, text=i)
                self.bookmarks_tree_view.append_column(column)

            self.bookmarks_box.show_all()
예제 #12
0
    async def server(self, websocket, path):
        req = await websocket.recv()

        req = json.loads(req)

        if req['msg'] == 'method':
            if req['method'] == 'getHistory':
                h = History.History('/home/pi/OS/HistoryDB.json')
                res = {'msg': 'result', 'result': h.get()}
                await websocket.send(json.dumps(res))
            if req['method'] == 'getEnergy':
                e = Energy.Energy('/home/pi/OS/EnergyDB.json')
                if not req['params']:
                    res = {'msg': 'result', 'result': e.get()}
                else:
                    resultArray = []
                    params = req['params']
                    if len(params) > 0:
                        for p in params:
                            resultArray.append(e.get(p))
                    res = {'msg': 'result', 'result': resultArray}
                await websocket.send(json.dumps(res))
            else:
                res = {
                    'msg': 'error',
                    'error': 'unrecognized request',
                    'code': 501
                }
                await websocket.send(json.dumps(res))
        print("sent response")
예제 #13
0
def MFPBCor(inIm, err, antSize=24.5, minGain=0.05):
    """
    Apply primary beam corrections to an ImageMF

    WARNING: This routine modifies the input image;
    ONLY RUN IT ONCE.
    * inIm    = Image to be modified
    * err     = Python Obit Error/message stack
    * antSize = Antenna diameter in m.
    * minGain = Minimum antenna gain
    """
    # Check
    if not inIm.ImageIsA():
        raise TypeError("input MUST be a Python Obit Image")
    # Image info
    nterm = inIm.Desc.List.Dict['NTERM'][2][0]
    nspec = inIm.Desc.List.Dict['NSPEC'][2][0]
    freqs = []
    for i in range(1, nspec + 1):
        key = 'FREQ%4.4d' % i
        freqs.append(inIm.Desc.List.Dict[key][2][0])

    # end loop
    # Make scratch image for beam
    beam = Image.Image("PBeam")
    Image.PCloneMem(inIm, beam, err)
    OErr.printErrMsg(err, "Error with scratch beam image")
    # Loop over planes
    for i in range(1, nspec + 1):
        # Read plane
        plane = [i + nterm, 1, 1, 1, 1]
        Image.PGetPlane(inIm, None, plane, err)
        OErr.printErrMsg(err, "Error reading image")
        # Set frequency for PBCor
        d = inIm.Desc.Dict
        d['crval'][2] = freqs[i - 1]
        inIm.Desc.Dict = d
        # Make PB Image
        ImageUtil.PPBImage(beam,
                           beam,
                           err,
                           minGain=minGain,
                           antSize=antSize,
                           outPlane=plane)
        OErr.printErrMsg(err, "Error making PB image")
        # Divide
        FArray.PDivClip(inIm.FArray, beam.FArray, minGain, inIm.FArray)
        # Rewrite plane
        Image.PPutPlane(inIm, None, plane, err)
        OErr.printErrMsg(err, "Error writing image")

    # end loop
    # Add history
    outHistory = History.History("history", inIm.List, err)
    outHistory.Open(History.READWRITE, err)
    outHistory.TimeStamp(" Start Obit MFPBCor", err)
    outHistory.WriteRec(-1, "MFPBCor" + " antSize = " + str(antSize), err)
    outHistory.WriteRec(-1, "MFPBCor" + " minGain = " + str(minGain), err)
    outHistory.Close(err)
def MainS():
    
    #SETTING UP THE FILE ACCESS TO READ ALL THERE IS TO BE READ
    #THE SCRIPT FROM NOW ON LOOKS for FILE AND if IT CANNOT FIND ONE IT WILL HAVE TO MAKE ONE
    
    #SOOO WE START BY LOOKING for AND READING THE FILE if WE FIND IT
    
    ##     
    ########################################################################
    #READ INFO IN THE FILE
    ########################################################################
   
    #ReadFile returns an array of [isAlive,startPoint,jointNos]
    content = History.ReadPolies(folder,file)
    
    
    rhUnitInches = 8
    rs.UnitSystem(rhUnitInches, False, True)
    
    zero = [0,0,0]
    zaxis = [0,0,1]
    
    vrt = []
    
    
    #Decimal display and decimal places
    #rs.UnitDistanceDisplayMode(0) 
    #rs.UnitDistanceDisplayPrecision(7)
    
    
    #sth to control that we have an [0,0,0] to check
    endcheck = 1
    
    size = 1
    
    helper =[]
    
    
    #if we read nothing we should save 1 starting point - namely [0,0,0]
    if content is None:
        endpts = [[0,0,0]]
        npolies = 0
        #polylines is an array of polylines
        #polyline is an array of points
        #point is an array of numbers
        
        #life#starting_point#joints_used
        sequence = [1,[0,0,0],[0]]
        #content = [[sequence],0]
        content = [sequence]
        
    else:
        
        #checking if new rib has actualy been started
        #[0,0,0] will always be the lasrt one
        for i = 0 To content(1]
            if rs.Distance(content(0](i](1],[0,0,0]]<tiny Then
                endcheck = endcheck*0
            End if
예제 #15
0
def historyDetailJson():
    row = History.Get(request.query.time)
    return "{" + \
      "\"path\":\"" + row[0] + "\"," + \
      "\"user\":\"" + row[1] + "\"," + \
      "\"comment\":\"" + row[2] + "\"," + \
      "\"time\":\"" + row[3] + "\"" + \
      "}"
예제 #16
0
 def __init__(self, data=None):
     """
     Initialize the QuadsData object.
     """
     self.hosts = Hosts.Hosts(data)
     self.clouds = Clouds.Clouds(data)
     self.history = History.History(data)
     self.cloud_history = CloudHistory.CloudHistory(data)
예제 #17
0
    def mousePressEvent(self, event):
        """
            @ 鼠标单击事件
        """
        self.m_prePoint = event.pos()
        #判断是否选中了直线的一端,如果选中了,需要触发编辑功能
        if self.m_sChooseShapeName != None and self.m_sChooseShapeName != "":
            shapeObj = self.m_dShape[self.m_sChooseShapeName]
            if shapeObj.isLine() == True:
                if shapeObj.getCorner(event.pos()) != -1:
                    History.push(self.m_dLayers)
                    #启动编辑对m_dLayer的输入输出产生影响
                    self.removeLine(self.m_sChooseShapeName)
                    return

        self.PressChooseShape(event)
        return
예제 #18
0
def readLog(path):
    # Reader de log de NOMAD et creer un objet history consequent

    # Regarde par le nom les specs de la run
    file=path.split('\\')[-1]
    name = file.split('_')
    ext = name[-1].split('.')[2]
    name[-1]=name[-1].split('.')[0]
    name.append(ext)

    #Erreur si on a pas un file history
    if name[2]!='history':
        print('file provided is not of the right format')
        return

    #On cree un objet history
    history=History.History()

    #Nom, Classe, solveur et parametre de resolution du probleme
    history.setProblem(str(name[0])+str(name[1]))
    history.setProblemNumber(str(name[0]))
    history.setProblemClass(str(name[1]))
    history.setSeed(str(name[3]))
    history.setAlgo(str(name[4][0]))
    history.setStrat(str(name[4][1:]))
    history.setSolver('NOMAD')

    # Ouvrir le history.txt
    with open(path, 'r') as file:
        iniFile = file.readlines()
        file.close()

    # Mettre la history dans l'objet
    nbIteration = len(iniFile) #nombre de lignes dans le fichier
    table = []  # initialisation de ma liste
    for x in range(0, nbIteration):
        # Pour chaque ligne de mon history je dois
        # creer une liste
        # appender la liste a l indice x du array
        ligne = list(map(float, (iniFile[x]).split()))  # creer la ligne de float
        table.append(ligne)  # ajoute a la table
    history.setTable(table)

    # Determiner la dimension du probleme
    paramPath = path[:-(len(path.split('\\')[-1]))]
    paramName = history.getSeed()+'_param.txt'
    paramFile = paramPath+paramName

    with open(paramFile, 'r') as f:
        # Ouvrir le parameters.txt
        params = f.readlines()
        f.close()
    for el in params:
        if el.split() and el.split()[0]=='DIMENSION':
            dim = el.split()[1]
    history.setNbVar(dim)

    return history
예제 #19
0
    def test_trend_forecasting_model(test_years,
                                     min_trend_h,
                                     model_years=None,
                                     model_hist=None,
                                     strict_mode=False,
                                     mode="avg"):

        if not model_years and not model_hist:
            raise Exception(
                "You must provide a model history or year for a model history!"
            )

        if model_years:
            if type(model_years) is not list:
                model_years = list(model_years)

            if len(model_years) > 2:
                model_years = [model_years[0], model_years[-1]]

        if type(test_years) is not list:
            test_years = list(test_years)

        if len(test_years) > 2:
            test_years = [test_years[0], test_years[-1]]

        if model_hist:
            anal = Analyzer(model_hist,
                            min_trend_h=min_trend_h,
                            realistic=False)
        else:
            h = History("GER30", *model_years)
            anal = Analyzer(h, min_trend_h=min_trend_h, realistic=False)

        anal.get_intern_trend_prediction_error(p=True,
                                               use_strict_mode=strict_mode,
                                               mode=mode)
        test_anal = Analyzer(History("GER30", *test_years),
                             min_trend_h=min_trend_h,
                             realistic=False)

        anal.get_extern_trend_prediction_error(test_anal.trend_list,
                                               p=True,
                                               use_strict_mode=strict_mode,
                                               mode=mode)
예제 #20
0
def createNewHistory(self, wherex, wherey, screenCoordinates=1):
    self.fromClass = None
    self.toClass = None
    # try the global constraints...
    res = self.ASGroot.preCondition(ASG.CREATE)
    if res:
        self.constraintViolation(res)
        self.mode = self.IDLEMODE
        return

    new_semantic_obj = History(self)
    res = new_semantic_obj.preCondition(ASGNode.CREATE)
    if res: return self.constraintViolation(res)
    new_semantic_obj.preAction(ASGNode.CREATE)

    ne = len(self.ASGroot.listNodes["History"])
    if new_semantic_obj.keyword_:
        new_semantic_obj.keyword_.setValue(
            new_semantic_obj.keyword_.toString() + str(ne))
    if screenCoordinates:
        new_obj = graph_History(self.UMLmodel.canvasx(wherex),
                                self.UMLmodel.canvasy(wherey),
                                new_semantic_obj)
    else:  # already in canvas coordinates
        new_obj = graph_History(wherex, wherey, new_semantic_obj)
    new_obj.DrawObject(self.UMLmodel, self.editGGLabel)
    self.UMLmodel.addtag_withtag("History", new_obj.tag)
    new_semantic_obj.graphObject_ = new_obj
    self.ASGroot.addNode(new_semantic_obj)
    res = self.ASGroot.postCondition(ASG.CREATE)
    if res:
        self.constraintViolation(res)
        self.mode = self.IDLEMODE
        return

    res = new_semantic_obj.postCondition(ASGNode.CREATE)
    if res:
        self.constraintViolation(res)
        self.mode = self.IDLEMODE
        return
    new_semantic_obj.postAction(ASGNode.CREATE)

    self.mode = self.IDLEMODE
    if self.editGGLabel:
        self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE)
    else:
        self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE)
    return new_semantic_obj
예제 #21
0
 def keyPressEvent(self, event):
     """
         @ 键盘回调函数
     """
     #删除矩形或者线条
     if event.key() == Qt.Key_Delete or event.key() == 16777219:
         if self.m_sChooseShapeName != None and self.m_sChooseShapeName != "":
             print 'key delete'
             History.push(self.m_dLayers)
             shapeObj = self.m_dShape[self.m_sChooseShapeName]
             shapeObj.setColor(False)
             if shapeObj.isRect():
                 self.removeRect(self.m_sChooseShapeName)
                 del self.m_dLayers[self.m_sChooseShapeName]
             elif shapeObj.isLine():
                 self.removeLine(self.m_sChooseShapeName)
             self.transLayersToShape()
         self.m_sChooseShapeName = None
         self.update()
     #ctrl + z 回退错误修改
     elif event.modifiers() == (
             Qt.ControlModifier) and event.key() == Qt.Key_Z:
         self.m_sChooseShapeName = None
         self.m_dLayers = History.back(self.m_dLayers)
         self.transLayersToShape()
         self.update()
     #ctrl + r 前进
     elif event.modifiers() == (
             Qt.ControlModifier) and event.key() == Qt.Key_R:
         self.m_sChooseShapeName = None
         self.m_dLayers = History.forward(self.m_dLayers)
         self.transLayersToShape()
         self.update()
     #F 刷新
     elif event.key() == Qt.Key_F:
         for (sName, layerObj) in self.m_dLayers.items():
             if sName != layerObj.GetName():
                 self.changeLayerName(sName, layerObj.GetName())
                 del self.m_dLayers[sName]
                 self.m_dLayers[layerObj.GetName()] = layerObj
         self.transLayersToShape()
예제 #22
0
    def test_trend_predictor():

        h = 35

        anal = Analyzer(dax_hist, min_trend_h=h)
        vali_anal = Analyzer(History("GER30", 2017), min_trend_h=h)
        #arti_anal = Analyzer(ArtificialHistory(dax_hist, out_len=1000000, min_trend_h=h), min_trend_h=h)

        anal.build_trend_predictor(
            7,
            validation_data=vali_anal.trend_list,
        )
예제 #23
0
 def manage_historyCompare(self,
                           rev1,
                           rev2,
                           REQUEST,
                           historyComparisonResults=''):
     return DTMLMethod.inheritedAttribute('manage_historyCompare')(
         self,
         rev1,
         rev2,
         REQUEST,
         historyComparisonResults=History.html_diff(rev1.read(),
                                                    rev2.read()))
예제 #24
0
def createNewHistory(self, wherex, wherey, screenCoordinates = 1):
   self.fromClass = None
   self.toClass = None
   # try the global constraints...
   res = self.ASGroot.preCondition(ASG.CREATE)
   if res:
      self.constraintViolation(res)
      self.mode=self.IDLEMODE
      return

   new_semantic_obj = History(self)
   ne = len(self.ASGroot.listNodes["History"])
   if new_semantic_obj.keyword_:
      new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne))
   if screenCoordinates:
      new_obj = graph_History(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj)
   else: # already in canvas coordinates
      new_obj = graph_History(wherex, wherey, new_semantic_obj)
   new_obj.DrawObject(self.UMLmodel, self.editGGLabel)
   self.UMLmodel.addtag_withtag("History", new_obj.tag)
   new_semantic_obj.graphObject_ = new_obj
   self.ASGroot.addNode(new_semantic_obj)
   res = self.ASGroot.postCondition(ASG.CREATE)
   if res:
      self.constraintViolation(res)
      self.mode=self.IDLEMODE
      return

   res = new_semantic_obj.postCondition(ASGNode.CREATE)
   if res:
      self.constraintViolation(res)
      self.mode=self.IDLEMODE
      return

   self.mode=self.IDLEMODE
   if self.editGGLabel :
      self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE)
   else:
      self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE)
   return new_semantic_obj
예제 #25
0
def Detail(
        no,  # String(In): FileID
        user  # String(In): User Name
):  # String(html)
    global lock
    global conn
    global c
    global videoInfo

    # [[[ 1. Lock ]]]
    lock.acquire()

    # [[[ 2. Prepare SQLite ]]]
    if conn is None:
        conn = sqlite3.connect(fileName, check_same_thread=False)
        c = conn.cursor()

    # [[[ 3. Make <li></li> List ]]]
    list = ''  # return html string
    # [[ 3.1. Prepare SQL statement ]]
    sql = 'SELECT FileID, DirName, FileName, Size, Time FROM File WHERE FileID = ?'
    # [[ 3.2. Query ]]
    size = 0
    time = ''
    filePath = ''
    for row in c.execute(sql, [no]):
        size = row[3]
        time = row[4]
        filePath = os.path.join(row[1], row[2])

    # [[[ 4. Unlock ]]]
    lock.release()

    # [[[ 5. Make Tag ]]]
    list = filePath + "<br>" + "{:,}".format(size) + "[Byte]<br>"
    list = list + time + "<br>"
    if None is videoInfo:
        videoInfo = VideoInfo.VideoInfo()
    if (None is videoInfo.GetDuration(filePath)):
        list = u"動画が見つかりません。" + "<br>" + u"曲情報を更新してください。"
    else:
        hour = str(int(videoInfo.GetDuration(filePath) / 3600)).zfill(2)
        minutes = str(int(videoInfo.GetDuration(filePath) % 3600 /
                          60)).zfill(2)
        seconds = str(int(videoInfo.GetDuration(filePath) % 60)).zfill(2)
        list = list + hour + ":" + minutes + ":" + seconds + "<br>"
        list = list + videoInfo.GetVideoEncode(filePath) + "("
        list = list + videoInfo.GetResolution(filePath) + ")"
        # [[ 5.1. History Count ]]
        list = list + "<br>" + str(History.Count(filePath)) + u"回"

    return list
예제 #26
0
    def Stalin(self, startr, endr, err):
        """
        Edit history
        
        return 0 on success, else failure

        * self   = input Python History
        * startr = first (1-rel) history record to delete
        * endr   = highest (1-rel) history record to delete, 0->to end
        * err    = Python Obit Error/message stack
        """
        hi = self.History(READWRITE, err)
        return History.PEdit(hi, startr, endr, err)
예제 #27
0
파일: Session.py 프로젝트: bbockelm/CRAB
 def __init__(self, logger, configFile, root):
     """ Construt a session with the current thread logger and the configFile name. """
     self.cwd = None # Working directory (discovered after crab -create)
     self.root = os.path.abspath(root)
     self.jobsHistory = History() 
     self.configFile = os.path.abspath(configFile)
     self.outNames = parseOutNames(open(self.configFile).read()) # Output file names found in the UI/res after getouput
     self.totJobs = None # Jobs managed (discovered after crab -crete)
     self.submitted = 0 # jobs submitted
     self.logger = logger
     self.returncode = None
     self.outdata = None
     self.errdata = None
     self.cmd = None
예제 #28
0
    def History(self, access, err):
        """
        Return the associated History

        * self      = Python OData object
        * access    = access code 1=READONLY, 2=WRITEONLY, 3=READWRITE
        * err       = Python Obit Error/message stack
        """
        out = History.History("History", self.List, err)
        #out.me = newODataHistory (self, access, err)
        # Error?
        if err.isErr:
            OErr.printErrMsg(err, "Error getting History")
        return out
예제 #29
0
def historyJson():
    list = '['
    firstLine = True
    for row in History.List():
        if True == firstLine:
            firstLine = False
        else:
            list = list + ","
        list = list + \
          "{\"file\":\"" + os.path.basename(row[0]) + "\"," + \
          "\"user\":\"" + row[1] + "\"," + \
          "\"comment\":\"" + row[2] + "\"," + \
          "\"time\":\"" + row[3] + "\"}"
    return list + "]"
예제 #30
0
    def createLayerCallback(self, sLayerTypeName):
        """
            @ 创建新的层, 窗口关闭回调
            @ sLayerTypeName 层的类型名
        """
        History.push(self.m_dLayers)
        try:
            self.createLayerCallback.__func__.nCounter += 1
        except AttributeError:
            self.createLayerCallback.__func__.nCounter = 1

        sLayerName = sLayerTypeName + "_" + str(
            self.createLayerCallback.__func__.nCounter)
        while self.m_dLayers.has_key(sLayerName) == True:
            self.createLayerCallback.__func__.nCounter += 1
            sLayerName = sLayerTypeName + "_" + str(
                self.createLayerCallback.__func__.nCounter)

        layerObj = CfgInstance.getLayerCfg(sLayerTypeName)
        layerObj.m_dKeys["name"] = sLayerName
        self.m_dLayers[sLayerName] = layerObj

        self.transLayersToShape()
        return
예제 #31
0
파일: CopyHistory.py 프로젝트: mauch/Obit-1
def CopyBeamHistory (inIm, outIm, err):
    """
    Copy beam and history from one image to another (beam)

    History may not appear in AIPS header (but is there)
    FITS History is written to "History" table
    * inIm   Input Obit image
    * outIm  Output Obit image (beam)
    * err    Obit Error/message object
    """
    # Copy Beam
    din  = inIm.Desc.Dict
    dout = outIm.Desc.Dict
    dout['beamMaj'] = din['beamMaj']
    dout['beamMin'] = din['beamMin']
    dout['beamPA']  = din['beamPA']
    outIm.Desc.Dict = dout
    outIm.UpdateDesc(err)
    # Copy History
    inHis  = History.History("in",inIm.List,err)
    outHis = History.History("out",outIm.List,err)
    History.PCopy(inHis, outHis,err)
    outIm.UpdateDesc(err)
    OErr.printErr(err)
예제 #32
0
 def mouseDoubleClickEvent(self, event):
     """
         @鼠标双击事件回调
         @坐标落在空白处,触发生成一个新的层的逻辑
         @坐标落在矩形内部,触发生成一个新的连接的逻辑
     """
     #走单击的逻辑
     self.PressChooseShape(event)
     #触发新建连接的逻辑
     if self.m_sChooseShapeName != None and self.m_sChooseShapeName != "":
         History.push(self.m_dLayers)
         shapeObj = self.m_dShape[self.m_sChooseShapeName]
         lineObj = BaseShape.Line()
         lineObj.setStart(event.pos())
         lineObj.setEnd(event.pos())
         lineObj.m_left = self.m_sChooseShapeName
         lineObj.m_curConner = 1
         sName = lineObj.m_left + lineObj.m_left
         self.m_dShape[sName] = lineObj
         self.m_sChooseShapeName = sName
     #触发新建层的逻辑
     else:
         editor = Editor.CreateLayerEditor(self.createLayerCallback)
         editor.exec_()
예제 #33
0
def console():
    global path
    global user
    global comment
    global pause
    global duration
    global audioNum

    # [[[ 1. Update Playing Video ]]]
    if 0 != len(Book.List()) and False is pause:
        # < Can Play >
        if False is video.CheckPlaying():
            # < Not Playing >
            # [[ 1.1. Lock ]]
            lock.acquire()
            try:
                # [[ 1.2. Get and Update First Reservation ]]
                bookList = Book.List()[0]
                path = bookList[2]
                user = bookList[3]
                comment = bookList[4]
                dummy = bookList[8]
                audioIndex = int(bookList[7])
                duration = videoInfo.GetDuration(path)
                audioNum = videoInfo.GetAudioNum(path)
                # [[ 1.2. Check Dummy ]]
                if 0 == dummy:
                    # < Not Dummy >
                    # [ 1.2.1. Play Video ]
                    video.Open(path, vol, audioNum, audioIndex)
                    # [ 1.2.2. Add History ]
                    History.Add(path, user, comment)
                    # [ 1.2.3. Update pause status for playing ]
                    pause = False
                else:
                    # < Dummy >
                    # [ 1.2.4. Switch HDMI Signal ]
                    hdmi.Switch()
                    # [ 1.2.5. Update pause status for pausing ]
                    pause = True
            except:
                import traceback
                traceback.print_exc()
            finally:
                # [[ 1.3. Delete Playing Book ]]
                Book.Delete(bookList[0])
                # [[ 1.4. Unlock ]]
                lock.release()
예제 #34
0
파일: Session.py 프로젝트: bbockelm/CRAB
class Session:
    """ Manager of a Crab session. """
    def __init__(self, logger, configFile, root):
        """ Construt a session with the current thread logger and the configFile name. """
        self.cwd = None # Working directory (discovered after crab -create)
        self.root = os.path.abspath(root)
        self.jobsHistory = History() 
        self.configFile = os.path.abspath(configFile)
        self.outNames = parseOutNames(open(self.configFile).read()) # Output file names found in the UI/res after getouput
        self.totJobs = None # Jobs managed (discovered after crab -crete)
        self.submitted = 0 # jobs submitted
        self.logger = logger
        self.returncode = None
        self.outdata = None
        self.errdata = None
        self.cmd = None

    def jobIds2str(self, jobIds):
        """ Translates a list of jobs into a string. "all" means a complete list of jobs built using self.totJobs.

        >>> jobIds2str([3,1,2])
        '3,1,2'
        """
        if jobIds == "all":
            return str(self.totJobs)
        elif jobIds:
            jobIds = list(jobIds)
            jobs = str(jobIds[0])
            for jobId in jobIds[1:]:
                jobs += ","+str(jobId)
            return jobs
        else:
            return ""

    def crabRunner(self, cmd):
        """ Executes crab with the list of parameters cmd.

        Executes crab with the list of parameters cmd. It returns a tuple containing the returncode and the stdout and the stderr
        in two string.
        """
        cmd = ["crab"] + cmd
        self.logger.debug("Testing: "+" ".join(cmd))
        self.cmd = " ".join(cmd)
        self.returncode, self.outdata, self.errdata = runner(cmd)
        if self.returncode:
            raise CrabException, (cmd, self.returncode, self.outdata, self.errdata)
        return self.returncode, self.outdata, self.errdata


    def crabCreate(self):
        """ Run and test crab -create, returning the set of jobsIds created. """

        cmd = ['-create', '-cfg', self.configFile, '-USER.ui_working_dir', self.root]
        returncode, outdata, errdata = self.crabRunner(cmd)

        self.totJobs = parseCreate(outdata)

        if int(self.totJobs < 1):
            raise TestException, "No jobs created!"
        
        self.logger.info("#### creating -> "+self.jobIds2str(range(1,self.totJobs+1)))

        self.jobsHistory.setJobsNumber(self.totJobs)
        self.cwd = findCrabWD(outdata)
        if not str(self.cwd):
            raise TestException, "Can't get the WD!"
        
        for i in range(1, self.totJobs+1):
            self.jobsHistory.setLocalJobStatus(i, 'create')
        
        self.crabStatus()
        
        for i in range(1, self.totJobs+1):
            local, remote = self.jobsHistory.getJobStatus(i)
            if not remote in CREATED:
                raise TestException, "Job "+str(i)+" not correctly created!"
        
        return set(range(1, self.totJobs+1))
            
    def crabStatus(self):
        """ Run and test crab -status, updating the jobsHistory. """

        assert(self.cwd)

        cmd = ['-status', '-c', self.cwd]
        returncode, outdata, errdata = self.crabRunner(cmd)

        jobList = parseEntireStatus(outdata)
        self.logger.debug("parseEntireStatus->"+str(jobList))
        
        for jobId, status, host, exitcode, statuscode in jobList:
            self.jobsHistory.setRemoteJobStatus(jobId, status)
            self.jobsHistory.setJobAttrs(jobId, host, exitcode, statuscode)

        self.logger.debug(str(self.jobsHistory))

    def crabSubmit(self, nSubmit=-1):
        """ Run and test crab -submit, returning the set of jobsIds submitted. If nSubmit < 0 submit all the jobs it can submit. """

        assert(self.cwd)

        nSubmit = int(nSubmit)
        
        if int(nSubmit) < 0:
            cmd = ['-submit', '-c', self.cwd]
        else:
            cmd = ['-submit', str(nSubmit), '-c', self.cwd]

        if nSubmit < 0:
            nSubmit = self.totJobs
    
        returncode, outdata, errdata = self.crabRunner(cmd)

        submitted = parseSubmit(outdata)
        if not submitted:
            raise TestException, "Wasn't able to submit any jobs correctly!"
        elif submitted < nSubmit:
            self.logger.error("Requested "+str(nSubmit)+" jobs but submitted only "+str(submitted)+"!")
        

        for i in range(self.submitted+1, self.submitted+submitted+1):
            self.jobsHistory.setLocalJobStatus(i, 'submit')
        
        self.logger.info("#### submitting -> "+self.jobIds2str(range(self.submitted+1, self.submitted+submitted+1)))
        
        self.crabStatus()

        if self.submitted+submitted > self.totJobs:
            raise TestException, "More jobs submitted than created!!!"

        for i in range(self.submitted+1, self.submitted+submitted+1):
            local, remote = self.jobsHistory.getJobStatus(i)
            if not (remote in SUBMITTED or remote in WAITING or remote in RUNNING or remote in DONE):
                raise TestException, "Job "+str(i)+" not submitted correctly!"

        self.submitted += submitted
        
        return set(range(self.submitted-submitted+1,self.submitted+1))
        
    def crabGetOutput(self, jobIds = "all", expectedIds = None):
        """ Run and test crab -getouput, returning the set of jobsIds retrieved.
         
        Run and test crab -getouput, returning the set of jobsIds retrieved. if expectedIds is a set of jobIds, the jobs
        retrieved is compared to the expectedIds set, in order to check if some jobs aren't correctly retrieved.
        """
        assert(self.cwd)

        if jobIds == "all":
            cmd = ['-getoutput', '-c', self.cwd]
            self.logger.info("crab -getouput")
        else:
            cmd = ['-getoutput', self.jobIds2str(jobIds), '-c', self.cwd]

        if jobIds == "all":
            jobIds = set(range(1, self.totJobs+1))

        self.logger.info("#### retrieving -> "+self.jobIds2str(jobIds))
        returncode, outdata, errdata = self.crabRunner(cmd)
        
        if not expectedIds:
            expectedIds = jobIds

        try:
            getoutput = parseGetOutput(outdata)
        except TestException, txt:
            if expectedIds:
                raise TestException, txt

        for i in getoutput:
            self.jobsHistory.setLocalJobStatus(i, 'getouput')

        if expectedIds > getoutput: # If something was retrievable but wasn't retrieved
            raise TestException, "Crab didn't succeed in getting every output requested!"


        self.crabStatus()
        
        for i in getoutput:
            local, remote = self.jobsHistory.getJobStatus(i)
            host, exitcode, exitstatus = self.jobsHistory.getJobAttrs(i)

            if not remote in CLEARED:
                raise TestException, "Status of job "+str(i)+" after getoutput isn't correctly cleared!"

            # Checking the existance of output files in the UI
            try:
                for name in self.outNames:
                    self.logger.debug("Verifing "+name+" was retrieved...")
                    name = name.rsplit(".",1)
                    assert(len(name) == 2)
                    name = os.path.join(self.cwd, "res", name[0]+"_"+str(i)+"."+name[1])
                    try:
                        open(name, "rb").close()
                    except IOError:
                        raise TestException, "Output "+name+ " for job "+str(i)+" doesn't exist!"
            except TestException, txt:
                if not exitcode or not exitstatus: # The job hasn't correctly ended
                    self.logger.error(txt) # no need to say crab failed
                else:
                    raise TestException, txt # well, maybe here crab failed!
    
            if not exitcode or not exitstatus:
                raise TestException, "Job "+str(i)+" not ended cleanly: EXITCODE="+str(exitcode)+" EXITSTATUS="+str(exitstatus)
예제 #35
0
 def __init__(self):
     Sim.__init__(self)
     self.history = History()
예제 #36
0
class Simulator(Sim):
    def __init__(self):
        Sim.__init__(self)
        self.history = History()
                    
    def handleErr(self, desc): # TODO:
        return
    
    def simLog(self, s):
        if self.isGuimode:
            return
        if self.logfile != None:
            self.logfile.write("%s\n" % (s))
        if self.isOnScreen or self.logfile == None:
            print s
            return

    def showStatTitle(self):  
        if self.isGuimode:
            return
        self.simLog('Cycle_%d' % self.cycle)
        self.simLog('--------------------')
        
    def showStat(self):
        if self.isGuimode:
            return
        self.simLog('FETCH:')
        self.simLog('\tF_predPC \t= 0x%s\n' % int_to_hexStr(self.F_predPC, 8))
        
        self.simLog('DECODE:')
        self.simLog('\tD_icode  \t= 0x%s' % int_to_hexStr(self.D_icode))
        self.simLog('\tD_ifun   \t= 0x%s' % int_to_hexStr(self.D_ifun))
        self.simLog('\tD_rA     \t= 0x%s' % int_to_hexStr(self.D_rA))
        self.simLog('\tD_rB     \t= 0x%s' % int_to_hexStr(self.D_rB))
        self.simLog('\tD_valC   \t= 0x%s' % int_to_hexStr(self.D_valC, 8))
        self.simLog('\tD_valP   \t= 0x%s\n' % int_to_hexStr(self.D_valP, 8))
        
        self.simLog('EXECUTE:')
        self.simLog('\tE_icode  \t= 0x%s' % int_to_hexStr(self.E_icode))
        self.simLog('\tE_ifun   \t= 0x%s' % int_to_hexStr(self.E_ifun))
        self.simLog('\tE_valC   \t= 0x%s' % int_to_hexStr(self.E_valC, 8))
        self.simLog('\tE_valA   \t= 0x%s' % int_to_hexStr(self.E_valA, 8))
        self.simLog('\tE_valB   \t= 0x%s' % int_to_hexStr(self.E_valB, 8))
        self.simLog('\tE_dstE   \t= 0x%s' % int_to_hexStr(self.E_dstE))
        self.simLog('\tE_dstM   \t= 0x%s' % int_to_hexStr(self.E_dstM))
        self.simLog('\tE_srcA   \t= 0x%s' % int_to_hexStr(self.E_srcA))
        self.simLog('\tE_srcB   \t= 0x%s\n' % int_to_hexStr(self.E_srcB))
        
        self.simLog('MEMORY:')
        self.simLog('\tM_icode  \t= 0x%s' % int_to_hexStr(self.M_icode))
        self.simLog('\tM_Bch    \t= %s' % self.M_Cnd)
        self.simLog('\tM_valE   \t= 0x%s' % int_to_hexStr(self.M_valE, 8))
        self.simLog('\tM_valA   \t= 0x%s' % int_to_hexStr(self.M_valA, 8))
        self.simLog('\tM_dstE   \t= 0x%s' % int_to_hexStr(self.M_dstE))
        self.simLog('\tM_dstM   \t= 0x%s\n' % int_to_hexStr(self.M_dstM))
        
        self.simLog('WRITE BACK:')
        self.simLog('\tW_icode  \t= 0x%s' % int_to_hexStr(self.W_icode))
        self.simLog('\tW_valE   \t= 0x%s' % int_to_hexStr(self.W_valE, 8))
        self.simLog('\tW_valM   \t= 0x%s' % int_to_hexStr(self.W_valM, 8))
        self.simLog('\tW_dstE   \t= 0x%s' % int_to_hexStr(self.W_dstE))
        self.simLog('\tW_dstM   \t= 0x%s\n' % int_to_hexStr(self.W_dstM))
    
    def pipeCtr(self):
        # F_stall
        if IRET in (self.D_icode, self.E_icode, self.M_icode) or \
            (self.E_icode in (IMRMOVL, IPOPL) and \
            self.E_dstM in (self.d_srcA, self.d_srcB)):
            self.F_stall = True
            
        # D_stall and D_bub
        if self.E_icode in (IMRMOVL, IPOPL) and self.E_dstM in (self.d_srcA, self.d_srcB):
            self.D_stall = True # stall
        elif (self.E_icode==IJXX and not self.e_Cnd) or \
            not (self.E_icode in (IMRMOVL, IPOPL) and self.E_dstM in (self.d_srcA, self.d_srcB)) \
            and IRET in (self.D_icode, self.E_icode, self.M_icode):
            self.D_bub = True
            
        # E_bub
        if (self.E_icode == IJXX and not self.e_Cnd) or \
            self.E_icode in (IMRMOVL, IPOPL) and \
            self.E_dstM in (self.d_srcA, self.d_srcB):
            self.E_bub = True
    
    def writeF(self):
        if self.F_stall:
            self.F_stall = False
            return  # stall
        self.F_currentPC = self.F_predPC
        self.F_predPC = self.f_predPC
        self.F_stat = 'AOK'

    def stageF(self):
        f_pc = self.F_predPC

        if self.M_icode == IJXX and not self.M_Cnd:
            f_pc = self.M_valA
        elif self.W_icode == IRET:
            f_pc = self.W_valM
        old_pc = f_pc
        pcstart = f_pc * 2
        imem_error = False
        instr = self.memory.getByte(f_pc)
        imem_icode = hi4(instr)
        imem_ifun = lo4(instr)
        if self.isSecond:
            if imem_icode == 0x1:
                imem_icode = INOP
            elif imem_icode == 0x0:
                imem_icode = IHALT
        pcstart += 2
        f_pc += 1
        self.f_icode = INOP if imem_error else imem_icode
        self.f_ifun = FNONE if imem_error else imem_ifun
        instr_valid =  self.f_icode in (INOP, IHALT, IRRMOVL, IIRMOVL, IRMMOVL, IMRMOVL, \
                                   IOPL, IJXX, ICALL, IRET, IPUSHL, IPOPL, IIADDL, ILEAVE)
        if instr_valid:
            try:
                if self.f_icode in (IRRMOVL, IOPL, IPUSHL, IPOPL, \
                               IIRMOVL, IRMMOVL, IMRMOVL, IIADDL):
                    regids = self.memory.getByte(f_pc)
                    self.f_rA = hi4(regids)
                    self.f_rB = lo4(regids)
                    if self.isSecond:
                        if self.f_rA == 0xf:
                            self.f_rA = RNONE
                        if self.f_rB == 0xf:
                            self.f_rB = RNONE
                    pcstart += 2
                    f_pc += 1
                else:
                    self.f_rA = RNONE
                    self.f_rB = RNONE
                if (self.f_rA not in regname.keys() and self.f_rA != RNONE) or \
                    (self.f_rB not in regname.keys() and self.f_rB != RNONE):
                    imem_error = True
            except:
                imem_error = True
            self.f_valC = 0x0
            try:
                if self.f_icode in (IIRMOVL, IRMMOVL, IMRMOVL, IJXX, ICALL, IIADDL):
                    self.f_valC = self.memory.getWord(f_pc)
                    pcstart += 8
                    f_pc += 4
            except:
                imem_error = True
        if not instr_valid:
            self.handleErr({'what':'instr-not-valid', 'imem_icode':imem_icode, \
                            'imem_ifun':imem_ifun})
        self.f_valP = f_pc
        self.f_predPC = self.f_valC if self.f_icode in (IJXX, ICALL) else self.f_valP         
        self.f_stat = 'AOK'
        if imem_error:
            self.f_stat = 'ADR'
        if not instr_valid:
            self.f_stat = 'INS'
        if self.f_icode == IHALT:
            self.f_stat = 'HLT'

    def writeD(self):
        if self.D_stall:
            self.D_stall = False
            return
        if self.D_bub:
            self.D_bub = False
            self.D_icode = INOP
            self.D_ifun = FNONE
            self.D_rA = RNONE
            self.D_rB = RNONE
            self.D_valC = 0x0
            self.D_valP = 0x0
            self.D_stat = 'BUB'
            return
        self.D_stat = self.f_stat
        self.D_icode = self.f_icode
        self.D_ifun = self.f_ifun
        self.D_rA = self.f_rA
        self.D_rB = self.f_rB
        self.D_valC = self.f_valC
        self.D_valP = self.f_valP
        self.D_currentPC = self.F_currentPC

    def stageD(self):
        self.d_srcA = RNONE
        if self.D_icode in (IRRMOVL, IRMMOVL, IOPL, IPUSHL):
            self.d_srcA = self.D_rA
        elif self.D_icode in (IPOPL, IRET):
            self.d_srcA = RESP
        elif self.D_icode == ILEAVE:
            self.d_srcA = REBP
        self.d_srcB = RNONE
        if self.D_icode in (IOPL, IRMMOVL, IMRMOVL, IIADDL):
            self.d_srcB = self.D_rB
        elif self.D_icode in (IPUSHL, IPOPL, ICALL, IRET):
            self.d_srcB = RESP
        self.d_dstE = RNONE
        if self.D_icode in (IRRMOVL, IIRMOVL, IOPL, IIADDL):
            self.d_dstE = self.D_rB
        elif self.D_icode in (IPUSHL, IPOPL, ICALL, IRET, ILEAVE):
            self.d_dstE = RESP
        self.d_dstM = RNONE
        if self.D_icode in (IMRMOVL, IPOPL):
            self.d_dstM = self.D_rA
        elif self.D_icode == ILEAVE:
            self.d_dstM = REBP
        self.d_valA = self.register[self.d_srcA]
        if self.D_icode in (ICALL, IJXX):
            self.d_valA = self.D_valP
        elif self.d_srcA == self.e_dstE:
            self.d_valA = self.e_valE
        elif self.d_srcA == self.M_dstM:
            self.d_valA = self.m_valM
        elif self.d_srcA == self.M_dstE:
            self.d_valA = self.M_valE
        elif self.d_srcA == self.W_dstM:
            self.d_valA = self.W_valM
        elif self.d_srcA == self.W_dstE:
            self.d_valA = self.W_valE
        self.d_valB = self.register[self.d_srcB]
        if self.d_srcB == self.e_dstE:
            self.d_valB = self.e_valE
        elif self.d_srcB == self.M_dstM:
            self.d_valB = self.m_valM
        elif self.d_srcB == self.M_dstE:
            self.d_valB = self.M_valE
        elif self.d_srcB == self.W_dstM:
            self.d_valB = self.W_valM
        elif self.d_srcB == self.W_dstE:
            self.d_valB = self.W_valE

    def writeE(self):
        if self.E_bub:
            self.E_bub = False
            self.E_icode = INOP
            self.E_ifun = FNONE
            self.E_valC = 0x0
            self.E_valA = 0x0
            self.E_valB = 0x0
            self.E_dstE = RNONE
            self.E_dstM = RNONE
            self.E_srcA = RNONE
            self.E_srcB = RNONE
            self.E_stat = 'BUB'
            return
        self.E_stat = self.D_stat
        self.E_icode = self.D_icode
        self.E_ifun = self.D_ifun
        self.E_valC = self.D_valC
        self.E_valA = self.d_valA
        self.E_valB = self.d_valB
        self.E_dstE = self.d_dstE
        self.E_dstM = self.d_dstM
        self.E_srcA = self.d_srcA
        self.E_srcB = self.d_srcB
        self.E_currentPC = self.D_currentPC

    def stageE(self):
        aluA = 0
        if self.E_icode in (IRRMOVL, IOPL, ILEAVE):
            aluA = self.E_valA
        elif self.E_icode in (IIRMOVL, IRMMOVL, IMRMOVL, IIADDL):
            aluA = self.E_valC
        elif self.E_icode in (ICALL, IPUSHL):
            aluA = -4
        elif self.E_icode in (IRET, IPOPL):
            aluA = 4
        aluB = 0
        if self.E_icode in (IRMMOVL, IMRMOVL, IOPL, ICALL, \
                       IPUSHL, IRET, IPOPL, IIADDL):
            aluB = self.E_valB
        elif self.E_icode == ILEAVE:
            aluB = 4
        alufun = self.E_ifun if self.E_icode == IOPL else ALUADD
        alures = 0
        aluchar = '+'
        if alufun == ALUADD:
            alures = aluB + aluA
            aluchar = '+'
        elif alufun == ALUSUB:
            alures = aluB - aluA
            aluchar = '-'
        elif alufun == ALUAND:
            alures = aluB & aluA
            aluchar = '&'
        elif alufun == ALUXOR:
            alures = aluB ^ aluA
            aluchar = '^'
        self.e_setcc =  self.E_icode in (IOPL, IIADDL) and \
                   self.m_stat not in ('ADR', 'INS', 'HLT') and \
                   self.W_stat not in ('ADR', 'INS', 'HLT')
        if self.e_setcc:
            self.condcode['ZF'] = 1 if alures == 0 else 0
            self.condcode['SF'] = 1 if alures < 0 else 0
            self.condcode['OF'] = 0
            if (self.E_ifun == ALUADD) and \
                ((aluB > 0 and aluA > 0 and alures < 0) or \
                  aluB < 0 and aluB < 0 and alures > 0):
                self.condcode['OF'] = 1
            if (self.E_ifun == ALUSUB) and \
                ((aluB > 0 and aluA < 0 and alures < 0) or \
                  aluB < 0 and aluB > 0 and alures > 0):
                self.condcode['OF'] = 1
        self.e_Cnd = False
        if self.E_icode == IJXX or self.E_icode == IRRMOVL:
            zf = self.condcode['ZF']
            sf = self.condcode['SF']
            of = self.condcode['OF']
            if self.E_ifun == FJMP:
                self.e_Cnd = True
            elif self.E_ifun == FJLE and (sf ^ of) | zf == 1:
                self.e_Cnd = True
            elif self.E_ifun == FJL and sf ^ of == 1:
                self.e_Cnd = True
            elif self.E_ifun == FJE and zf == 1:
                self.e_Cnd = True
            elif self.E_ifun == FJNE and zf == 0:
                self.e_Cnd = True
            elif self.E_ifun == FJGE and sf ^ of == 0:
                self.e_Cnd = True
            elif self.E_ifun == FJG and (sf ^ of) | zf == 0:
                self.e_Cnd = True
        self.e_valE = alures
        self.e_dstE = self.E_dstE
        if self.E_icode == IRRMOVL and not self.e_Cnd:
            self.e_dstE = RNONE

    def writeM(self):
        if self.m_stat in ('ADR', 'INS', 'HLT') or \
            self.W_stat in ('ADR', 'INS', 'HLT'):
            self.M_stat = 'BUB'
            self.M_icode = INOP
            self.M_ifun = FNONE
            self.M_Cnd = False
            self.M_valE = 0x0
            self.M_valA = 0x0
            self.M_dstE = RNONE
            self.M_dstM = RNONE
            return
        self.M_stat = self.E_stat
        self.M_icode = self.E_icode
        self.M_ifun = self.E_ifun
        self.M_Cnd = self.e_Cnd
        self.M_valE = self.e_valE
        self.M_valA = self.E_valA
        self.M_dstE = self.e_dstE
        self.M_dstM = self.E_dstM
        self.M_currentPC = self.E_currentPC

    def stageM(self):
        self.m_valM = 0
        self.mem_addr = 0
        self.dmem_error = False
        if self.M_icode in (IRMMOVL, IPUSHL, ICALL, IMRMOVL): # write
            self.mem_addr = self.M_valE
        elif self.M_icode in (IPOPL, IRET, ILEAVE): # read, get addr
            self.mem_addr = self.M_valA
        if self.M_icode in (IMRMOVL, IPOPL, IRET, ILEAVE): # read
            try:
                self.m_valM = self.memory.getWord(self.mem_addr)
                self.m_read = True
            except:
                self.dmem_error = True
        if self.M_icode in (IRMMOVL, IPUSHL, ICALL): # write
            try:
                self.memory.setWord(self.mem_addr, self.M_valA)
            except:
                self.dmem_error = True
        self.m_stat = 'ADR' if self.dmem_error else self.M_stat

    def writeW(self):
        if self.W_stat in ('ADR', 'INS', 'HLT'):
            return
        self.W_stat = self.m_stat
        self.W_icode = self.M_icode
        self.W_ifun = self.M_ifun
        self.W_valE = self.M_valE
        self.W_valM = self.m_valM
        self.W_dstE = self.M_dstE
        self.W_dstM = self.M_dstM
        self.W_currentPC = self.M_currentPC

    def stageW(self):
        if self.W_dstE != RNONE:
            self.register[self.W_dstE] = self.W_valE
        if self.W_dstM != RNONE:
            self.register[self.W_dstM] = self.W_valM
        self.cpustat = 'AOK' if self.W_stat == 'BUB' else self.W_stat

    def step(self):
        if self.maxCycle != 0 and self.cycle > self.maxCycle:
            self.simLog('Reach Max Cycle')
            self.cpustat = 'HLT'
            return       
        self.showStatTitle()
        self.pipeCtr()
        
        self.writeW() # take care of orders if u wanna save some intermediate vals
        self.writeM()
        self.writeE()
        self.writeD()
        self.writeF()
        
        self.stageW()
        self.stageM()
        self.stageE()
        self.stageD()
        self.stageF()
        self.showStat()
        self.history.record(self)
        self.cycle += 1
        
        if self.cpustat != 'AOK' and self.cpustat != 'BUB':
            self.isTerminated = True
            return False
        else: 
            return True
    
    def back(self):
        tmp = self.history.back(self.cycle-1)
        if tmp==False or tmp==None:
            self.simLog('out of history\'s reach')
            return
        else:
            self.isTerminated = False
            self.copy(tmp)
            self.showStatTitle()
            self.showStat()
            self.cycle += 1
            
        
    def load(self, fin, fout=None):
        # prepare    
        self.cycle = 0
        self.yasbin = ''
        inputName = fin.name
        prefixName = os.path.splitext(inputName)[0]
        if fout==None and not self.isNoLogFile:
            outputName = prefixName + '.txt'
            try:
                self.logfile = open(outputName, 'w')
            except IOError:
                self.handleErr({'what':'cannot open a logfile to write'})
                raise
        else:
            self.logfile = fout
            outputName = fout.name
        if not self.isNoLogFile and not self.isGuimode:
            print('Log file: %s' % (outputName))
            
        # load    
        # TODO: how to load both bin and non-bin
        for str_line in fin.readlines():
            str_valid = str_line
            str_valid = re.sub(r'\|.*','',str_valid)
            str_valid = str_valid.strip(' \n\r\t')
            if str_valid == '':
                continue
            tokens = str_valid.split(':')
            if tokens[1] == '':
                continue
            addr = int(tokens[0].strip(' '), 16)
            content_str = tokens[1].strip(' ')
            self.yasbin += content_str
            content_bytes = str_to_bytes(content_str)
            self.memory.setBytesThrough( addr, content_bytes)
        self.binlen = len(self.yasbin)   
        
    def run(self):
        try:       
            while True:
                if self.isGoing:
                    if not self.step():
                        break
                    time.sleep(self.interval)
            self.logfile.close()
        except:
            self.simLog('Error: bad input binary file')
            self.logfile.close()
            raise
        
    def getMemory(self, addr):
        return self.memory.mem[addr]
    
    def getMemoryChange(self):
        return self.memory.memChange    
            
    def getCache(self, setIndex, lineIndex):
        entrySize = self.memory.cache.E
        line = self.memory.cache.set[setIndex*entrySize+lineIndex]
        return line.isValid, line.isDirty, line.tag, line.block

    def setCacheParams(self, S, E, B, m):
        self.memory.setCache(S, E, B, m)
        
    '''''''''''''''''
    '    trivial    '
    '''''''''''''''''