Exemplo n.º 1
0
def generate_null_distribution(seq_x,seq_y, scoring_matrix, num_trials):
    retdic = {}
    #cnt = 0
    while num_trials > 0:
        #seq_y = random.shuffle(seq_y)
        #seq_y = ''.join(random.sample(seq_y,len(seq_y)))
        l = list(seq_y)
        random.shuffle(l)
        seq_y = ''.join(l) 
        alignment_matrix = PR.compute_alignment_matrix(seq_x, seq_y, scoring_matrix, False)
        #print alignment_matrix
        res = PR.compute_local_alignment(seq_x, seq_y, scoring_matrix, alignment_matrix)
        
        #calc MAX
        '''vals = []
        for fst in alignment_matrix:
            vals.append(max(fst))
        ith = vals.index(max(vals))
        jth = alignment_matrix[ith].index(max(alignment_matrix[ith])) '''
        
        #print "ALI = ", alignment_matrix[ith][jth]
        #print "res = ", res[0]
        #print "------------"
        #ali0 = alignment_matrix[ith][jth] #~!!!!!!!!!!!!!!!!!!!!!!!!!!
        #print "score = ", res[0]
        if retdic.has_key(res[0]):
            temp = retdic[res[0]]
            retdic[res[0]] = temp+1
        else:
            retdic[res[0]] = 1
        #cnt += 1
        num_trials -= 1    
    return retdic    
Exemplo n.º 2
0
def _removePreviewObjFiles(fpath):
    objectFilePaths = ['build/'+fpath+'.o',
            'build/nacl/build/'+fpath+'.o']
    for obj in objectFilePaths:
        Project.removeFile(obj)
        pass
    pass
Exemplo n.º 3
0
 def testUS17(self):
     self.assertEqual(Project.US17("@I1@", "@I2@", []), True)
     self.assertEqual(Project.US17("@I1@", "@I2@", ["@I1@"]), False)
     self.assertEqual(Project.US17("@I1@", "@I2@", ["@I2@"]), False)
     self.assertEqual(Project.US17("@I1@", "@I2@", ["@I3@", "@I4@"]), True)
     self.assertEqual(
         Project.US17("@I1@", "@I2@", ["@I3@", "@I4@", "@I2@"]), False)
Exemplo n.º 4
0
 def load(self, fileName, resetViews=True, setSaved=True):
     self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
     self.reset(resetViews=resetViews)
     self.currentProj = Project(fileName)
     self.projDir = self.currentProj.dir
     self.lib = self.currentProj.lib
     
     #make sure we get updated versions of assets
     ModelPool.releaseAllModels()
     TexturePool.releaseAllTextures()
     ShaderPool.releaseAllShaders()
     
     self.currentSceneName = self.currentProj.sceneName
     self.fileMgr.loadFromFile(self.projDir + '/' +self.currentProj.getScene(self.currentSceneName).getFullpath())
     self.fileMgr.loadJournalFromFile(self.projDir+'/'+self.currentProj.journalFilename.getFullpath())
     self.fileMgr.loadInventoryMapFromFile(self.projDir+'/'+self.currentProj.inventoryMapFilename.getFullpath())
     if setSaved:
         self.saved = True
     
     #self.currenScene = self.currentProj.sceneFilename
     self.ui.scenesUI.populateTreeFromScenes()
     
     self.objectMgr.updateMainCharWidget() #[antonjs 4/14/11]
     
     self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
Exemplo n.º 5
0
 def newProj(self):
     if self.tempDir and os.path.exists(self.tempDir):
         shutil.rmtree(self.tempDir)
     self.tempDir = os.path.join(Util.getTempDir(), 'NewProj')
     if os.path.exists(self.tempDir):
         for root, dirs, files in os.walk(self.tempDir):
             for f in files:
                 file = os.path.join(root, f)
                 fileAtt = os.stat(file)[0]
                 if (not fileAtt & stat.S_IWRITE):
                     os.chmod(file, stat.S_IWRITE)
                 
         shutil.rmtree(self.tempDir)
     
     projFile = Filename.fromOsSpecific(self.tempDir) + '/New Project.proj'
     self.currentProj = Project(projFile, "New Project")
     #defaultSceneName = "default"
     #self.currentProj.addScene(defaultSceneName, 
     #                          Filename(defaultSceneName+'.scene'))#Filename(projFile.getBasenameWoExtension() + '.scene'))
     #current Scene that the objectMgr manages and saves to
     #self.currentScene = self.currentProj.sceneFilename
     self.currentSceneName = self.currentProj.sceneName
     self.ui.scenesUI.populateTreeFromScenes()#add(defaultSceneName)
     self.projDir = self.currentProj.dir
     self.lib = self.currentProj.lib
     self.saved = False
     self.ui.libraryUI.update()
     self.ui.storyObjUI.update()
     self.ui.soundUI.update()
Exemplo n.º 6
0
def parseMethodName(project):
	print(project)
	if(len(sys.argv)>1):
		cmd2=sys.argv[2]
	else:
		while True:
			cmd2=input("Enter method to be called.\n")
			if cmd2 == "Add":
				project.addTask()
				
			elif cmd2 == "Complete":
				project.completeTask()
				
			elif cmd2 == "Next":
				project.nextTask()
				
			elif cmd2 == "Show":
				project.showTasks()
				
			elif cmd2 == "Showc":
				project.showCompletedTasks()
				
			else:
				print("That is not a valid task.\n")
				parseMethodName(project)
Exemplo n.º 7
0
    def __init__(self, *args, **kw):
        super(BaseWindow, self).__init__(*args, **kw)
        self.Maximize(True)
        self.currentDirectory = os.getcwd()
        self.project = Project()
        self.pnl = wx.Panel(self,
                            size=self.Size,
                            style=wx.TAB_TRAVERSAL | wx.BORDER_SUNKEN)
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        collap = wx.Panel(self.pnl,
                          size=(260, self.Size[1]),
                          style=wx.TAB_TRAVERSAL | wx.BORDER_SUNKEN)
        self.hintPnl = HintPanel(collap)
        self.logPnl = ConsolePanel(collap)

        self.moduleManager = ModuleManager(self.pnl, self.project, self.logPnl)
        self.aux = Project()
        # create the menu bar that we don't need yet
        self.makeMenuBar(self.logPnl)
        csizer = wx.BoxSizer(wx.VERTICAL)

        csizer.Add(self.hintPnl)
        csizer.Add(self.logPnl)

        collap.SetSizer(csizer)

        # create the status bar
        self.CreateStatusBar()
        self.SetStatusText("")
        self.sizer.Add(collap)
        self.sizer.Add(self.moduleManager)
        self.pnl.SetSizer(self.sizer)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
Exemplo n.º 8
0
def _removePreviewObjFiles(fpath):
    objectFilePaths = [
        'build/' + fpath + '.o', 'build/nacl/build/' + fpath + '.o'
    ]
    for obj in objectFilePaths:
        Project.removeFile(obj)
        pass
    pass
Exemplo n.º 9
0
 def testUS11(self):
     self.assertEqual(Project.US11("4 JUL 1996", "N/A", "N/A"), False)
     self.assertEqual(Project.US11("4 JUL 1996", "4 SEP 1962", "N/A"), True)
     self.assertEqual(Project.US11("4 JUL 1997", "N/A", "4 SEP 1962"), True)
     self.assertEqual(
         Project.US11("4 JUL 1996", "5 JUL 1962", "4 JAN 1996"), True)
     self.assertEqual(Project.US11("4 JUL 1996", "3 JUL 1998", "N/A"),
                      False)
Exemplo n.º 10
0
 def testUS14(self):
     self.assertEqual(Project.US14(["4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996"]), True)
     self.assertEqual(Project.US14(["4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "3 MAR 1995"]), True)
     self.assertEqual(Project.US14(["4 JUL 1996"]), True)
     self.assertEqual(
         Project.US14(["4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 May 1996"]), True)
     self.assertEqual(
         Project.US14(["4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996", "4 JUL 1996"]), False)
Exemplo n.º 11
0
 def test_US15(self):
     self.assertTrue(Project.US15(['@I10@', '@I11@']))
     self.assertFalse(Project.US15(['@I10@', '@I11@', '@I1@', '@I2@', '@I3@', '@I4@', '@I5@', '@I6@', '@I7@',
                                    '@I8@', '@I9@', '@I12@', '@I13@', '@I14@', '@I15@']))
     self.assertTrue(Project.US15('N/A'))
     self.assertFalse(Project.US15(['@I10@', '@I11@', '@I1@', '@I2@', '@I3@', '@I4@', '@I5@', '@I6@', '@I7@',
                                    '@I8@', '@I9@', '@I12@', '@I13@', '@I14@', '@I15@', '@I16@']))
     self.assertTrue(Project.US15([]))
Exemplo n.º 12
0
def bugIdToBug(bugId):
    bugId = bugId.lower()
    project = None
    if bugId[1] == "m":
        project = Project.Project("math")
    else:
        project = Project.Project("lang")
    return Bug.Bug(project, bugId)
Exemplo n.º 13
0
 def test_US05(self):
     self.assertEqual(Project.US05("4 JUL 1996", "3 JUL 2001", "N/A"), True)
     self.assertEqual(Project.US05("4 JUL 1996", "N/A", "N/A"), True)
     self.assertEqual(
         Project.US05("4 JUL 1996", "3 JUL 2001", "3 JUL 1967"), False)
     self.assertEqual(Project.US05("4 JUL 1996", "3 JUL 1996", "N/A"),
                      False)
     self.assertEqual(
         Project.US05("4 JUL 1996", "3 JUL 2001", "3 APR 2005"), True)
Exemplo n.º 14
0
 def test_US09(self):
     self.assertTrue(
         Project.US09("9 MAY 1910", "10 FEB 1900", "24 MAR 1900"))
     self.assertFalse(
         Project.US09("9 MAY 1960", "10 FEB 1970", "24 MAR 2005"))
     self.assertTrue(
         Project.US09("15 SEP 1972", "10 OCT 1971", "20 FEB 1972 "))
     self.assertFalse(
         Project.US09("27 JAN 1990", "26 JAN 1980", "22 JAN 1985"))
     self.assertTrue(Project.US09("1 DEC 1975", "1 DEC 1975", "1 DEC 1975"))
Exemplo n.º 15
0
 def testUS08(self):
     self.assertEqual(
         Project.US08("4 JUL 1996", "4 SEP 1962", "4 SEP 2000"), True)
     self.assertEqual(Project.US08("4 JUL 1996", "4 SEP 1962", "N/A"), True)
     self.assertEqual(Project.US08("4 JUL 1997", "4 SEP 2000", "N/A"),
                      False)
     self.assertEqual(
         Project.US08("4 JUL 1996", "5 JUL 1962", "4 JAN 1996"), True)
     self.assertEqual(
         Project.US08("4 JUL 1996", "3 JUL 1962", "4 SEP 1990"), False)
Exemplo n.º 16
0
 def test_US06(self):
     self.assertFalse(
         Project.US06("9 MAY 2000", "10 FEB 1900", "24 MAR 1905"))
     self.assertTrue(
         Project.US06("9 MAY 2000", "10 FEB 2004", "24 MAR 2005"))
     self.assertTrue(
         Project.US06("15 SEP 1972", "10 OCT 2002", "30 AUG 1980"))
     self.assertFalse(
         Project.US06("27 JAN 1990", "26 JAN 1990", "22 JAN 1990"))
     self.assertTrue(Project.US06("1 DEC 1975", "1 DEC 1975", "1 DEC 1975"))
Exemplo n.º 17
0
 def get_Ekin_data(self):
     """Open the Ekin data from an ekin proj file"""
     ekinfilename='sampled66a.Ekinprj'        
     ekinfile=os.getcwd()
     print 'opened Ekin project: '+ekinfilename
     P = Project()
     self.plotdata,self.fit_data = P.open_project_nogui(filename=os.path.join(ekinfile,ekinfilename))        
     #print self.plotdata
     #print self.fit_data
     return
Exemplo n.º 18
0
 def testUS23(self):
     p_dict = {}
     p_dict["1"] = ["Bill /Smith/", "M", "6 May 1930", "90", "True", "N/A", "N/A", "N/A"]
     p_dict["2"] = ["Carol /Jones/", "F", "6 May 1932", "88", "True", "N/A", "N/A", "N/A"]
     
     self.assertEqual(Project.US23(p_dict, "Bill /Smith/", "6 May 1930"), False)
     self.assertEqual(Project.US23(p_dict, "Carol /Jones/", "6 May 1932"), False)
     self.assertEqual(Project.US23(p_dict, "Carol /Jones/", "6 May 1930"), True)
     self.assertEqual(Project.US23(p_dict, "Bill /Smith/", "6 May 1932"), True)
     self.assertEqual(Project.US23(p_dict, "Tom /Hanks/", "6 May 1937"), True)
Exemplo n.º 19
0
 def get_Ekin_data(self):
     """Open the Ekin data from an ekin proj file"""
     ekinfilename = 'sampled66a.Ekinprj'
     ekinfile = os.getcwd()
     print 'opened Ekin project: ' + ekinfilename
     P = Project()
     self.plotdata, self.fit_data = P.open_project_nogui(
         filename=os.path.join(ekinfile, ekinfilename))
     #print self.plotdata
     #print self.fit_data
     return
Exemplo n.º 20
0
 def test_US02(self):
     self.assertEqual(
         Project.US02("4 JUL 1996", "4 SEP 1962", "4 SEP 1962"), True)
     self.assertEqual(
         Project.US02("4 JUL 1996", "4 SEP 2000", "4 SEP 1962"), False)
     self.assertEqual(
         Project.US02("4 JUL 1996", "4 SEP 1996", "4 SEP 1962"), False)
     self.assertEqual(
         Project.US02("4 JUL 1996", "5 JUL 1996", "4 SEP 1962"), False)
     self.assertEqual(
         Project.US02("4 JUL 1996", "3 JUL 1996", "4 SEP 1962"), True)
Exemplo n.º 21
0
def createNewProject(evData):
    in_path = tkFileDialog.asksaveasfilename(initialfile='project.json')

    if len(in_path) != 0:
        _pushProjectToRecentList(in_path)

        # Create new project!
        Project.createNewProject(in_path)
        pass

    return in_path
Exemplo n.º 22
0
def createNewProject(evData):
    in_path = tkFileDialog.asksaveasfilename(initialfile='project.json')

    if len(in_path)!=0:
        _pushProjectToRecentList(in_path)

        # Create new project!
        Project.createNewProject(in_path)
        pass

    return in_path
Exemplo n.º 23
0
def check_spelling(checked_word, dist, word_list):
    matrix = PR.build_scoring_matrix(alphabet, 2 ,1, 0)
    retlist = []
    str1 = checked_word
    for ith in word_list:
        str2 = ith
        alig = PR.compute_alignment_matrix(str1, str2, matrix, True)
        res = PR.compute_global_alignment(str1, str2, matrix, alig)
        edit_dist = len(str1)+len(str2)-res[0]
        if edit_dist <= dist:
            retlist.append(str2)
    return retlist
Exemplo n.º 24
0
    def __init__(self):
        super().__init__()

        # Check requirements
        if not self.check_requirements():
            self.call_message_box(
                txt='Missing gcc compiler',
                info='Please install gcc and make sure it is in system PATH',
                title='Missing gcc'
            )

        self.setupUi()
        self.project = Project()
Exemplo n.º 25
0
 def mostRecentDependencyTime(self):
     mostRecentTime = self.getModificationTime()
     for dependency in self.persistent_fields['dependencies']:
         if Project.fileExists(dependency):
             depTime = Project.getModificationTime(dependency)
             if depTime > mostRecentTime:
                 mostRecentTime = depTime
                 pass
         else:
             # The dependency was removed! Since we dont know when, lets
             # just assumed it happened right now
             mostRecentTime = time.gmtime()
             pass
         pass
     return mostRecentTime
Exemplo n.º 26
0
 def mostRecentDependencyTime(self):
     mostRecentTime = self.getModificationTime()
     for dependency in self.persistent_fields['dependencies']:
         if Project.fileExists(dependency):
             depTime = Project.getModificationTime(dependency)
             if depTime > mostRecentTime:
                 mostRecentTime = depTime
                 pass
         else:
             # The dependency was removed! Since we dont know when, lets
             # just assumed it happened right now
             mostRecentTime = time.gmtime()
             pass
         pass
     return mostRecentTime
Exemplo n.º 27
0
def ProjectPage(name):
    if request.method == "GET":
        if "user" in session:
            usr = session["user"]
            PID, Pname = CH.CheckDB(usr)
            PB = CH.CheckMetadata(PID)
            print(PB)
            Number = len(PID)
            app.logger.info(PB)
            return render_template("/home.html", user=usr, ID=PID, Name=Pname, Length = Number, PB=PB)
    elif request.method == "POST":
        ProjectName = request.form["ProjectNameInput"]
        CH.GenProject(session["user"], ProjectName)
        app.logger.info("CreateProject")
        return redirect("/org/{}/project".format(session["user"]))
Exemplo n.º 28
0
def testUserScores(testFiles, weights):
    """
     predict the score of the test set using corresponding user average scores
    """
    neededFiles = [testFiles[REVIEW], testFiles[USER]]
    print 'importing test reviews and users'
    reviewsList, usersList = Project.importJSONFiles(neededFiles)
    print 'building dictionary of test users'
    userAvgs = {}
    for user in usersList:
        userID = user['user_id']
        userAvgs[userID] = {}
        thisUser = userAvgs[userID]
        thisUser['useful'] = user['votes']['useful'] / float(user['review_count'])
        thisUser['funny']  = user['votes']['funny']  / float(user['review_count'])
        thisUser['cool']   = user['votes']['cool']   / float(user['review_count'])

    # Dictionaries raise a "KeyError" if you try to access a key not in them
    defaultDict = {'useful': 0, 'funny': 0, 'cool': 0}

    print 'building matrix'
    testList = []
    for review in reviewsList:
        thisUser = userAvgs.get(review['user_id'], defaultDict)
        testList += [(1, thisUser['useful'], thisUser['funny'], thisUser['cool'])]

    testMatrix = np.asmatrix(testList)

    predictedScores = predictScores(testMatrix, weights)
Exemplo n.º 29
0
def _init():
    global lang
    global package
    global currentFile
    global fileType
    currentFile = Editor.currentFile()
    fileType = currentFile[-2:]
    if not Editor.isValid() or currentFile == '':
        return
    lang = Project.targetLangCode()
    (path, pofilename) = os.path.split(Editor.currentFile())
    (package, ext) = os.path.splitext(pofilename)
    currentFile = Editor.currentFile()
    if fileType == 'po':
        complilerPresent = cmd_exists('msgfmt')
        if complilerPresent:
            saveSameFolder()
        else:
            os.system('kdialog --sorry \
                "The command <msgfmt> is not available.\nYou need to install the gettext package"')
            return
    # Alert for the wrong extension
    else:
        os.system('kdialog --sorry \
                "This format is not supported"')
def Fill_from_xmlfile(filename):

    tree = ET.parse(filename)
    doc = tree.getroot()
    NAME = None
    BUGET = None
    PGA = None
    Countries = []

    for child in doc:

        if child.tag == "{http://cordis.europa.eu}acronym":
            NAME = child.text

        if child.tag == "{http://cordis.europa.eu}ecMaxContribution":
            BUGET = child.text

    Countries = (look_for_countries(doc))

    PGA = look_for_pga(doc)

    if NAME is None:
        raise ValueError("The file", filename, "doest have a name of project.")

    if BUGET is None:
        raise ValueError("The file", filename, "doest have a buget.")

    if Countries == []:
        raise ValueError("The file", filename, "doest have any country.")

    if PGA == None:
        return None

    return Project(NAME, to_int(BUGET), Countries, PGA)
Exemplo n.º 31
0
    def update(self):
        from server.build import BuildEventHandler

        def buildCallback(output, message, returncode):
            if returncode != 0:
                self.isBroken = True
            else:
                self.isBroken = False
                pass
            pass

        # Generate its .o object if the path refers to a cpp file
        if Utils.IsImplementationFile(self.path):
            BuildEventHandler.BuildPreviewObject(self.path, buildCallback)
            # Update dependency list
            self.getMetadata()
        elif Utils.IsHeaderFile(self.path):
            # The file was updated. Re-generate its Factory file.
            if self.persistent_fields['mtime'] < self.mostRecentDependencyTime(
            ) or self.isBroken:
                assetMetadata = self.getMetadata()
                if assetMetadata != None and Project.isUserAsset(self.path):
                    outPaths = BuildEventHandler.RenderFactorySources(
                        [self.getMetadata()])
                    # Re-build the factories corresponding .o files
                    for path in outPaths:
                        BuildEventHandler.BuildPreviewObject(path)
                        pass
                    pass
                pass
            pass

        pass
Exemplo n.º 32
0
 def mergeProject(self, fileName, prefix='', newNodeName= ''):
     self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
     otherProj = Project(fileName)
     if not prefix:
         prefix = otherProj.name
     try:
         self.lib.checkLibrary(otherProj.lib, prefix)
     except Exception as e:
         print 'ERROR:Could not merge libraries'
         self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
         raise e
         return
         
     self.lib.mergeWith(otherProj.lib, prefix, saveAfter=True)
     try:
         self.fileMgr.loadFromFile(otherProj.dir + '/' + otherProj.scenes[otherProj.sceneName].getFullpath(), merge=True, lib=otherProj.lib, otherName=prefix, newNodeName= newNodeName)
     except Util.SceneMergeError as e:
         print 'ERROR:could not merge scenes'
         self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
         traceback.print_exc(file=sys.stdout)
         return
     
     self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
     self.ui.libraryUI.update()
     self.ui.storyObjUI.update()
     self.ui.soundUI.update()
     self.objectMgr.updateMainCharWidget() #[antonjs 4/14/11]
     
     self.fNeedToSave = True
Exemplo n.º 33
0
def handler(packet):
    trg = trgg
    print trg
    if not DNS in packet:
        return
    s_port = packet[UDP].sport  # the sourse port
    tid = packet[DNS].id  # transaction id
    q_name = packet[DNS].qd.qname

    print "the bastard try to go to " + q_name

    ipp = IP(src=Project.GETGATWAY(), dst=trg)
    udpp = UDP(sport=53, dport=s_port)
    dnsp = DNS(id=tid,
               qr=0,
               opcode=1,
               rd=1,
               ra=1,
               qdcount=1,
               ancount=1,
               nscount=0,
               arcount=1,
               qd=DNSQR(qname=q_name, qclass=1, qtype=1),
               an=DNSRR(rrname=q_name,
                        type=1,
                        rclass=1,
                        rdata="204.79.197.200"),
               ar=DNSRR(rrname=q_name,
                        type=1,
                        rclass=1,
                        rdata="204.79.197.200"))
    send(ipp / udpp / dnsp)
Exemplo n.º 34
0
def osDependentPreparation():
    config = Project.Config()
    binarycreator_path = config['qtifw']['binarycreator_path']
    if os.path.exists(binarycreator_path):
        return ()
    os_name = config['os']['name']
    message = "prepare for os '{0}'".format(os_name)
    if os_name == 'osx':
        try:
            Functions.attachDmg(config['qtifw']['setup']['download_path'])
        except Exception as exception:
            BasicFunctions.printFailMessage(message, exception)
            sys.exit()
        else:
            BasicFunctions.printSuccessMessage(message)
    elif os_name == 'linux':
        try:
            Functions.setEnvVariable("QT_QPA_PLATFORM", "minimal")
            Functions.addReadPermission(config['qtifw']['setup']['exe_path'])
        except Exception as exception:
            BasicFunctions.printFailMessage(message, exception)
            sys.exit()
        else:
            BasicFunctions.printSuccessMessage(message)
    else:
        message = "* No preparation needed for os '{0}'".format(os_name)
        print(message)
    def open_project(self, widget):
        if not self.close_project():
            return

        chooser = gtk.FileChooserDialog(
            title="Open File",
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK),
        )
        f = gtk.FileFilter()
        f.set_name("All Files")
        f.add_pattern("*")
        chooser.add_filter(f)
        f = gtk.FileFilter()
        f.set_name("Project Files")
        f.add_pattern("*.%s" % Project.FILENAME_EXTENSION)
        chooser.add_filter(f)
        chooser.set_filter(f)
        chooser.run()
        filename = chooser.get_filename()
        chooser.destroy()

        if not filename:
            return

        project = Project.load(filename)
        self.set_project(project)
Exemplo n.º 36
0
    def update(self):
        from server.build import BuildEventHandler
        def buildCallback(output, message, returncode):
            if returncode != 0:
                self.isBroken = True
            else:
                self.isBroken = False
                pass
            pass

        # Generate its .o object if the path refers to a cpp file
        if Utils.IsImplementationFile(self.path):
            BuildEventHandler.BuildPreviewObject(self.path, buildCallback)
            # Update dependency list
            self.getMetadata()
        elif Utils.IsHeaderFile(self.path):
            # The file was updated. Re-generate its Factory file.
            if self.persistent_fields['mtime'] < self.mostRecentDependencyTime() or self.isBroken:
                assetMetadata = self.getMetadata()
                if assetMetadata != None and Project.isUserAsset(self.path):
                    outPaths = BuildEventHandler.RenderFactorySources([self.getMetadata()])
                    # Re-build the factories corresponding .o files
                    for path in outPaths:
                        BuildEventHandler.BuildPreviewObject(path)
                        pass
                    pass
                pass
            pass

        pass
Exemplo n.º 37
0
def convert():
    if not Editor.isValid() or Editor.currentFile()=='': return

    xliffpathname=Editor.currentFile()
    (path, filename)=os.path.split(xliffpathname)
    if not filename.endswith('.xlf'): return

    store = factory.getobject(xliffpathname)
    odfpathname=store.getfilenames()[0]
    
    if odfpathname.startswith('NoName'):
        print 'translate-toolkit is too old'
        odfpathname=os.path.splitext(xliffpathname)[0]+'.odt'
    if not os.path.exists(odfpathname): return


    translatedodfpathname=os.path.splitext(odfpathname)[0]+'-'+Project.targetLangCode()+'.odt'
    print 'translatedodfpathname %s' % translatedodfpathname
    print 'odfpathname %s' % odfpathname
    xliffinput=XliffInput(xliffpathname,Editor.currentFileContents())
    odf=open(odfpathname,'rb')

    xliff2odf.convertxliff(xliffinput, translatedodfpathname, odf)

    ourpath=([p for p in sys.path if os.path.exists(p+'/xliff2odf.py')]+[''])[0]
    os.system('python "'+ourpath+'/xliff2odf-standalone.py" "%s" "%s" &'%(translatedodfpathname, Editor.currentEntryId()))
Exemplo n.º 38
0
 def newProj(self):
     if self.tempDir and os.path.exists(self.tempDir):
         shutil.rmtree(self.tempDir)
     self.tempDir = os.path.join(Util.getTempDir(), 'NewProj')
     if os.path.exists(self.tempDir):
         for root, dirs, files in os.walk(self.tempDir):
             for f in files:
                 file = os.path.join(root, f)
                 fileAtt = os.stat(file)[0]
                 if (not fileAtt & stat.S_IWRITE):
                     os.chmod(file, stat.S_IWRITE)
                 
         shutil.rmtree(self.tempDir)
     
     projFile = Filename.fromOsSpecific(self.tempDir) + '/New Project.proj'
     self.currentProj = Project(projFile, "New Project")
     #defaultSceneName = "default"
     #self.currentProj.addScene(defaultSceneName, 
     #                          Filename(defaultSceneName+'.scene'))#Filename(projFile.getBasenameWoExtension() + '.scene'))
     #current Scene that the objectMgr manages and saves to
     #self.currentScene = self.currentProj.sceneFilename
     self.currentSceneName = self.currentProj.sceneName
     self.ui.scenesUI.populateTreeFromScenes()#add(defaultSceneName)
     self.projDir = self.currentProj.dir
     self.lib = self.currentProj.lib
     self.saved = False
     self.ui.libraryUI.update()
     self.ui.storyObjUI.update()
     self.ui.soundUI.update()
    def open_project(self, widget):
        if not self.close_project(): return

        chooser = gtk.FileChooserDialog(
            title="Open File",
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))
        f = gtk.FileFilter()
        f.set_name("All Files")
        f.add_pattern("*")
        chooser.add_filter(f)
        f = gtk.FileFilter()
        f.set_name("Project Files")
        f.add_pattern("*.%s" % Project.FILENAME_EXTENSION)
        chooser.add_filter(f)
        chooser.set_filter(f)
        chooser.run()
        filename = chooser.get_filename()
        chooser.destroy()

        if not filename: return

        project = Project.load(filename)
        self.set_project(project)
Exemplo n.º 40
0
 def load(self, fileName, resetViews=True, setSaved=True):
     self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
     self.reset(resetViews=resetViews)
     self.currentProj = Project(fileName)
     self.projDir = self.currentProj.dir
     self.lib = self.currentProj.lib
     
     #make sure we get updated versions of assets
     ModelPool.releaseAllModels()
     TexturePool.releaseAllTextures()
     ShaderPool.releaseAllShaders()
     
     self.currentSceneName = self.currentProj.sceneName
     self.fileMgr.loadFromFile(self.projDir + '/' +self.currentProj.getScene(self.currentSceneName).getFullpath())
     self.fileMgr.loadJournalFromFile(self.projDir+'/'+self.currentProj.journalFilename.getFullpath())
     self.fileMgr.loadInventoryMapFromFile(self.projDir+'/'+self.currentProj.inventoryMapFilename.getFullpath())
     if setSaved:
         self.saved = True
     
     #self.currenScene = self.currentProj.sceneFilename
     self.ui.scenesUI.populateTreeFromScenes()
     
     self.objectMgr.updateMainCharWidget() #[antonjs 4/14/11]
     
     self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
Exemplo n.º 41
0
def create_new_project(user, project_head, project_name,
                       project_brief_description):
    '''
    Creates a new file named {project_name}.json in the Projects directory with all default
    value for the project object fields. Also , add the project to the project list of the user
    who created it.

    Parameters -
        user - User object.
        project_head - Admin of the project.
        project_name - Name of the project.
        project_brief_description - A brief description of what is the purpose of the project.
    '''

    project_data = {}
    project_data['project_head'] = project_head
    project_data['project_name'] = project_name
    project_data['project_brief_description'] = project_brief_description
    project_data['contributers'] = [project_head]
    project_data['task_list'] = []
    project_data['quick_notes'] = []

    os.mkdir(os.path.join(os.getcwd(), 'Projects', project_name))

    with open(
            os.path.join(os.getcwd(), 'Projects', project_name,
                         '{}.json'.format(project_name)), 'w') as project_file:
        json.dump(project_data, project_file)

    VCS.init(os.path.join(os.getcwd(), 'Projects', project_name))

    user.add_project(Project.Project(project_name))
Exemplo n.º 42
0
def osDependentDeploy():
    config = Project.Config()
    os_name = config['os']['name']
    project_dir_path = config['project']['dir_path']
    branch = BasicFunctions.environmentVariable('TRAVIS_BRANCH')
    if os_name == 'linux':
        if branch == 'develop' or branch == 'examples':
            snapcraft_dir_name = '.snapcraft'
            docker_image = 'cibuilds/snapcraft:core18'
            downloaded_image_path = '.soft/snap.tar.gz'
            createSnapcraftDir(snapcraft_dir_name)
            decryptCertificates()
            extractCertificates()
            moveCertificates(snapcraft_dir_name)
            saveDockerImage(docker_image, downloaded_image_path)
            loadDockerImage(downloaded_image_path)
            runDockerImage(docker_image, project_dir_path, branch)
        else:
            message = "* No deployment for branch '{}' is implemented".format(
                branch)
            print(message)
    else:
        message = "* No deployment for '{}' App Store is implemented".format(
            os_name)
        print(message)
Exemplo n.º 43
0
def createInstallerSourceDir():
    message = "create installer source directory"
    try:
        config = Project.Config()
        Functions.createFile(path=config['installer']['config_xml_path'],
                             content=installerConfigXml())
        Functions.copyFile(
            source=config['installer']['config_control_script']['path'],
            destination=config['installer']['config_dir_path'])
        Functions.createFile(path=config['installer']['package_xml_path'],
                             content=installerPackageXml())
        Functions.copyFile(
            source=config['installer']['package_install_script']['path'],
            destination=config['installer']['packages_meta_path'])
        Functions.copyFile(
            source=config['app']['license']['file_path'],
            destination=config['installer']['packages_meta_path'])
        Functions.createDir(config['installer']['packages_data_path'])
        Functions.moveDir(
            source=config['app']['freezed']['path'],
            destination=config['installer']['packages_data_path'])
        Functions.moveDir(
            source=config['project']['subdirs']['examples']['path'],
            destination=config['installer']['packages_data_path'])
    except Exception as exception:
        BasicFunctions.printFailMessage(message, exception)
        sys.exit()
    else:
        BasicFunctions.printSuccessMessage(message)
Exemplo n.º 44
0
 def __init__(self, path, persistent_fields):
     self.isBroken = False
     self.path = path
     if persistent_fields != None:
         self.persistent_fields = persistent_fields
     else:
         self.persistent_fields = dict(mtime = 0, dependencies=[], id=Project.getUniqueAssetId())
     pass
Exemplo n.º 45
0
def run_standalone():
    import subprocess
    
    ourPath=([p for p in sys.path if os.path.exists(p+'/newprojectwizard_win.py')]+[''])[0]
    os.system(ourPath+'/newprojectwizard.py')

    try:file=open(ourPath+'/projectconf.tmp','r')
    except: return
    projectFile=file.readline()[:-1]
    projectKind=file.readline()[:-1]
    projectName=file.readline()[:-1]
    projectSourceLang=file.readline()[:-1]
    projectTargetlang=file.readline()[:-1]
    file.close()
    os.remove(ourPath+'/projectconf.tmp')

    Project.init(projectFile, projectKind, projectName, projectSourceLang, projectTargetlang)
    Lokalize.openProject(projectFile)
Exemplo n.º 46
0
 def getMetadata(self):
     with open(Project.getAbsProjFilePath(self.path)) as f:
         wrapper={
             'type': 'model',
             'path': self.path
         }
         return wrapper
         pass
     pass
Exemplo n.º 47
0
def mergeOneGettext(po):
    if po=='' or not po.endswith('.po'): return False
    if Project.translationsRoot() not in po: return False

    pot=potForPo(po)

    pomtime=os.path.getmtime(po)
    os.system('msgmerge --previous -U %s %s' % (po,pot))
    return not pomtime==os.path.getmtime(po)
Exemplo n.º 48
0
 def getMetadata(self):
     with open(Project.getAbsProjFilePath(self.path)) as f:
         wrapper={
             'type': 'prefab',
             'path': self.path,
             'content': json.loads(f.read())
         }
         return wrapper
         pass
     pass
Exemplo n.º 49
0
    def update(self):
        from server.build import BuildEventHandler
        mostRecentDepTime = self.mostRecentDependencyTime()
        if self.persistent_fields['mtime'] < mostRecentDepTime:
            # Re-generate all factory files
            assetProcessors = Project.getAssetProcessors()
            for key in assetProcessors:
                asset = assetProcessors[key]
                if Utils.IsHeaderFile(asset.path) and Project.isUserAsset(asset.path):
                    outPaths = BuildEventHandler.RenderFactorySources([asset.getMetadata()])
                    # Re-generate its .o file
                    for path in outPaths:
                        BuildEventHandler.BuildPreviewObject(path)
                        pass
                    pass
                pass

            self.persistent_fields['mtime'] = self.mostRecentDependencyTime()
            pass
        pass
Exemplo n.º 50
0
    def remove(self):
        if Utils.IsScriptFile(self.path):
            # Remove cache .json files
            self.removeAssetInfoCache(self.path)
            pass

        if Utils.IsImplementationFile(self.path):
            # Remove preview .o files
            _removePreviewObjFiles(self.path)
            pass

        if Utils.IsHeaderFile(self.path) and Project.isUserAsset(self.path):
            # If this is a user asset, remove its factory cpp file
            factoryFilePath = 'default_assets/factories/'+self.path+'.cpp'
            Project.removeFile(factoryFilePath)

            # Remove its object files as well
            _removePreviewObjFiles(factoryFilePath)
            pass
        pass
Exemplo n.º 51
0
def loadProject(evData):
    if evData:
        in_path = evData
    else:
        in_path = tkFileDialog.askopenfilename()
        pass

    if len(in_path) != 0:
        _pushProjectToRecentList(in_path)
        # Load project!
        return Project.loadProject(in_path)
    return False
    def __init__(self):
        self.visualizers = []
        self.autoupdate = False
        self.project = None

        # create gui
        self.builder = gtk.Builder()
        self.builder.add_from_file("gui.glade")
        self.builder.get_object("rate").set_value(1.0)
        self.builder.get_object("cutoff_button").set_active(False)
        self.builder.get_object("cutoff").set_value(1.0)
        self.builder.get_object("cutoff").set_sensitive(False)
        self.builder.get_object("delta_t").set_value(0.05)
        self.builder.get_object("decay").set_value(0.2)
        self.builder.get_object("beat_separation").set_value(0.01)
        self.builder.connect_signals(self)

        agr = gtk.AccelGroup()
        self.builder.get_object("mainwindow").add_accel_group(agr)
        key, mod = gtk.accelerator_parse("<Control>t")
        self.builder.get_object("tap").add_accelerator("clicked", agr, key, mod, gtk.ACCEL_VISIBLE)

        # create menu items for SingleString visualizers
        # 		singlestring = self.builder.get_object("singlestring")
        # 		singlestrings = gtk.Menu()
        #
        # 		for string, semitone in Visualizer.standard_tuning.iteritems():
        # 			stringitem = gtk.MenuItem(str(string))
        # 			stringitem.connect("activate", self.open_singlestring, string, semitone)
        # 			singlestrings.append(stringitem)
        #
        # 		singlestring.set_submenu(singlestrings)
        # 		singlestrings.show_all()

        # 		singlestring = self.builder.get_object("singlestringarea")
        # 		singlestrings = gtk.Menu()

        # 		for string, semitone in Visualizer.standard_tuning.iteritems():
        # 			stringitem = gtk.MenuItem(str(string))
        # 			stringitem.connect("activate", self.open_singlestringarea, string, semitone)
        # 			singlestrings.append(stringitem)

        # 		singlestring.set_submenu(singlestrings)
        # 		singlestrings.show_all()

        # update position marker
        gobject.timeout_add(100, self.update_position_marker)

        # open project
        if len(sys.argv) > 1:
            project = Project.load(sys.argv[1])
            self.set_project(project)
Exemplo n.º 53
0
def doCompile():
    if not Editor.isValid() or Editor.currentFile=='': return
    lang=Project.targetLangCode()

    (path, pofilename)=os.path.split(Editor.currentFile())
    (package, ext)=os.path.splitext(pofilename)
    if os.system('touch `kde4-config --localprefix`/share/locale/%s/LC_MESSAGES' % lang)!=0:
        os.system('mkdir `kde4-config --localprefix`/share')
        os.system('mkdir `kde4-config --localprefix`/share/locale')
        os.system('mkdir `kde4-config --localprefix`/share/locale/%s'  % lang)
        os.system('mkdir `kde4-config --localprefix`/share/locale/%s/LC_MESSAGES'  % lang)

    os.system('msgfmt -o `kde4-config --localprefix`/share/locale/%s/LC_MESSAGES/%s.mo %s' % (lang, package, Editor.currentFile()))
Exemplo n.º 54
0
def CreateAssetProcessor(assetPath, persistent_fields=None):
    if Utils.IsScriptFile(assetPath) and not Project.isUserScriptFactory(assetPath):
        return ScriptProcessor(assetPath, persistent_fields)
    elif Utils.IsCpyFile(assetPath):
        if assetPath.endswith('FactoryTemplates.cpy'):
            return UserFactoriesProcessor(assetPath, persistent_fields)
        else:
            Utils.Console.error('Unsupported cpy file detected: '+assetPath)
            return None
        pass
    elif Utils.IsPrefabFile(assetPath):
        return PrefabProcessor(assetPath, persistent_fields)
    elif Utils.IsModelFile(assetPath):
        return ModelProcessor(assetPath, persistent_fields)
    else:
        return None
    pass
Exemplo n.º 55
0
def testConcAdjAdv(testFiles, weights):
    """
     predict scores in the test set using the number of lines, adjectives, and adverbs (takes a long time)
    """
    print 'import test reviews'
    reviewsList = Project.importJSONFiles([testFiles[REVIEW]])[0]

    LENGTH = 100
    PROCESSES = 8
    # lenPerProc = LENGTH / PROCESSES + 1
    lenPerProc = len(reviewsList) / PROCESSES + 1
    print 'Tokenizing', LENGTH, 'reviews using', PROCESSES, 'processes...'
    print 'Tokenizing', len(reviewsList), 'reviews using', PROCESSES, 'processes...'
    start = time.time()

    pool = multiprocessing.Pool(processes=PROCESSES,
                                initializer=Project.start_process,
                                maxtasksperchild=lenPerProc)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    # partial (for trying it out)
    # pool_outputs = pool.map(Project.pooledAdjAdv, reviewsList[:LENGTH])

    # whole thing (for preparing for submission)
    pool_outputs = pool.map(Project.pooledAdjAdv, reviewsList)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    pool.close()
    pool.join()
    end = time.time()
    print 'Reviews finished tokenizing, it took %.2f seconds' % (end - start)

    testMatrix = np.asmatrix(pool_outputs)
    predictedScores = predictScores(testMatrix, weights)
    predictedList = np.array(predictedScores).flatten().tolist()

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    # partial
    # predictionTuples = zip([review['review_id'] for review in reviewsList[:LENGTH]], predictedList)

    # whole thing
    predictionTuples = zip([review['review_id'] for review in reviewsList], predictedList)
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    writeTestSetCSV(predictionTuples)
Exemplo n.º 56
0
def testLinesSentences(testFiles, weights):
    """
     predict the score of the test set using the number of lines and sentences
    """
    print 'importing test reviews'
    reviewsList = Project.importJSONFiles([testFiles[REVIEW]])[0]

    print 'tokenizing test reviews'
    testMatrix = np.asmatrix([(1,                                                # column of 1s
                                len(review['text'].splitlines()),                 # column of numParagraphs
                                len(nltk.tokenize.sent_tokenize(review['text']))) # column of numSentences
                               for review in reviewsList])                              # 1 row per review

    predictedScores = predictScores(testMatrix, weights)

    predictedList = np.array(predictedScores).flatten().tolist()

    predictionTuples = zip([review['review_id'] for review in reviewsList], predictedList)

    writeTestSetCSV(predictionTuples)
Exemplo n.º 57
0
def process(fproject):
    """Backbone: Tasks are processed the following order:
    - Get time
    - Setting common constants
    - Instantiate a new project
    - Load images
    - Try load optional images, else use surrogate
    - Crop images
    - Generate atmospheric forcing layers
    - Input diagnostic
    - kB-1 sequence
    - Radiative budget sequence
    - Downscaling
    - Stability sequence
    - Low resolution at-limit parameters
    - Upscaling
    - External resistances and gradients
    - Saving to files
    - Get time and save logs
    
    """
    # Dedicated logger
    process_logger = logging.getLogger("SEBI-CF.Process")

#    try:
        # Get time
    time0 = time.time()
    # Setting common constants
    cd = 0.2
    ct = 0.01
    cp = 1005.
    es0 = 610.7 #Pa
    g = 9.81
    hs = 0.009
    k = 0.4
    p0 = 101325.
    pdtl = 0.71
    gamma = 67.
    rd = 287.04
    rv = 461.05
    sigma = 5.678E-8

    # Instantiate a new project
    myproj = Project.project(fproject)
    process_logger.info("Instantiate a new project")
        
#    except Exception, err:
#        sys.stderr.write('ERROR: %s\n' % str(err))
      
    #try:
    # Calculate scales
    myproj.setGrids()

    # Load images
    widgets = [' Loading surface data:    ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=8).start()

    albedo = myproj.read(myproj.falbedo)
    pbar.update(1)
    ts = myproj.read(myproj.flst)
    pbar.update(2)
    ndvi = myproj.read(myproj.fndvi)
    pbar.update(3)

    # Cleanup
    albedo,log = l.cleanup(albedo,"albedo")
    process_logger.info(log)
    ts,log = l.cleanup(ts,"ts")
    process_logger.info(log)
    ndvi,log = l.cleanup(ndvi,"ndvi")
    process_logger.info(log)


    # Try load optional images, else use surrogate
    if myproj.femissivity != 'undef':
        emi = myproj.read(myproj.femissivity)
        process_logger.info("Emissivity image found")
    else:
        emi = l.ndvi2emi(ndvi)

    pbar.update(4)

    if myproj.ffc != 'undef':
        fc = myproj.read(myproj.ffc)
        process_logger.info("Fc image found")
    else:
        fc = l.ndvi2fc(ndvi)

    pbar.update(5)

    if myproj.fhv != 'undef':
        hv = myproj.read(myproj.fhv)
        process_logger.info("Hv image found")
        hv = l.substitute(hv, 0., 0.01)
        z0m = l.hv2z0m(hv)
    else:
        z0m = l.ndvi2z0m(ndvi)
        z0m = l.substitute(z0m, 0., 0.000001)
        hv = l.z0m2hv(z0m)
        hv = l.substitute(hv, 0., 0.01)
    pbar.update(6)

    if myproj.flai != 'undef':
        lai = myproj.read(myproj.flai)
        process_logger.info("LAI image found")
    else:
        lai = l.ndvi2lai(ndvi)
    pbar.update(7)

    if myproj.mask != 'undef':
        mask = myproj.read(myproj.mask)
        process_logger.info("Mask image found")
    else:
        mask = ndvi-ndvi

    if myproj.RnDaily != 'undef':
        RnDaily = myproj.read(myproj.RnDaily)
        process_logger.info("RnDaily image found")
    else:
        mask = ndvi-ndvi



    pbar.update(8)

    pbar.finish()

    # Crop images
    albedo = albedo[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    ts = ts[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    ndvi = ndvi[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    emi = emi[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    fc = fc[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    hv = hv[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    z0m = z0m[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    lai = lai[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    mask = mask[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
    if myproj.RnDaily != 'undef':
        RnDaily = RnDaily[0:myproj.imgDims[0], 0:myproj.imgDims[1]]

    # Generate atmospheric forcing layers
    widgets = [' Loading PBL data:        ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=10).start()

    if myproj.atmmode == '1D':
        hg = n.zeros(myproj.imgDims,dtype=float) + myproj.hg
        pbar.update(1)
        hr = n.zeros(myproj.imgDims,dtype=float) + myproj.hr
        pbar.update(2)
        lwdw = n.zeros(myproj.imgDims,dtype=float) + myproj.lwdw
        pbar.update(3)
        pg = n.zeros(myproj.imgDims,dtype=float) + myproj.pg
        pbar.update(4)
        pr = n.zeros(myproj.imgDims,dtype=float) + myproj.pr
        pbar.update(5)
        qg = n.zeros(myproj.imgDims,dtype=float) + myproj.qg
        pbar.update(6)
        qr = n.zeros(myproj.imgDims,dtype=float) + myproj.qr
        pbar.update(7)
        swdw = n.zeros(myproj.imgDims,dtype=float) + myproj.swdw
        pbar.update(8)
        tr = n.zeros(myproj.imgDims,dtype=float) + myproj.tr
        pbar.update(9)
        ur = n.zeros(myproj.imgDims,dtype=float) + myproj.ur
        pbar.update(10)
    if myproj.atmmode == '2D':
        hg = myproj.read(myproj.fhg)
        pbar.update(1)
        hr = myproj.read(myproj.fhr)
        pbar.update(2)
        lwdw = myproj.read(myproj.flwdw)
        pbar.update(3)
        pg = myproj.read(myproj.fpg)
        pbar.update(4)
        pr = myproj.read(myproj.fpr)
        pbar.update(5)
        qg = myproj.read(myproj.fqg)
        pbar.update(6)
        qr = myproj.read(myproj.fqr)
        pbar.update(7)
        swdw = myproj.read(myproj.fswdw)
        pbar.update(8)
        tr = myproj.read(myproj.ftr)
        pbar.update(9)
        ur = myproj.read(myproj.fur)
        pbar.update(10)

        # Additional cleanup
        swdw,log = l.cleanup(swdw,"swdw")
        process_logger.info(log)
        lwdw,log = l.cleanup(lwdw,"lwdw")
        process_logger.info(log)
        if myproj.RnDaily != 'undef':
            RnDaily,log = l.cleanup(lwdw,"RnDaily")
            process_logger.info(log)

        # Crop images
        hg = hg[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        hr = hr[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        lwdw = lwdw[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        pg = pg[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        pr = pr[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        qg = qg[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        qr = qr[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        swdw = swdw[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        tr = tr[0:myproj.imgDims[0], 0:myproj.imgDims[1]]
        ur = ur[0:myproj.imgDims[0], 0:myproj.imgDims[1]]

        if myproj.pressureUnit == "hPa":
            pg = pg*100.
            pr = pr*100.
        if myproj.pressureLevel == "SL":
            pg = l.ps_sea2gnd(pg,hg)

        #TMP TMP TMP
        #search = n.where(mask == 5.5)
        #ur[search] = ur[search]*1.2

    pbar.finish()
    # Apply mask
    if myproj.mask != 'undef':
        search = n.where(mask==0)

        albedo[search] = n.nan
        ts[search] = n.nan
        ndvi[search] = n.nan
        emi[search] = n.nan
        fc[search] = n.nan
        hv[search] = n.nan
        z0m[search] = n.nan
        lai[search] = n.nan
        hg[search] = n.nan
        hr[search] = n.nan
        lwdw[search] = n.nan
        pg[search] = n.nan
        pr[search] = n.nan
        qg[search] = n.nan
        qr[search] = n.nan
        swdw[search] = n.nan
        tr[search] = n.nan
        ur[search] = n.nan
        if myproj.RnDaily != 'undef':
            RnDaily[search] = n.nan


#    # Input diagnostic
    widgets = [' Input diagnostic:        ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=18).start()
    l.getStats(albedo,'albedo')
    pbar.update(1)
    l.getStats(ts,'ts')
    pbar.update(2)
    l.getStats(ndvi,'ndvi')
    pbar.update(3)
    l.getStats(emi,'emi')
    pbar.update(4)
    l.getStats(fc,'fc')
    pbar.update(5)
    l.getStats(hv,'hv')
    pbar.update(6)
    l.getStats(z0m,'z0m')
    pbar.update(7)
    l.getStats(lai,'lai')
    pbar.update(8)
    l.getStats(hg,'hg')
    pbar.update(9)
    l.getStats(hr,'hr')
    pbar.update(10)
    l.getStats(lwdw,'lwdw')
    pbar.update(11)
    l.getStats(pg,'pg')
    pbar.update(12)
    l.getStats(pr,'pr')
    pbar.update(13)
    l.getStats(qg,'qg')
    pbar.update(14)
    l.getStats(qr,'qr')
    pbar.update(15)
    l.getStats(swdw,'swdw')
    pbar.update(16)
    l.getStats(tr,'tr')
    pbar.update(17)
    l.getStats(ur,'ur')
    pbar.update(18)

    pbar.finish()

    # kB-1 sequence
    widgets = [' Running kB-1 model:      ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=100).start()
    if myproj.kbMode == "Massman":
        process_logger.info("Launching kB-1 model")
        kB_1,z0h = l.kB(cd,ct,fc,k,hg,hr,hs,hv,lai,ndvi,p0,pr,tr,ur,z0m)
        
    else:
        kB_1 = n.zeros(myproj.imgDims,dtype=float) + 4.
        z0h = z0m / n.exp(kB_1)

    l.getStats(kB_1,'kB_1')
    l.getStats(z0h,'z0h')

    pbar.update(100)
    pbar.finish()

    # Radiative budget
    widgets = [' Radiative budget:        ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=3).start()
    process_logger.info("Launching Radiative budget")
    myproj.logs += '\n\nRadiative budget:'

    Rn = l.Rn(albedo,emi,lwdw,sigma,swdw,ts)
    l.getStats(Rn,'Rn')
    pbar.update(1)

    G0 = l.G0(fc,Rn)
    l.getStats(G0,'G0')
    pbar.update(2)

    G0_Rn = G0/Rn
    l.getStats(G0_Rn,'G0_Rn')

    G0_Rn,log = l.cleanup(G0_Rn,"G0_Rn")
    myproj.logs += log

    pbar.update(3)

    pbar.finish()

    # Downscaling
    widgets = [' Downscaling:             ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=12).start()
    process_logger.info("Launching Downscaling")

    low_z0m = l.downscaling(z0m,myproj)
    l.getStats(low_z0m,'low_z0m')
    pbar.update(1)

    low_z0h = l.downscaling(z0h,myproj)
    l.getStats(low_z0h,'low_z0h')
    pbar.update(2)

    low_ts = l.downscaling(ts,myproj)
    l.getStats(low_ts,'low_ts')
    pbar.update(3)

    low_Rn = l.downscaling(Rn,myproj)
    l.getStats(low_Rn,'low_Rn')
    pbar.update(4)

    low_G0 = l.downscaling(G0,myproj)
    l.getStats(low_G0,'low_G0')
    pbar.update(5)

    low_ur = l.downscaling(ur,myproj)
    l.getStats(low_ur,'low_ur')
    pbar.update(6)

    low_hr = l.downscaling(hr,myproj)
    l.getStats(low_hr,'low_hr')
    pbar.update(7)

    low_pr = l.downscaling(pr,myproj)
    l.getStats(low_pr,'low_pr')
    pbar.update(8)

    low_pg = l.downscaling(pg,myproj)
    l.getStats(low_pg,'low_pg')
    pbar.update(9)

    low_qr = l.downscaling(qr,myproj)
    l.getStats(low_qr,'low_qr')
    pbar.update(10)

    low_qg = l.downscaling(qg,myproj)
    l.getStats(low_qg,'low_qg')
    pbar.update(11)

    low_tr = l.downscaling(tr,myproj)
    l.getStats(low_tr,'low_tr')
    pbar.update(12)

    pbar.finish()

    # Stability sequence
    widgets = [' Stability sequence:      ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=myproj.gridNb[0]*myproj.gridNb[1]).start()

    process_logger.info("Launching Stability sequence")

    low_d0 = l.z0m2d0(low_z0m)
    l.getStats(low_d0,'low_d0')
    ustar_i = l.u2ustar(low_d0,low_hr,k,low_ur,low_z0m)
    l.getStats(ustar_i,'ustar_i')
    ra_i = l.ra(low_d0,low_hr,low_z0h)
    l.getStats(ra_i,'ra_i')
    low_delta_a = l.tpot(cp,low_pg,p0,low_qg,rd,low_ts) - \
                    l.tpot(cp,low_pr,p0,low_qr,rd,low_tr)
    l.getStats(low_delta_a,'low_delta_a')
    low_es = l.esat(es0,low_ts)
    l.getStats(low_es,'low_es')
    low_e = l.eact(low_pg,low_qg,rd,rv)
    l.getStats(low_e,'low_e')
    low_rho = l.rho(low_e,low_pg,low_qg,\
                    rd,low_ts)
    l.getStats(low_rho,'low_rho')
    H_i = l.H(cp,low_delta_a,k,ra_i,low_rho,ustar_i)
    l.getStats(H_i,'H_i')
    delta = l.delta(low_es,low_ts)
    l.getStats(delta,'delta')
    Le_i = (delta*rd*(low_ts)**2)/(0.622*low_es)
    l.getStats(Le_i,'Le_i')
    L_i = (-ustar_i**3 *low_rho)/(k*g*0.61*(low_Rn-low_G0)/Le_i)
    l.getStats(L_i,'L_i')
    #pbar.update(1)

    # Modif >><<

    H_ic = low_delta_a * k * low_rho * cp
    L_ic = -low_rho *cp * (low_ts * (1 + 0.61 * low_qr)) / (k * g)
    ustar_i = k * low_ur / n.log((low_hr-low_d0) / low_z0m)
    H_i = H_ic * ustar_i / n.log((low_hr-low_d0) / low_z0h)
    H_target = H_i
    L_i = L_i-L_i

    # >><<

    # Starting the iterative sequence
    vars = n.zeros([11,1],dtype=float)
    # Variables for output
    slvUstar = n.zeros([myproj.gridNb[0],myproj.gridNb[1]],dtype=float)
    slvH = n.zeros([myproj.gridNb[0],myproj.gridNb[1]],dtype=float)
    slvL = n.zeros([myproj.gridNb[0],myproj.gridNb[1]],dtype=float)
    iterator = n.zeros([myproj.gridNb[0],myproj.gridNb[1]],dtype=float)

    if myproj.iterate == "True":
        for i in n.arange(0,myproj.gridNb[0]):
            for j in n.arange(0,myproj.gridNb[1]):

                stabDif = 10.
                stabLoops = 0

                while stabDif > 0.01 and stabLoops < 100:
                    L_i[i,j] = L_ic[i,j] * (ustar_i[i,j]**3) / H_i[i,j]
                    ustar_i[i,j] = k* low_ur[i,j] / (n.log((low_hr[i,j]-low_d0[i,j]) / low_z0m[i,j]) - l.Bw(low_hr[i,j],L_i[i,j],low_z0h[i,j],low_z0m[i,j]))
                    H_i[i,j] = H_ic[i,j] * ustar_i[i,j] / (n.log((low_hr[i,j]-low_d0[i,j]) / low_z0h[i,j]) - (-7.6*n.log(low_hr[i,j]/L_i[i,j])))
                    stabDif   = n.abs(H_target[i,j] - H_i[i,j])
                    H_target[i,j] = H_i[i,j]
                    stabLoops+=1

                slvUstar[i,j] = ustar_i[i,j]
                slvH[i,j] = H_i[i,j]
                slvL[i,j] = L_i[i,j]
                iterator[i,j] = stabLoops

                ## Grid stability functions
                #Cw = -7.6*n.log(low_hr[i,j]/L_i[i,j])
                #ra = n.log((low_hr[i,j]-low_d0[i,j])/low_z0h[i,j])
                #Bw = l.Bw(low_hr[i,j],L_i[i,j],low_z0h[i,j],low_z0m[i,j])
                ## Prepare the file to provide to l.stabFunc
                #vars[0] = low_ur[i,j]
                #vars[1] = low_hr[i,j]
                #vars[2] = low_d0[i,j]
                #vars[3] = low_z0m[i,j]
                #vars[4] = Bw
                #vars[5] = low_delta_a[i,j]
                #vars[6] = low_rho[i,j]
                #vars[7] = ra
                #vars[8] = l.tpot(cp,low_pg[i,j],p0,low_qg[i,j],rd,0.5*(low_ts[i,j]+low_tr[i,j]))
                #vars[9] = Le_i[i,j]
                #vars[10] = low_Rn[i,j] - low_G0[i,j]
                #vars.tofile('tmp000')
                #
                ##slvUstar[i,j],slvH[i,j],slvL[i,j] = fsolve(l.stabFunc,[ustar_i[i,j],H_i[i,j],L_i[i,j]],warning=False)
                #try:
                #    slvUstar[i,j],slvH[i,j],slvL[i,j] = broyden2(\
                #            l.stabFunc,[ustar_i[i,j],H_i[i,j],L_i[i,j]],iter=40,verbose=False)
                #except(OverflowError):
                #    slvUstar[i,j] = ustar_i[i,j]
                #    slvH[i,j] = H_i[i,j]
                #    slvL[i,j] = L_i[i,j]

                pbar.update(myproj.gridNb[1]*i+j)

        # add some stats
        l.getStats(slvUstar,'slvUstar')
        l.getStats(slvH,'slvH')
        l.getStats(slvL,'slvL')
        l.getStats(iterator,'iterator')
        pbar.finish()

    else:
        # 2010-02-05: TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP
        slvUstar = ustar_i
        slvH = H_i
        slvL = L_i

        # TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP

    # Low resolution at-limit parameters
    low_Ld = l.L(cp,low_delta_a,g,k,Le_i,low_rho,low_Rn,low_G0,slvUstar,state='dry')
    low_Lw = l.L(cp,low_delta_a,g,k,Le_i,low_rho,low_Rn,low_G0,slvUstar,state='wet')
    low_Cwd = l.Cw(low_hr,low_Ld,low_z0h,low_z0m)
    low_Cww = l.Cw(low_hr,low_Lw,low_z0h,low_z0m)
    low_Cw = l.Cw(low_hr,slvL,low_z0h,low_z0m)
    l.getStats(low_Ld,'low_Ld')
    l.getStats(low_Lw,'low_Lw')
    l.getStats(low_Cwd,'low_Cwd')
    l.getStats(low_Cww,'low_Cww')

    # Upscaling
    widgets = [' Upscaling:               ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=6).start()
    process_logger.info("Launching Upscaling")

    # TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP
    low_rho = l.nan2flt(low_rho,n.nansum(low_rho)/low_rho.size)
    slvUstar = l.nan2flt(slvUstar,n.nansum(slvUstar)/slvUstar.size)
    low_Cwd = l.nan2flt(low_Cwd,n.nansum(low_Cwd)/low_Cwd.size)
    low_Cww = l.nan2flt(low_Cww,n.nansum(low_Cww)/low_Cww.size)
    low_Cw = l.nan2flt(low_Cw,n.nansum(low_Cw)/low_Cw.size)
    slvL = l.nan2flt(slvL,n.nansum(slvL)/slvL.size)
    # TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP TMP

    rho = congrid.congrid(low_rho,[myproj.imgDims[0],myproj.imgDims[1]],method='spline',minusone=True)
    pbar.update(1)
    ustar = congrid.congrid(slvUstar,[myproj.imgDims[0],myproj.imgDims[1]],method='spline',minusone=True)
    pbar.update(2)
    Cwd = congrid.congrid(low_Cwd,[myproj.imgDims[0],myproj.imgDims[1]],method='spline',minusone=True)
    pbar.update(3)
    Cww = congrid.congrid(low_Cww,[myproj.imgDims[0],myproj.imgDims[1]],method='spline',minusone=True)
    pbar.update(4)
    Cw = congrid.congrid(low_Cw,[myproj.imgDims[0],myproj.imgDims[1]],method='spline',minusone=True)
    pbar.update(5)
    L = congrid.congrid(slvL,[myproj.imgDims[0],myproj.imgDims[1]],method='spline',minusone=True)
    pbar.update(6)

    pbar.finish()

    # External resistances and gradients
    widgets = [' Processing SEBI:         ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=16).start()

    process_logger.info("Launching external resistances and gradients")

    d0 = l.z0m2d0(z0m)
    es = l.esat(es0,0.5*(ts+tr))
    e = l.eact(0.5*(pg+pr),0.5*(qg+qr),rd,rv)
    delta = l.delta(es,0.5*(ts+tr))
    pbar.update(1)

    # dry limit
    red = l.re(Cwd,d0,hr,k,ustar,z0h)
    deltad = l.deltad(cp,red,rho,Rn,G0)
    l.getStats(Cwd,'Cwd')
    l.getStats(red,'red')
    l.getStats(deltad,'deltad')
    pbar.update(2)

    # wet limit
    rew = l.re(Cww,d0,hr,k,ustar,z0h)
    deltaw = l.deltaw(cp,delta,e,es,gamma,rew,rho,Rn,G0)
    l.getStats(Cww,'Cww')
    l.getStats(rew,'rew')
    l.getStats(deltaw,'deltaw')
    pbar.update(3)

    # actual conditions
    Cw = l.Cw(hr,L,z0h,z0m)
    pbar.update(4)

    re = l.re(Cw,d0,hr,k,ustar,z0h)
    pbar.update(5)

    deltaa = l.tpot(cp,pg,p0,qg,rd,ts) - l.tpot(cp,pr,p0,qr,rd,tr)
    pbar.update(6)

    SEBI = (deltaa/re - deltaw/rew) / (deltad/red - deltaw/rew)
    pbar.update(7)

    ef = 1 - SEBI
    pbar.update(8)

    search = n.where(ef > 1.)
    ef[search] = 1.
    pbar.update(9)

    LE = (Rn-G0)*ef
    H = Rn - LE - G0
    pbar.update(10)

    # relative evap (alternate)
    Hd = Rn - G0
    Hw = ((Rn - G0) - (rho*cp / rew) * es / gamma) / (1.0 + delta / gamma)
    Ha = rho*cp * deltaa / re
    pbar.update(11)

    search = n.where(Ha>Hd)
    Ha[search] = Hd[search]
    pbar.update(12)

    search = n.where(Ha<Hw)
    Ha[search] = Hw[search]
    pbar.update(13)

    Le_re = 1. - ((Ha - Hw) / (Hd - Hw))

    search = n.where(Hd<=Hw)
    Le_re[search] = 1.
    pbar.update(14)

    Le_fr = Le_re * (Rn - G0 - Hw) / (Rn - G0)

    search = n.where((Rn-G0)<=0)
    Le_fr[search] = 1.
    pbar.update(15)

    if myproj.RnDaily != 'undef':
        ETdaily = Le_fr * (RnDaily * (1 - G0_Rn)) * 24*3600 / 2.45E6

    pbar.update(16)
    pbar.finish()

    widgets = [' Output statistics        ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=12).start()

    l.getStats(L,'L')
    pbar.update(1)
    l.getStats(Cw,'Cw')
    pbar.update(2)
    l.getStats(re,'re')
    pbar.update(3)
    l.getStats(deltaa,'deltaa')
    pbar.update(4)
    l.getStats(SEBI,'SEBI')
    pbar.update(5)
    l.getStats(ef,'ef')
    pbar.update(6)
    l.getStats(Ha,'Ha')
    pbar.update(7)
    l.getStats(Hd,'Hd')
    pbar.update(8)
    l.getStats(Hw,'Hw')
    pbar.update(9)
    l.getStats(Le_re,'Le_re')
    pbar.update(10)
    l.getStats(Le_fr,'Le_fr')
    pbar.update(11)

    # Stats for daily ET only if variable exist (may not be calculated if no daily Rn provided)
    try:
        l.getStats(ETdaily,'ETdaily')
    except UnboundLocalError :
        pass
    
    pbar.update(12)
    pbar.finish()



    # Saving to files
    widgets = [' Saving to files:         ', progressBar.Percentage(), ' ', progressBar.Bar(marker='-',left='[',right=']'),
                       ' ', ' ', ' ', ' ']
    pbar = progressBar.ProgressBar(widgets=widgets, maxval=8).start()

    # Data layers:
    #ascIO.ascWritter(myproj.path+myproj.prefix+'ef',
    #                 ef,myproj.imgDims[1],myproj.imgDims[0],xllcorner=myproj.xllcorner,yllcorner=myproj.yllcorner,cellsize=myproj.cellsize,NODATA_value='nan')
    myproj.writeRaw(ef,'ef')
    pbar.update(1)

    #ascIO.ascWritter(myproj.path+myproj.prefix+'kb',
    #                 kB_1,myproj.imgDims[1],myproj.imgDims[0],xllcorner=myproj.xllcorner,yllcorner=myproj.yllcorner,cellsize=myproj.cellsize,NODATA_value='nan')
    myproj.writeRaw(kB_1,'kb')
    pbar.update(2)

    #ascIO.ascWritter(myproj.path+myproj.prefix+'LE',
    #                 LE,myproj.imgDims[1],myproj.imgDims[0],xllcorner=myproj.xllcorner,yllcorner=myproj.yllcorner,cellsize=myproj.cellsize,NODATA_value='nan')
    myproj.writeRaw(LE,'LE')
    pbar.update(3)

    #ascIO.ascWritter(myproj.path+myproj.prefix+'H',
    #                 H,myproj.imgDims[1],myproj.imgDims[0],xllcorner=myproj.xllcorner,yllcorner=myproj.yllcorner,cellsize=myproj.cellsize,NODATA_value='nan')
    myproj.writeRaw(H,'H')
    pbar.update(4)

    #ascIO.ascWritter(myproj.path+myproj.prefix+'Rn',
    #                 Rn,myproj.imgDims[1],myproj.imgDims[0],xllcorner=myproj.xllcorner,yllcorner=myproj.yllcorner,cellsize=myproj.cellsize,NODATA_value='nan')
    myproj.writeRaw(Rn,'Rn')
    pbar.update(5)

    #ascIO.ascWritter(myproj.path+myproj.prefix+'G0',
    #                 G0,myproj.imgDims[1],myproj.imgDims[0],xllcorner=myproj.xllcorner,yllcorner=myproj.yllcorner,cellsize=myproj.cellsize,NODATA_value='nan')
    myproj.writeRaw(G0,'G0')
    pbar.update(6)

    myproj.writeRaw(Le_fr,'Le_fr')
    pbar.update(7)

    if myproj.RnDaily != 'undef':
        myproj.writeRaw(ETdaily,'ETdaily')

    pbar.update(8)

    pbar.finish()

    print 'Done...'
        
    #except Exception, err:
        #log.exception('Error from process():')
        #myproj.logs += log.exception('Error from process():')
        #process_logger.info("ERROR: process aborted")
        
    #finally:
    print "Check sebi-cf.log for more information."
 def test_values_json(self):
     p = Project()
     assert serializers.serialize("json", [p], indent=4) == p.values_json()
 def test_authors_as_list(self):
     p = Project()
     assert '' == p.authors_as_list()
Exemplo n.º 60
0
class LevelEditorBase(DirectObject):
    """ Base Class for Panda3D LevelEditor """ 
    def __init__(self):
        #loadPrcFileData('startup', 'window-type none')
        self.currentFile = None
        
        self.fNeedToSave = False    #if there are unsaved changes
        self.actionEvents = []
        #self.objectMgr = ObjectMgr(self)
        self.fileMgr = FileMgr(self)
        self.actionMgr = ActionMgr()
        self.standaloneExporter = StandaloneExporter(self)
        self.saved = False  #if the project has been saved at all

        self.fMoveCamera = False

        self.NPParent = render

        # define your own config file in inherited class
        self.settingsFile = None

        # you can show/hide specific properties by using propertiesMask and this mode
        self.mode = BitMask32()
        
        self.tempDir = None
        
        self.manipMode = 'translate'
        
        groundRay = CollisionNode('groundRay')
        groundRay.addSolid(CollisionRay(Point3(0,0,0), Vec3(0,0,-1)))
        groundRay.setFromCollideMask(BitMask32.allOn())
        self.groundCollide = render.attachNewNode(groundRay)
        self.groundCollideHandler = CollisionHandlerQueue()
        self.groundCollideTraverser = CollisionTraverser()
        self.groundCollideTraverser.addCollider(self.groundCollide, self.groundCollideHandler)
        
        
    
    def initialize(self):
        """ You should call this in your __init__ method of inherited LevelEditor class """
        # specifiy what obj can be 'selected' as objects
        base.direct.selected.addTag('OBJRoot')

        self.actionEvents.extend([
            # Node path events
            ('DIRECT-select', self.select),
            ('DIRECT-delete', self.handleDelete),
            ('DIRECT-preDeselectAll', self.deselectAll),
            ('DIRECT_deselectAll', self.deselectAllCB),
            ('preRemoveNodePath', self.removeNodePathHook),
            ('DIRECT_deselectedNodePath', self.deselectAllCB),
            ('DIRECT_selectedNodePath_fMulti_fTag_fLEPane', self.selectedNodePathHook),
            ('DIRECT_deselectAll', self.deselectAll),
            ('LE-Undo', self.actionMgr.undo),
            ('LE-Redo', self.actionMgr.redo),
            ('LE-Duplicate', self.ui.onDuplicate),
            ('DIRECT_manipulateObjectCleanup', self.cleanUpManipulating),
            #('LE-MakeLive', self.objectMgr.makeSelectedLive),
            ('LE-NewScene', self.ui.onNew),
            ('LE-SaveScene', self.ui.onSave),
            ('LE-OpenScene', self.ui.onOpen),
            ('LE-Import', self.ui.onImport),
            ('LE-Quit', self.ui.quit),
            ('DIRECT-mouse1', self.handleMouse1),
            ('DIRECT-mouse1Up', self.handleMouse1Up),
            ('DIRECT-mouse2', self.handleMouse2),
            ('DIRECT-mouse2Up', self.handleMouse2Up),
            ('DIRECT-mouse3', self.handleMouse3),
            ('DIRECT-mouse3Up', self.handleMouse3Up),
            ('LE-translateMode', self.translateMode),
            ('LE-rotateMode', self.rotateMode),
            ('LE-scaleMode', self.scaleMode),
            ('LE-localMode', self.localMode),
            ('LE-worldMode', self.worldMode),
            ('LE-DropToGround', self.onDropToGround),
            ('LE-lookAtSelected', self.lookAtSelected),
            ('LE-moveCameraToSelected', self.moveCameraToSelected),
            ('LE-moveAllCamerasToSelected', self.moveAllCamerasToSelected),
            ])

        # Add all the action events
        for event in self.actionEvents:
            if len(event) == 3:
                self.accept(event[0], event[1], event[2])
            else:
                self.accept(event[0], event[1])        

        # editor state text display such as edit mode
        self.statusReadout = OnscreenText(
            pos = (-1.2, 0.9), bg=Vec4(1,1,1,1),
            scale = 0.05, align = TextNode.ALeft,
            mayChange = 1, font = TextNode.getDefaultFont())
        self.statusReadout.setText("")
        # Make sure readout is never lit or drawn in wireframe
        useDirectRenderStyle(self.statusReadout)
        self.statusReadout.reparentTo(hidden)
        self.statusLines = []
        taskMgr.doMethodLater(5, self.updateStatusReadoutTimeouts, 'updateStatus')
        taskMgr.add(self.updateShaders, 'updateShaders')

        self.loadSettings()
        self.reset()
        self.newProj()
        
        self.resetWidgets()
        base.direct.manipulationControl.useSeparateScaleHandles = True
        base.direct.cameraControl.switchDirBelowZero = False
        
        #self.defaultColor = BGC_LIGHT_BLUE
        self.setBackgroundColor(BGC_LIGHT_BLUE)
        
        
    
    #opens a new project in the temp directory
    def newProj(self):
        if self.tempDir and os.path.exists(self.tempDir):
            shutil.rmtree(self.tempDir)
        self.tempDir = os.path.join(Util.getTempDir(), 'NewProj')
        if os.path.exists(self.tempDir):
            for root, dirs, files in os.walk(self.tempDir):
                for f in files:
                    file = os.path.join(root, f)
                    fileAtt = os.stat(file)[0]
                    if (not fileAtt & stat.S_IWRITE):
                        os.chmod(file, stat.S_IWRITE)
                    
            shutil.rmtree(self.tempDir)
        
        projFile = Filename.fromOsSpecific(self.tempDir) + '/New Project.proj'
        self.currentProj = Project(projFile, "New Project")
        #defaultSceneName = "default"
        #self.currentProj.addScene(defaultSceneName, 
        #                          Filename(defaultSceneName+'.scene'))#Filename(projFile.getBasenameWoExtension() + '.scene'))
        #current Scene that the objectMgr manages and saves to
        #self.currentScene = self.currentProj.sceneFilename
        self.currentSceneName = self.currentProj.sceneName
        self.ui.scenesUI.populateTreeFromScenes()#add(defaultSceneName)
        self.projDir = self.currentProj.dir
        self.lib = self.currentProj.lib
        self.saved = False
        self.ui.libraryUI.update()
        self.ui.storyObjUI.update()
        self.ui.soundUI.update()
    
    def setTitleWithFilename(self, filename=""):
        title = self.ui.appname
        if filename != "":
           filenameshort = os.path.basename(filename)
           title = title + " (%s)"%filenameshort
        self.ui.SetLabel(title)

    def removeNodePathHook(self, nodePath):
        if nodePath is None:
            return
        base.direct.deselect(nodePath)
        self.objectMgr.removeObjectByNodePath(nodePath)

        if (base.direct.selected.last != None and nodePath.compareTo(base.direct.selected.last)==0):
            # if base.direct.selected.last is refering to this
            # removed obj, clear the reference
            if (hasattr(__builtins__,'last')):
                __builtins__.last = None
            else:
                __builtins__['last'] = None
            base.direct.selected.last = None

    def handleMouse1(self, modifiers):
        if base.direct.fAlt or modifiers == 4:
            self.fMoveCamera = True
            return

    def handleMouse1Up(self):
        self.fMoveCamera = False
        
        base.direct.fAlt = wx.GetKeyState(wx.WXK_ALT)
        base.direct.fControl = wx.GetKeyState(wx.WXK_CONTROL)
        base.direct.fShift = wx.GetKeyState(wx.WXK_SHIFT)

    def handleMouse2(self, modifiers):
        if base.direct.fAlt or modifiers == 4:
            self.fMoveCamera = True
            return

    def handleMouse2Up(self):
        self.fMoveCamera = False
        
        base.direct.fAlt = wx.GetKeyState(wx.WXK_ALT)
        base.direct.fControl = wx.GetKeyState(wx.WXK_CONTROL)
        base.direct.fShift = wx.GetKeyState(wx.WXK_SHIFT)
        
    def handleMouse3(self, modifiers):
        if base.direct.fAlt or modifiers == 4:
            self.fMoveCamera = True
            return

        self.ui.onRightDown()

    def handleMouse3Up(self):
        self.fMoveCamera = False
        
        base.direct.fAlt = wx.GetKeyState(wx.WXK_ALT)
        base.direct.fControl = wx.GetKeyState(wx.WXK_CONTROL)
        base.direct.fShift = wx.GetKeyState(wx.WXK_SHIFT)

    def handleDelete(self):
        oldSelectedNPs = base.direct.selected.getSelectedAsList()
        oldUIDs = []
        for oldNP in oldSelectedNPs:
            obj = self.objectMgr.findObjectByNodePath(oldNP)
            if obj:
                oldUIDs.append(obj.getName())
        action = ActionDeleteObj(self)
        self.actionMgr.push(action)
        action()

##         reply = wx.MessageBox("Do you want to delete selected?", "Delete?",
##                               wx.YES_NO | wx.ICON_QUESTION)
##         if reply == wx.YES:
##             base.direct.removeAllSelected()
##         else:
##             # need to reset COA
##             dnp = base.direct.selected.last
##             # Update camera controls coa to this point
##             # Coa2Camera = Coa2Dnp * Dnp2Camera
##             mCoa2Camera = dnp.mCoa2Dnp * dnp.getMat(base.direct.camera)
##             row = mCoa2Camera.getRow(3)
##             coa = Vec3(row[0], row[1], row[2])
##             base.direct.cameraControl.updateCoa(coa)

    def translateMode(self, evt=None):
        self.manipMode = 'translate'
        self.resetWidgets()

        self.ui.translateMenuItem.Check()
        
    def rotateMode(self, evt=None):
        self.manipMode = 'rotate'
        self.resetWidgets()
        
        self.ui.rotateMenuItem.Check()
    
    def scaleMode(self, evt=None):
        self.manipMode = 'scale'
        self.resetWidgets()
        
        self.ui.scaleMenuItem.Check()
    
    def worldMode(self, evt=None):
        base.direct.manipulationControl.switchToWorldSpaceMode()
        self.ui.worldMenuItem.Check()
    
    def localMode(self, evt=None):
        base.direct.manipulationControl.switchToLocalSpaceMode()
        self.ui.localMenuItem.Check()
     
    def showWidget(self):
        for widget in base.direct.manipulationControl.widgetList:
            widget.activate()
    
    def hideWidget(self):
        for widget in base.direct.manipulationControl.widgetList:
            widget.deactivate()
     
    def resetWidgets(self):
        for widget in base.direct.manipulationControl.widgetList:
            widget.disableHandles('all')
            if self.manipMode == 'translate':
                widget.enableHandles('post')
            elif self.manipMode == 'rotate':
                widget.enableHandles('ring')
            elif self.manipMode == 'scale':
                widget.enableHandles('scale')

    #makes the camera look at the center of teh bounding box of whatever is selected
    def lookAtSelected(self):
        selected = base.direct.selected.getSelectedAsList()
        if selected:
            bounds = BoundingBox()
            for np in selected:
                b = np.getBounds()
                b.xform(np.getParent().getMat(render))
                bounds.extendBy(b)      
        else:
            bounds = BoundingBox()
            for obj in self.objectMgr.objects.values():
                np = obj.nodePath
                b = np.getBounds()
                b.xform(np.getParent().getMat(render))
                bounds.extendBy(b)
        if bounds.isEmpty() or bounds.isInfinite():
            center = Point3(0, 0, 0)
        else:
            center = Point3((bounds.getMax() + bounds.getMin()) / 2.0)
        
        np = NodePath('temp')
        np.setPos(self.ui.perspView.camera.getPos())
        np.lookAt(center)
        i = LerpHprInterval(self.ui.perspView.camera, 1.0, np.getHpr(), blendType='easeInOut')
        i.start()
        base.direct.cameraControl.coaMarkerPos.assign(center)
        np.removeNode()
    
    #moves the camera to the outside of the bounding box of whatever is selected and looks at it
    def moveCameraToSelected(self):
        selected = base.direct.selected.getSelectedAsList()
        if selected:
            bounds = BoundingBox()
            for np in selected:
                b = np.getBounds()
                b.xform(np.getParent().getMat(render))
                bounds.extendBy(b)      
        else:
            bounds = BoundingBox()
            for obj in self.objectMgr.objects.values():
                np = obj.nodePath
                b = np.getBounds()
                b.xform(np.getParent().getMat(render))
                bounds.extendBy(b)
        
        if bounds.isEmpty() or bounds.isInfinite():
            center = Point3(0, 0, 0)
            targetPos = Point3(-19, -19, 19)
        else:
            center = Point3((bounds.getMax() + bounds.getMin()) / 2.0)
            diff = self.ui.perspView.camera.getPos() - center
            diff.normalize()
            targetPos = center + diff * (bounds.getMax() - bounds.getMin()).length() * 1.8
        
        np = NodePath('temp')
        np.setPos(targetPos)
        np.lookAt(center)
        i = LerpPosHprInterval(self.ui.perspView.camera, 1, targetPos, np.getHpr(), blendType='easeInOut')
        i.start()
        base.direct.cameraControl.coaMarkerPos.assign(center)
        np.removeNode()
    
    #moves all cameras(perspective and the 3 ortho cameras) to focus on the selected object
    def moveAllCamerasToSelected(self):
        selected = base.direct.selected.getSelectedAsList()
        if selected:
            bounds = BoundingBox()
            for np in selected:
                b = np.getBounds()
                b.xform(np.getParent().getMat(render))
                bounds.extendBy(b)        
        else:
            bounds = BoundingBox()
            for obj in self.objectMgr.objects.values():
                np = obj.nodePath
                b = np.getBounds()
                b.xform(np.getParent().getMat(render))
                bounds.extendBy(b)
        
        #perspective
        if bounds.isEmpty() or bounds.isInfinite():
                center = Point3(0, 0, 0)
                targetPos = Point3(-19, -19, 19)
        else:
            center = Point3((bounds.getMax() + bounds.getMin()) / 2.0)
            diff = self.ui.perspView.camera.getPos() - center
            diff.normalize()
            targetPos = center + diff * (bounds.getMax() - bounds.getMin()).length() * 1.8
        
        np = NodePath('temp')
        np.setPos(targetPos)
        np.lookAt(center)
        i = LerpPosHprInterval(self.ui.perspView.camera, 1, targetPos, np.getHpr(), blendType='easeInOut')
        i.start()
        base.direct.cameraControl.coaMarkerPos.assign(center)
        np.removeNode()
        
        #top
        if bounds.isEmpty() or bounds.isInfinite():
            targetPos = Point3(0, 0, 600)
            base.direct.drList[base.camList.index(NodePath(self.ui.topView.camNode))].orthoFactor = 0.1
            
        else:
            targetPos = Point3((bounds.getMax().getX() + bounds.getMin().getX()) / 2.0, (bounds.getMax().getY() + bounds.getMin().getY()) / 2.0, bounds.getMax().getZ() + 600)
            size = max( (bounds.getMax().getX() - bounds.getMin().getX()), (bounds.getMax().getY() - bounds.getMin().getY()))
            base.direct.drList[base.camList.index(NodePath(self.ui.topView.camNode))].orthoFactor = size / min(self.ui.topView.ClientSize.GetWidth(), self.ui.topView.ClientSize.GetHeight() )
            
        x = self.ui.topView.ClientSize.GetWidth() * base.direct.drList[base.camList.index(NodePath(self.ui.topView.camNode))].orthoFactor
        y = self.ui.topView.ClientSize.GetHeight() * base.direct.drList[base.camList.index(NodePath(self.ui.topView.camNode))].orthoFactor
        i = LerpFunc(self.orthoPosFilmSizeInterval, extraArgs=[self.ui.topView.camera, self.ui.topView.camLens, self.ui.topView.camera.getPos(), targetPos,\
        self.ui.topView.camLens.getFilmSize().getX(), x, self.ui.topView.camLens.getFilmSize().getY(), y], blendType = 'noBlend', duration=1)
        i.start()
        
        #right
        if bounds.isEmpty() or bounds.isInfinite():
            targetPos = Point3(600, 0, 0)
            base.direct.drList[base.camList.index(NodePath(self.ui.leftView.camNode))].orthoFactor = 0.1
            
        else:
            targetPos = Point3(bounds.getMax().getX() + 600, (bounds.getMax().getY() + bounds.getMin().getY()) / 2.0, (bounds.getMax().getZ() + bounds.getMin().getZ()) / 2.0)
            size = max( (bounds.getMax().getY() - bounds.getMin().getY()), (bounds.getMax().getZ() - bounds.getMin().getZ()))
            base.direct.drList[base.camList.index(NodePath(self.ui.leftView.camNode))].orthoFactor = size / min(self.ui.leftView.ClientSize.GetWidth(), self.ui.leftView.ClientSize.GetHeight() )
            
        x = self.ui.leftView.ClientSize.GetWidth() * base.direct.drList[base.camList.index(NodePath(self.ui.leftView.camNode))].orthoFactor
        y = self.ui.leftView.ClientSize.GetHeight() * base.direct.drList[base.camList.index(NodePath(self.ui.leftView.camNode))].orthoFactor
        i = LerpFunc(self.orthoPosFilmSizeInterval, extraArgs=[self.ui.leftView.camera, self.ui.leftView.camLens, self.ui.leftView.camera.getPos(), targetPos,\
        self.ui.leftView.camLens.getFilmSize().getX(), x, self.ui.leftView.camLens.getFilmSize().getY(), y], blendType = 'noBlend', duration=1)
        i.start()
        
        #front
        if bounds.isEmpty() or bounds.isInfinite():
            targetPos = Point3(0, -600, 0)
            base.direct.drList[base.camList.index(NodePath(self.ui.frontView.camNode))].orthoFactor = 0.1
            
        else:
            targetPos = Point3((bounds.getMax().getX() + bounds.getMin().getX()) / 2.0, bounds.getMin().getY() - 600, (bounds.getMax().getZ() + bounds.getMin().getZ()) / 2.0)
            size = max( (bounds.getMax().getX() - bounds.getMin().getX()), (bounds.getMax().getZ() - bounds.getMin().getZ()))
            base.direct.drList[base.camList.index(NodePath(self.ui.frontView.camNode))].orthoFactor = size / min(self.ui.frontView.ClientSize.GetWidth(), self.ui.frontView.ClientSize.GetHeight() )
            
        x = self.ui.frontView.ClientSize.GetWidth() * base.direct.drList[base.camList.index(NodePath(self.ui.frontView.camNode))].orthoFactor
        y = self.ui.frontView.ClientSize.GetHeight() * base.direct.drList[base.camList.index(NodePath(self.ui.frontView.camNode))].orthoFactor
        i = LerpFunc(self.orthoPosFilmSizeInterval, extraArgs=[self.ui.frontView.camera, self.ui.frontView.camLens, self.ui.frontView.camera.getPos(), targetPos,\
        self.ui.frontView.camLens.getFilmSize().getX(), x, self.ui.frontView.camLens.getFilmSize().getY(), y], blendType = 'noBlend', duration=1)
        i.start()
        
            
    def orthoPosFilmSizeInterval(self, t, camera, camLens, beginPos, endPos, beginX, endX, beginY, endY):
        camera.setPos(beginPos * (1-t) + endPos * t)
        camLens.setFilmSize(beginX * (1-t) + endX * t, beginY * (1-t) + endY * t)
        
    def cleanUpManipulating(self, selectedNPs):
        for np in selectedNPs:
            obj = self.objectMgr.findObjectByNodePath(np)
            if obj and np.getMat() != self.objectMgr.objectsLastXform[obj.getName()]:
                action = ActionTransformObj(self, obj.getName(), Mat4(np.getMat()))
                self.actionMgr.push(action)
                action()

    def select(self, nodePath, fMultiSelect=0, fSelectTag=1, fResetAncestry=1, fLEPane=0, fUndo=1):
        base.direct.toggleWidgetVis()
        if fUndo:
            # Select tagged object if present
            if fSelectTag:
                for tag in base.direct.selected.tagList:
                    if nodePath.hasNetTag(tag):
                        nodePath = nodePath.findNetTag(tag)
                        break
            action = ActionSelectObj(self, nodePath, fMultiSelect=fMultiSelect, fSelectTag=fSelectTag, fResetAncestry=fResetAncestry,fLEPane=fLEPane)
            self.actionMgr.push(action)
            action()
        else:
            base.direct.selectCB(nodePath, fMultiSelect, fSelectTag, fResetAncestry, fLEPane, fUndo)
            
        if base.direct.selected.getSelectedAsList:
            self.showWidget()

    def selectedNodePathHook(self, nodePath, fMultiSelect = 0, fSelectTag = 1, fLEPane = 0):
        # handle unpickable nodepath
        if nodePath.getName() in base.direct.iRay.unpickable:
            base.direct.deselect(nodePath)
            return

        if fMultiSelect == 0 and fLEPane == 0:
           oldSelectedNPs = base.direct.selected.getSelectedAsList()
           for oldNP in oldSelectedNPs:
              obj = self.objectMgr.findObjectByNodePath(oldNP)
              if obj:
                 self.ui.sceneGraphUI.deSelect(obj.getName())
        self.objectMgr.selectObject(nodePath, fLEPane, fMultiSelect)
        self.ui.buildContextMenu(nodePath)
        
        
    def deselectAll(self, np=None):
        self.hideWidget()
        self.objectMgr.deselectAll()
        if len(base.direct.selected.getSelectedAsList()) ==0:
            return
        action = ActionDeselectAll(self)
        self.actionMgr.push(action)
        action()

    def deselectAllCB(self, dnp=None):
        if not dnp:
            self.objectMgr.deselectAll()
            self.editor.ui.sceneGraphUI.tree.UnselectAll()
        else:
            obj = self.objectMgr.findObjectByNodePath(dnp)
            if obj:
                self.ui.sceneGraphUI.deSelect(obj.name)
        
    def reset(self, resetViews=True):
        if self.fNeedToSave:
            reply = wx.MessageBox("Do you want to save the current project?", "Save?",
                               wx.YES_NO | wx.ICON_QUESTION)
            if reply == wx.YES:
                result = self.ui.onSave()
                if result == False:
                    return

        base.direct.deselectAll()
        self.ui.reset()
        self.objectMgr.reset()
        self.actionMgr.reset()
        self.soundMgr.reset()
        self.journalMgr.reset()
        self.inventoryMgr.reset()
        if resetViews:
            self.ui.perspView.camera.setPos(-19, -19, 19)
            self.ui.perspView.camera.lookAt(Point3(0, 0, 0))
            self.ui.leftView.camera.setPos(600, 0, 0)
            self.ui.frontView.camera.setPos(0, -600, 0)
            self.ui.topView.camera.setPos(0, 0, 600)
            self.resetOrthoCam(self.ui.topView)
            self.resetOrthoCam(self.ui.frontView)
            self.resetOrthoCam(self.ui.leftView)
        self.fNeedToSave = False
        self.setTitleWithFilename()
    
    def resetScene(self):
        if self.fNeedToSave:
            reply = wx.MessageBox("With Switching Scenes you will lose the previous Scene.\n Do you want to save the current project?", "Save?",
                               wx.YES_NO | wx.ICON_QUESTION)
            if reply == wx.YES:
                result = self.ui.onSave()
                if result == False:
                    return
        base.direct.deselectAll()
        self.objectMgr.reset()
        self.actionMgr.reset()
        self.soundMgr.reset()# May not reset this
        self.fNeedToSave = False
        self.setTitleWithFilename()
        
        
        
    def resetOrthoCam(self, view):
        base.direct.drList[base.camList.index(NodePath(view.camNode))].orthoFactor = 0.1
        x = view.ClientSize.GetWidth() * 0.1
        y = view.ClientSize.GetHeight() * 0.1
        view.camLens.setFilmSize(x, y)
        
    def save(self):
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
        #check to make sure everything is writable
        try:
            f = open(self.currentProj.filename.toOsSpecific(), 'a')
            f.close()
        except IOError as e:
            dlg = wx.MessageDialog(self.ui, "The project file " +\
            " could not be written.  Make sure it is not marked read-only and try again",\
            caption = "Save Error", style=wx.ICON_ERROR|wx.OK)
            dlg.ShowModal()
            self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            return
            
        try:
            f = open((self.projDir + '/' + self.currentProj.getScene(self.currentSceneName).getFullpath()).toOsSpecific(), 'a')
            f.close()
        except IOError as e:
            dlg = wx.MessageDialog(self.ui, "The scene file "  +\
            " could not be written.  Make sure it is not marked read-only and try again",\
            caption = "Save Error", style=wx.ICON_ERROR|wx.OK)
            dlg.ShowModal()
            self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            return
            
        try:
            f = open((self.projDir + '/' + 'lib.index').toOsSpecific(), 'a')
            f.close()
        except IOError as e:
            dlg = wx.MessageDialog(self.ui, "The library index file " +\
            " could not be written.  Make sure it is not marked read-only and try again",\
            caption = "Save Error", style=wx.ICON_ERROR|wx.OK)
            dlg.ShowModal()
            self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            return
        
        try:
            f = open((self.projDir + '/' +  self.currentProj.journalFilename.getFullpath()).toOsSpecific(), 'a')
            f.close()
        except IOError as e:
            dlg = wx.MessageDialog(self.ui, "The journal file " +\
            " could not be written.  Make sure it is not marked read-only and try again",\
            caption = "Save Error", style=wx.ICON_ERROR|wx.OK)
            dlg.ShowModal()
            self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            return
        
        self.currentProj.saveToFile()
        self.fileMgr.saveToFile(self.projDir + '/' + self.currentProj.getScene(self.currentSceneName).getFullpath())
        self.fileMgr.saveJournalToFile(self.projDir+'/'+self.currentProj.journalFilename.getFullpath())
        self.fileMgr.saveInventoryMapToFile(self.projDir+'/'+self.currentProj.inventoryMapFilename.getFullpath())
        self.lib.saveToFile()
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

    def saveAs(self, fileName, projName):
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
        self.currentProj.saveAs(fileName, projName, self.saved)
        self.tempDir = None
        self.projDir = self.currentProj.dir
        self.fileMgr.saveToFile(self.projDir + '/' + self.currentProj.getScene(self.currentSceneName).getFullpath())
        self.fileMgr.saveJournalToFile(self.projDir+'/'+self.currentProj.journalFilename.getFullpath())
        self.fileMgr.saveInventoryMapToFile(self.projDir+'/'+self.currentProj.inventoryMapFilename.getFullpath())
        self.saved = True
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
        
#    def createSceneFile(self,sceneFile):
#        try:
#            f = open((self.projDir + '/' + sceneFile.getFullpath()).toOsSpecific(), 'a')
#            f.close()
#        except IOError as e:
#            dlg = wx.MessageDialog(self.ui, "The scene file "  +\
#            " could not be written.  Make sure it is not marked read-only and try again",\
#            caption = "Save Error", style=wx.ICON_ERROR|wx.OK)
#            dlg.ShowModal()
#            self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
#            return

    def load(self, fileName, resetViews=True, setSaved=True):
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
        self.reset(resetViews=resetViews)
        self.currentProj = Project(fileName)
        self.projDir = self.currentProj.dir
        self.lib = self.currentProj.lib
        
        #make sure we get updated versions of assets
        ModelPool.releaseAllModels()
        TexturePool.releaseAllTextures()
        ShaderPool.releaseAllShaders()
        
        self.currentSceneName = self.currentProj.sceneName
        self.fileMgr.loadFromFile(self.projDir + '/' +self.currentProj.getScene(self.currentSceneName).getFullpath())
        self.fileMgr.loadJournalFromFile(self.projDir+'/'+self.currentProj.journalFilename.getFullpath())
        self.fileMgr.loadInventoryMapFromFile(self.projDir+'/'+self.currentProj.inventoryMapFilename.getFullpath())
        if setSaved:
            self.saved = True
        
        #self.currenScene = self.currentProj.sceneFilename
        self.ui.scenesUI.populateTreeFromScenes()
        
        self.objectMgr.updateMainCharWidget() #[antonjs 4/14/11]
        
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

    #Cosider to change merging projects: Maybe just merging scenes?
    def mergeProject(self, fileName, prefix='', newNodeName= ''):
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
        otherProj = Project(fileName)
        if not prefix:
            prefix = otherProj.name
        try:
            self.lib.checkLibrary(otherProj.lib, prefix)
        except Exception as e:
            print 'ERROR:Could not merge libraries'
            self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            raise e
            return
            
        self.lib.mergeWith(otherProj.lib, prefix, saveAfter=True)
        try:
            self.fileMgr.loadFromFile(otherProj.dir + '/' + otherProj.scenes[otherProj.sceneName].getFullpath(), merge=True, lib=otherProj.lib, otherName=prefix, newNodeName= newNodeName)
        except Util.SceneMergeError as e:
            print 'ERROR:could not merge scenes'
            self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            traceback.print_exc(file=sys.stdout)
            return
        
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
        self.ui.libraryUI.update()
        self.ui.storyObjUI.update()
        self.ui.soundUI.update()
        self.objectMgr.updateMainCharWidget() #[antonjs 4/14/11]
        
        self.fNeedToSave = True
        
    def saveSettings(self):
        if self.settingsFile is None:
            return
        
        try:
            f = open(self.settingsFile, 'w')
            f.write('gridSize\n%f\n'%self.ui.perspView.grid.gridSize)
            f.write('gridSpacing\n%f\n'%self.ui.perspView.grid.gridSpacing)
            f.write('hotKey\n%s\n'%base.direct.hotKeyMap)
            f.close()
        except:
            pass        

    def loadSettings(self):
        base.direct.hotKeyMap = {   
            'control-y': ('Redo', 'LE-Redo'),
            'shift-v': ('Toggle Marker', 'DIRECT-toggleMarkerVis'),
            'control-n': ('New Scene', 'LE-NewScene'),
            'control-s': ('Save Scene', 'LE-SaveScene'),
            'escape': ('Deselect All', 'deselectAll'),
            'control-z': ('Undo', 'LE-Undo'),
            ',': ('Scale Down Widget', 'DIRECT-widgetScaleDown'),
            '.': ('Scale Up Widget', 'DIRECT-widgetScaleUp'),
            'control-o': ('Open Scene', 'LE-OpenScene'),
            'control-q': ('Quit', 'LE-Quit'),
            'control-i': ('Import', 'LE-Import'),
            # 'b': ('Toggle Backface', 'DIRECT-toggleBackface'),
            #'f': ('Fit on Widget', 'DIRECT-fitOnWidget'),
            # 't': ('Toggle Textures', 'DIRECT-toggleTexture'),
            't': ('Toggle Wireframe', 'DIRECT-toggleWireframe'),
            'f' : ('Look at Selected', 'LE-lookAtSelected'),
            'c' : ('Move Camera to Selected', 'LE-moveCameraToSelected'),
            'shift-c' : ('Move All Cameras to Selected', 'LE-moveAllCamerasToSelected'),
            'w': ('Enter Translate Mode', 'LE-translateMode'),
            'e': ('Enter Rotate Mode', 'LE-rotateMode'),
            'r': ('Enter Scale Mode', 'LE-scaleMode'),
            'delete': ('Delete', 'DIRECT-delete'),
            'control-g': ('Drop Selected to Ground', 'LE-DropToGround'),
            'control-d': ('Duplicate', 'LE-Duplicate')}
        
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_WAIT))
        try:
            f = open(self.settingsFile, 'r')
            configLines = f.readlines()
            f.close()

            gridSize = 100.0
            gridSpacing = 5.0
            for i in range(0, len(configLines)):
                line = configLines[i]
                i = i + 1
                if line.startswith('gridSize'):
                    gridSize = float(configLines[i])
                elif line.startswith('gridSpacing'):
                    gridSpacing = float(configLines[i])
                elif line.startswith('hotKey'):
                    customHotKeyMap = eval(configLines[i])
                    customHotKeyDict = {}
                    for hotKey in customHotKeyMap.keys():
                        desc = customHotKeyMap[hotKey]
                        customHotKeyDict[desc[1]] = hotKey

                    overriddenKeys = []
                    for key in base.direct.hotKeyMap.keys():
                        desc = base.direct.hotKeyMap[key]
                        if desc[1] in customHotKeyDict.keys():
                            overriddenKeys.append(key)

                    for key in overriddenKeys:
                        del base.direct.hotKeyMap[key]
                            
                    base.direct.hotKeyMap.update(customHotKeyMap)

            self.ui.updateGrids(gridSize, gridSpacing)
            self.ui.updateMenu()
        except:
            base.direct.hotKeyMap = {   
            'control-y': ('Redo', 'LE-Redo'),
            'shift-v': ('Toggle Marker', 'DIRECT-toggleMarkerVis'),
            'control-n': ('New Scene', 'LE-NewScene'),
            'control-s': ('Save Scene', 'LE-SaveScene'),
            'escape': ('Deselect All', 'deselectAll'),
            'control-z': ('Undo', 'LE-Undo'),
            ',': ('Scale Down Widget', 'DIRECT-widgetScaleDown'),
            '.': ('Scale Up Widget', 'DIRECT-widgetScaleUp'),
            'control-o': ('Open Scene', 'LE-OpenScene'),
            'control-q': ('Quit', 'LE-Quit'),
            'control-i': ('Import', 'LE-Import'),
            # 'b': ('Toggle Backface', 'DIRECT-toggleBackface'),
            #'f': ('Fit on Widget', 'DIRECT-fitOnWidget'),
            # 't': ('Toggle Textures', 'DIRECT-toggleTexture'),
            't': ('Toggle Wireframe', 'DIRECT-toggleWireframe'),
            'f' : ('Look at Selected', 'LE-lookAtSelected'),
            'c' : ('Move Camera to Selected', 'LE-moveCameraToSelected'),
            'shift-c' : ('Move All Cameras to Selected', 'LE-moveAllCamerasToSelected'),
            'w': ('Enter Translate Mode', 'LE-translateMode'),
            'e': ('Enter Rotate Mode', 'LE-rotateMode'),
            'r': ('Enter Scale Mode', 'LE-scaleMode'),
            'g': ('Switch to World Space Manipulation', 'LE-worldMode'),
            'l': ('Switch to Local Space Manipulation', 'LE-localMode'),
            'delete': ('Delete', 'DIRECT-delete'),
            'control-g': ('Drop Selected to Ground', 'LE-DropToGround'),
            'control-d': ('Duplicate', 'LE-Duplicate')}
            self.ui.updateMenu()
        self.ui.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))

    def convertMaya(self, modelname, callBack, obj=None, isAnim=False):
        if obj and isAnim:
            mayaConverter = MayaConverter(self.ui, self, modelname, callBack, obj, isAnim)
        else:
            reply = wx.MessageBox("Is it an animation file?", "Animation?",
                              wx.YES_NO | wx.ICON_QUESTION)
            if reply == wx.YES:
                mayaConverter = MayaConverter(self.ui, self, modelname, callBack, None, True)
            else:        
                mayaConverter = MayaConverter(self.ui, self, modelname, callBack, None, False)
        mayaConverter.Show()

    def convertFromMaya(self, modelname, callBack):
        mayaConverter = MayaConverter(self.ui, self, modelname, callBack, None, False)
        mayaConverter.Show()

    def updateStatusReadout(self, status, color=None):
        if status:
            # add new status line, first check to see if it already exists
            alreadyExists = False
            for currLine in self.statusLines:
                if (status == currLine[1]):
                    alreadyExists = True
                    break
            if (alreadyExists == False):
                time = globalClock.getRealTime() + 15
                self.statusLines.append([time,status,color])

        # update display of new status lines
        self.statusReadout.reparentTo(aspect2d)
        statusText = ""
        lastColor = None
        for currLine in self.statusLines:
            statusText += currLine[1] + '\n'
            lastColor = currLine[2]
        self.statusReadout.setText(statusText)
        if (lastColor):
            self.statusReadout.textNode.setCardColor(
                lastColor[0], lastColor[1], lastColor[2], lastColor[3])
            self.statusReadout.textNode.setCardAsMargin(0.1, 0.1, 0.1, 0.1)
        else:
            self.statusReadout.textNode.setCardColor(1,1,1,1)
            self.statusReadout.textNode.setCardAsMargin(0.1, 0.1, 0.1, 0.1)
            
    def updateStatusReadoutTimeouts(self,task=None):
        removalList = []
        for currLine in self.statusLines:
            if (globalClock.getRealTime() >= currLine[0]):
                removalList.append(currLine)
        for currRemoval in removalList:
            self.statusLines.remove(currRemoval)
        self.updateStatusReadout(None)
        # perform doMethodLater again after delay
        # This crashes when CTRL-C'ing, so this is a cheap hack.
        #return 2
        from direct.task import Task
        return Task.again

    def updateShaders(self, task):
        for obj in self.objectMgr.objects.values():
            if obj.shader and obj.shaderActive:
                obj.shader.update()
        return task.cont
        
    def propMeetsReq(self, typeName, parentNP):
        parentNP[0] = None
        return True
    
    def onDropToGround(self, evt=None):
        action = ActionDropSelectedToGround(self)
        self.actionMgr.push(action)
        action()
    
    def dropSelectedToGround(self):
        selected = base.direct.selected.getSelectedAsList()
        toDrop = set(selected)
        
        origParents = {}
        
        for np in toDrop:
            for otherNP in toDrop:
                if np != otherNP and otherNP.isAncestorOf(np):
                    origParents[np] = np.getParent()
                    np.wrtReparentTo(render)
                    break

        for np in toDrop:
            self.dropToGround(np)
                    
        for np, parent in origParents.iteritems():
            np.wrtReparentTo(parent)
            
    def dropToGround(self, np):
        self.groundCollide.setPos(np.getPos(render))
        
        self.groundCollideTraverser.traverse(render)
        
        if self.groundCollideHandler.getNumEntries() > 0:
            self.groundCollideHandler.sortEntries()
            for e in self.groundCollideHandler.getEntries():
                hitNP = e.getIntoNodePath()
                if hitNP.hasNetTag('OBJRoot'):
                    hitObj = hitNP.findNetTag('OBJRoot')
                    if hitObj.hasTag('LE-ground'):
                        np.setZ(render, e.getSurfacePoint(render).getZ())
                        return
    
        
                    
    def openScene(self, sceneName):
        self.ui.sceneGraphUI.reset()
        self.ui.soundUI.reset()
        sceneFile = self.currentProj.getScene(sceneName)
        #self.currentScene = sceneFile
        
        if(sceneName.strip().startswith("interior_")):
            self.setBackgroundColor(BGC_DARK_GREY)
        else:
            self.setBackgroundColor(BGC_LIGHT_BLUE)
        
        self.currentSceneName = sceneName
        f = Filename(sceneFile)
        f.setDirname(self.currentProj.dir.getFullpath())

        if os.path.exists(f.toOsSpecific()):
            self.fileMgr.loadFromFile(self.projDir + '/' +self.currentProj.getScene(self.currentSceneName).getFullpath())
        
        self.objectMgr.updateMainCharWidget() #[antonjs 4/14/11]
    
    def addScene(self):
        name, scenefile = self.currentProj.addScene()
        #create an empty sceneFile
        #cr
        doc = xml.dom.minidom.Document()
        root = doc.createElement("scene")
        doc.appendChild(root)
        root.appendChild(doc.createElement("objects"))
        root.appendChild(doc.createElement("layers"))
        root.appendChild(doc.createElement("sounds"))
        
        try:
            filename = self.projDir + '/' + scenefile.getFullpath()
            f = open(filename.toOsSpecific(), 'w')
            f.write(doc.toprettyxml())
            f.close()
        except IOError:
            raise SceneSaveError(filename.toOsSpecific())
        return name
        
    
    def removeScene(self, sceneName, delFile = False):
        toDelSceneFile = self.currentProj.getScene(sceneName)
        self.currentProj.removeScene(sceneName, delFile)
        #if the scene to remove the current Scene get the 
        if(self.currentSceneName == sceneName):
            self.openScene(self.currentProj.sceneName)
        #self.ui.onSave()
        #self.currentScene = self.currentProj.getOpeningScene()
        
        if(self.saved):
            self.save()
            
    def renameScene(self, name, newName):
        self.currentProj.renameScene(name,newName)
        if(self.currentSceneName == name):
            self.currentSceneName = newName
            if(newName.strip().startswith("interior_")):
                self.setBackgroundColor(BGC_DARK_GREY)
            else:
                self.setBackgroundColor(BGC_LIGHT_BLUE)
            
    def addEmptyTerrain(self):
        no = 0
        name =  self.currentSceneName+'_terrain'+str(no)
        tempFilePath = base.le.lib.projDir.toOsSpecific() + '/' + name+ '.png'
        assetFilename = Filename(tempFilePath)
        
        targetFilename = Filename(assetFilename)
        targetFilename.setDirname(self.currentProj.dir.getFullpath()+'/Textures')
        
        while os.path.exists(targetFilename.toOsSpecific()):
            no += 1
            tempFilePath = base.le.lib.projDir.toOsSpecific() + '/' + name+str(no)+ '.png'
            assetFilename = Filename(tempFilePath)
            targetFilename = Filename(assetFilename)
            targetFilename.setDirname(self.currentProj.dir.getFullpath()+'/Textures')
            
        
        tempImage = PNMImage(513,513)
        tempImage.fill(.5,.5,.5)
        tempImage.write(assetFilename)  
        
        no = 0
        #add the new terrain to the library
        asset = Terrain(name, assetFilename)
        while(1):
            try:
                base.le.lib.addTerrain(asset, True)
                break
            except:
                pass
                no += 1
                name =  self.currentSceneName+'_terrain'+str(no)
                #tempFilePath = base.le.lib.projDir.toOsSpecific() + '/' + name+ '.png'
                #assetFilename = Filename(tempFilePath)
                asset = Terrain(name, assetFilename)
            else:
                break
                        
        base.le.ui.libraryUI.update()
            
        #== Remove the temporary source file
        tempFilename = Filename(tempFilePath)
        #print 'temporary file path to now delete: ' + tempFilename.toOsSpecific()
        os.remove(tempFilename.toOsSpecific())
        
        pos = Vec3(512*(-.5), 512*(-.5), -128)            
        action = ActionAddNewObj(self, "Terrains", name = "terrain_"+name + ':1', asset=asset, anims={}, parent=None, pos=pos)
        self.actionMgr.push(action)
        newobj = action()
        newobj.getNodePath().setScale(1.,1.,255)
    
    #Color should a Vec4
    def setBackgroundColor(self, color):
        for i in range(4):
            base.winList[i].setClearColor(color)