def GetProjectFolderNameFromRevitProjectFilePath(revitProjectFilePath):
    projectFolderName = None
    # NOTE: called Path.GetDirectoryName() before expanding the path (rather than after) in
    # order to reduce the risk of hitting .NET path length limit (260 characters?)
    folderPath = ExpandedFullNetworkPath(
        Path.GetDirectoryName(revitProjectFilePath))
    parts = GetDirectoryParts(folderPath)
    numberOfParts = len(parts)
    if numberOfParts > (2):
        if IsProjectYearFolderName(parts[1]):
            projectFolderName = parts[2]
    return projectFolderName
Beispiel #2
0
def getGameDirectory(game='Skyrim'):
    from System.IO import Path
    from Microsoft.Win32 import Registry, RegistryValueOptions
    key = Registry.LocalMachine.OpenSubKey(
        r"SOFTWARE\Wow6432Node\Bethesda Softworks\%s" % game)
    if not key:
        key = Registry.LocalMachine.OpenSubKey(
            r"SOFTWARE\Bethesda Softworks\%s" % game)
    result = key.GetValue("Installed Path", '', RegistryValueOptions.None)
    if key: key.Dispose()
    if not result: return None
    return Path.Combine(result, "Data") + Path.DirectorySeparatorChar
Beispiel #3
0
    def setUp(self):
        super(SuperConsoleTest, self).setUp()
        
        import clr

        #if this is a debug build and the assemblies are being saved...peverify is run.
        #for the test to pass, Maui assemblies must be in the AssembliesDir
        if is_peverify_run:
            AddReferenceToDlrCore()
            clr.AddReference("Microsoft.Scripting")
            from Microsoft.Scripting.Runtime import ScriptDomainManager
            from System.IO import Path

            tempMauiDir = Path.GetTempPath()
            
            print "Copying Maui.Core.dll to %s for peverify..." % (tempMauiDir)
            if not File.Exists(tempMauiDir + '\\Maui.Core.dll'):
                File.Copy(testpath.rowan_root + '\\Util\\Internal\\Maui_old\\Maui.Core.dll',
                        tempMauiDir + '\\Maui.Core.dll')

        #Cleanup the last run
        for t_name in ['ip_session.log', 'ip_session_stderr.log']:
            if File.Exists(t_name):
                File.Delete(t_name)
            Assert(not File.Exists(t_name))

        sys.path.append(testpath.rowan_root + '\\Util\\Internal\\Maui_old')
        try:
            clr.AddReference('Maui.Core.dll')
        except:
            print "test_superconsole.py failed: cannot load Maui.Core assembly"
            sys.exit(int(is_snap))

        from Maui.Core import App
        proc = Process()
        proc.StartInfo.FileName = sys.executable
        proc.StartInfo.WorkingDirectory = testpath.rowan_root + '\\Languages\\IronPython\\Tests'
        proc.StartInfo.Arguments = '-X:TabCompletion -X:AutoIndent -X:ColorfulConsole'
        proc.StartInfo.UseShellExecute = True
        proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal
        proc.StartInfo.CreateNoWindow = False
        started = proc.Start()

        try:
            superConsole = App(proc.Id)
        except Exception as e:
            print "test_superconsole.py failed: cannot initialize App object (probably running as service, or in minimized remote window)"
            print "On VSLGO-MAUI machines close all remote desktop sessions using EXIT command on desktop!"
            proc.Kill()
            sys.exit(1) 
            
        superConsole.SendKeys('from pretest import *{ENTER}')
Beispiel #4
0
def GetSnapshotData(sessionId, revitFilePath, snapshotStartTime,
                    snapshotEndTime, snapshotFolderPath, revitJournalFilePath,
                    snapshotError):
    projectFolderName = path_util.GetProjectFolderNameFromRevitProjectFilePath(
        revitFilePath)
    projectModelFolderPath = Path.GetDirectoryName(revitFilePath)
    modelName = snapshot_data_util.GetRevitModelName(revitFilePath)
    modelFileLastModified = path_util.GetLastWriteTimeUtc(revitFilePath)
    modelFileSize = path_util.GetFileSize(revitFilePath)
    modelRevitVersion = revit_file_util.GetRevitFileVersion(revitFilePath)
    modelRevitVersionDetails = snapshot_data_util.GetRevitFileVersionDetails(
        revitFilePath)

    snapshotData = {
        "projectFolderName":
        projectFolderName,
        "modelFolder":
        path_util.ExpandedFullNetworkPath(projectModelFolderPath),
        "modelName":
        modelName,
        "modelFileLastModified":
        (time_util.GetTimestampObject(modelFileLastModified)
         if modelFileLastModified is not None else None),
        "modelFileSize":
        modelFileSize,
        "modelRevitVersion":
        modelRevitVersion,
        "modelRevitVersionDetails":
        modelRevitVersionDetails,
        "snapshotStartTime": (time_util.GetTimestampObject(snapshotStartTime)
                              if snapshotStartTime is not None else None),
        "snapshotEndTime": (time_util.GetTimestampObject(snapshotEndTime)
                            if snapshotEndTime is not None else None),
        "sessionId":
        sessionId,
        "snapshotFolder":
        path_util.ExpandedFullNetworkPath(snapshotFolderPath),
        "snapshotError":
        snapshotError,
        "username":
        environment.GetUserName(),
        "machineName":
        environment.GetMachineName(),
        "gatewayAddresses":
        network_util.GetGatewayAddresses(),
        "ipAddresses":
        network_util.GetIPAddresses(),
        snapshot_data_util.SNAPSHOT_DATA__REVIT_JOURNAL_FILE:
        revitJournalFilePath
    }

    return snapshotData
def genPeverifyInteropAsm(file):
    #if this isn't a test run that will invoke peverify there's no point in
    #continuing
    if not is_peverify_run: 
        return
    else:
        mod_name = file.rsplit("\\", 1)[1].split(".py")[0]
        print "Generating interop assemblies for the", mod_name, "test module which are needed in %TEMP% by peverify..."
        from System.IO import Path
        tempDir = Path.GetTempPath()
        cwd = nt.getcwd()
    
    #maps COM interop test module names to a list of DLLs
    module_dll_dict = {
        "excel" :          [],
        "msagent" :        [agentsvr_path],
        "scriptpw" :       [scriptpw_path],
        "word" :           [],
    }
    
    dlrcomlib_list = [  "dlrcomserver", "paramsinretval", "method", "obj", "prop",  ]
    if is_cli32:
        temp_name = testpath.rowan_root + "\\Test\\DlrComLibrary\\Debug\\DlrComLibrary.dll" 
    else:
        temp_name = testpath.rowan_root + "\\Test\\DlrComLibrary\\x64\\Release\\DlrComLibrary.dll" 
    for mod_name in dlrcomlib_list: module_dll_dict[mod_name] = [ temp_name ]
    
    
    if not file_exists_in_path("tlbimp.exe"):
        print "ERROR: tlbimp.exe is not in the path!"
        sys.exit(1)
    
    try:
        if not module_dll_dict.has_key(mod_name):
            print "WARNING: cannot determine which interop assemblies to install!"
            print "         This may affect peverify runs adversely."
            print
            return
            
        else:
            nt.chdir(tempDir)
    
            for com_dll in module_dll_dict[mod_name]:
                if not file_exists(com_dll):
                    print "\tERROR: %s does not exist!" % (com_dll)
                    continue
    
                print "\trunning tlbimp on", com_dll
                run_tlbimp(com_dll)
        
    finally:
        nt.chdir(cwd)   
def CurrentModelInfo():
    "Get the current document name and path"
    name = rs.DocumentName()
    path = rs.DocumentPath()
    fileexists = False
    if (path and name):
        filespec = Path.Combine(path, name)
        fileexists = File.Exists(filespec)

    if fileexists:
        __PrintFileInformation(filespec)
    else:
        print "Current model not found. Make sure the model has been saved to disk."
Beispiel #7
0
def compilePackage(packageName, codeDict):
    packagePath = path_combine(testpath.temporary_dir, packageName)
    ensure_directory_present(packagePath)
    fileList = []
    for fileName, code in codeDict.iteritems():
        filePath = path_combine(packagePath, fileName)
        ensure_directory_present(Path.GetDirectoryName(filePath))
        write_to_file(filePath, code)
        fileList.append(filePath)
    dllFile = path_combine(testpath.temporary_dir, packageName + ".dll")
    clr.CompileModules(dllFile, mainModule=fileList[0], *fileList)
    delete_files(*fileList)
    clr.AddReferenceToFileAndPath(dllFile)
def AddBatchRvtUtilAssemblyReference():
    try:
        clr.AddReference(BATCH_RVT_UTIL_ASSEMBLY_NAME)
    except IOException, e:  # Can occur if PyRevit is installed. Need to use AddReferenceToFileAndPath() in this case.
        batchRvtScriptHostAssembly = GetExistingLoadedAssembly(
            BATCH_RVT_SCRIPT_HOST_ASSEMBLY_NAME)
        clr.AddReference(batchRvtScriptHostAssembly)
        from BatchRvt.ScriptHost import ScriptHostUtil
        environmentVariables = ScriptHostUtil.GetEnvironmentVariables()
        batchRvtFolderPath = ScriptHostUtil.GetBatchRvtFolderPath(
            environmentVariables)
        clr.AddReferenceToFileAndPath(
            Path.Combine(batchRvtFolderPath, BATCH_RVT_UTIL_ASSEMBLY_NAME))
Beispiel #9
0
def getshortfiles(filelist):
    """Create list with shortended filenames

    :param filelist: List with files with complete path names
    :type filelist: list
    :return: List with filenames only
    :rtype: list
    """
    files_short = []
    for short in filelist:
        files_short.append(Path.GetFileName(short))

    return files_short
Beispiel #10
0
def getshortfiles(filelist):
    """Create a list of files using only the basenames.

    :param filelist: list with files with complete path
    :type filelist: list
    :return: list with filename (basename) only
    :rtype: list
    """
    # get the short filenames from all list entries
    files_short = []
    for short in filelist:
        files_short.append(Path.GetFileName(short))

    return files_short
Beispiel #11
0
def GetSessionFilesData(sessionId, sessionFiles):
    sessionFilesData = {
        "sessionId":
        sessionId,
        "sessionFiles": [
            (
                path_util.ExpandedFullNetworkPath(filePath)
                if Path.IsPathRooted(filePath)
                # Cloud models 'paths' are not normal file paths so this accounts for that.
                else filePath) for filePath in sessionFiles
        ]
    }

    return sessionFilesData
Beispiel #12
0
    def FileComboBox_SelectionChanged(self, sender, e):
        self.clear_plot()

        if self.FileComboBox.SelectedIndex != -1:
            comboIndex = self.FileComboBox.SelectedIndex
            file_name = self.file_names[comboIndex]
            data = parse_file(file_name)
            stem = Path.GetFileNameWithoutExtension(file_name)
            fig = self.generate_plot(
                x=data['Stage_StageReadings_StagePasteMins1'],
                y=data['Stage_StageReadings_StagePasteDive1'],
                title=stem,
            )
            self.set_plot(fig)
def run_postprocessing(image, parameters={}, func='topography'):

    if func == 'topography':

        noise_low = parameters['noise_low']
        noise_high = parameters['noise_high']
        outputfolder = parameters['outputfolder']
        ext = parameters['extension']

        # converting to topo, with defined FZ noisecut
        # in filter settings: 0-255 means no filter, 1-254 means cut one gray scale from top and from bottom
        imgtop = Zen.Processing.Transformation.Topography.CreateTopography(
            image, noise_low, noise_high)
        # saving file to the directory
        topo_filepath = Path.Combine(
            outputfolder,
            Path.GetFileNameWithoutExtension(image.FileName) + ext)
        Zen.Processing.Utilities.ExportHeightmapFromTopography(
            imgtop, topo_filepath)
        print('Exported to : ', topo_filepath)
        imgtop.Close()

    return image
Beispiel #14
0
def extract(filename_s):
    '''
   Takes the filename of a comic book, and extracts three strings out of it: the 
   series name, the issue number, and the issue year. These three pieces 
   of information are returned as a triple, i.e. ("batman", "344", "2004").
   
   This function never returns None, and it will ALWAYS return the triple with
   at least a non-empty series name (even if it is just "unknown"), but the 
   issue number and year may be "" if they couldn't be determined.
   '''
    # remove the file extension, unless it's the whole filename
    name_s = Path.GetFileName(filename_s.strip())
    if "ero" in name_s:
        log.debug(name_s)
    last_period = name_s.rfind(r".")
    name_s = name_s if last_period <= 0 else name_s[0:last_period]

    # see if the comic matches the following format, and if so, remove everything
    # after the first number:
    # "nnn series name #xx (etc) (etc)" -> "series name #xx (etc) (etc)"
    match = re.match(
        r"^\s*(\d+)[\s._-]+" +  # "nnn"
        r"([^#]+?" +  # "series name"
        r"#-?\d+.*)",
        name_s)  # "#xx (etc) (etc)"
    if match: name_s = match.group(2)

    # see if the comic matches the following format, and if so, remove everything
    # after the first number that isn't in brackets:
    # "series name #xxx - title (etc) (etc)" -> "series name #xxx (ect) (etc)
    match = re.match(
        r"^((?:[a-zA-Z,.-]+\s+)+" +  # "series name"
        r"#?(?:\d+[.0-9]*))\s*(?:-)" +  # "#xxx -"
        r".*?((\(.*)?)$",
        name_s)  # "title (etc) (etc)"
    if match:
        log.debug(name_s)
        name_s = match.group(1) + " " + match.group(2)
        log.debug("     -> ", name_s)

    # try the extraction.  if anything goes wrong, or if we come up with a blank
    # series name, revert to the filename (without extension) as series name
    try:
        retval = __extract(name_s)
        if retval[0].strip() == "":
            raise Exception("parsed blank series name")
    except:
        log.debug_exc("Recoverable error extracting from '" + name_s + "':")
        retval = name_s, "", ""
    return retval
def __PrintFileInformation(fullpath):
    "Displays a file's information."
    fi = FileInfo(fullpath)
    info = "Full Path:  " + fullpath + "\n"
    info += "File Name:  " + Path.GetFileName(fullpath) + "\n"
    info += "File Attributes:  " + __FileAttributes(fullpath) + "\n"
    info += "Date Created:  " + File.GetCreationTime(
        fullpath).ToString() + "\n"
    info += "Last Date Accessed:  " + File.GetLastAccessTime(
        fullpath).ToString() + "\n"
    info += "Last Date Modified:  " + File.GetLastWriteTime(
        fullpath).ToString() + "\n"
    info += "File Size (Bytes):  " + fi.Length.ToString() + "\n"
    rs.MessageBox(info, 0, "Current Model Information")
Beispiel #16
0
def OpenAndActivateBatchRvtTemporaryDocument(uiApplication):
    application = uiApplication.Application
    BATCHRVT_TEMPORARY_REVIT_FILE_PATH = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "BatchRvt", "TemporaryProject." + application.VersionNumber + ".rvt")
    if not path_util.FileExists(BATCHRVT_TEMPORARY_REVIT_FILE_PATH):
        path_util.CreateDirectoryForFilePath(
            BATCHRVT_TEMPORARY_REVIT_FILE_PATH)
        newDoc = CreateNewProjectFile(application,
                                      BATCHRVT_TEMPORARY_REVIT_FILE_PATH)
        newDoc.Close(False)
    uiDoc = uiApplication.OpenAndActivateDocument(
        BATCHRVT_TEMPORARY_REVIT_FILE_PATH)
    return uiDoc
Beispiel #17
0
def testFileStream():
    print 'Verifying FileStream against MemoryStream'
    stopwatch = Stopwatch.StartNew()
    for i in xrange(128):
        m = MemoryStream()
        file = Path.GetTempFileName()
        f = FileStream(file, FileMode.Open)
        try:
            streams = [m, f]
            randomOperations(128, streams)
        finally:
            f.Close()
            File.Delete(file)
    stopwatch.Stop()
    print '%s' % stopwatch.Elapsed
Beispiel #18
0
 def __init__(self):
     self.executablePath = __file__
     if self.executablePath is None:
         self.executablePath = Application.ExecutablePath
     self.executableDirectory = Path.GetDirectoryName(self.executablePath)
     self.InitializeComponent()
     self.controller = SimpleICMController(self)
     self.go_button.Click += self.controller.handle_go
     for stack in self.stacks:
         stack.GotFocus += self.controller.cache_value
         stack.LostFocus += self.controller.validate_number
     for payout in self.payouts:
         payout.GotFocus += self.controller.cache_value
         payout.LostFocus += self.controller.validate_number
     self._WebBrowser1.Navigating += self.controller.handle_navigate
Beispiel #19
0
    def run(self, Mml2vgmInfo, index):

        #設定値の読み込み
        Mml2vgmInfo.loadSetting()

        #初回のみ(設定値が無いときのみ)git.exeの場所をユーザーに問い合わせ、設定値として保存する
        gt = Mml2vgmInfo.getSettingValue("gitpath")
        if gt is None:
            gt = Mml2vgmInfo.fileSelect(
                "git.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)")
            if not Mml2vgmInfo.confirm("git.exeの場所は以下でよろしいですか\r\n" + gt):
                return None
            Mml2vgmInfo.setSettingValue("gitpath", gt)
            Mml2vgmInfo.saveSetting()

        #念のため
        if gt is None or gt == "":
            Mml2vgmInfo.msg("git.exeを指定してください")
            return None

        si = ScriptInfo()

        commitMsg = ""
        if index == 1:
            #git コミット
            commitMsg = Mml2vgmInfo.inputBox("コミット時のコメントを入力してください")
            if commitMsg == "":
                return si

        #ファイル情報の整理
        for fnf in Mml2vgmInfo.fileNamesFull:
            wp = Path.GetDirectoryName(fnf)
            Directory.SetCurrentDirectory(wp)

            if index == 0:
                #git ステージング
                args = "add " + fnf
                ret = Mml2vgmInfo.runCommand(gt, args, True)
                if ret != "":
                    Mml2vgmInfo.msg(ret)
            else:
                #git コミット
                args = "commit -m\"" + commitMsg + "\""
                ret = Mml2vgmInfo.runCommand(gt, args, True)
                if ret != "":
                    Mml2vgmInfo.msg(ret)

        return si
Beispiel #20
0
def ShowDebugInformation(input):
    if input.upper() == "DEBUG" and AWApi.IsDebugEnabled():
        ConsoleApi.WriteLine("ENVIRONMENT INFO:" + Environment.NewLine)
        ConsoleApi.WriteLine("Current Directory: " +
                             Environment.CurrentDirectory)
        ConsoleApi.WriteLine("Save Game Directory: " + Path.Combine(
            Environment.CurrentDirectory, GlobalConstants.SaveGameDirectory))
        ConsoleApi.WriteLine("Path to game file: " +
                             AWApi.Configuration.FullFilePath)
        ConsoleApi.WriteLine("Game Name: " + AWApi.Configuration.GameName)
        ConsoleApi.WriteLine("Start Room: " + AWApi.Configuration.StartRoom)
        ConsoleApi.WriteLine("Current Room: " +
                             AWApi.GetCurrentLocation().Name)
        return True

    return False
Beispiel #21
0
def check_host_drive_freespace():
    # get min free space from user config
    min_freespace = user_config.core.get_option('minhostdrivefreespace',
                                                default_value=0)

    if min_freespace:
        # find host drive and check free space
        host_drive = Path.GetPathRoot(HOST_APP.proc_path)
        for drive in DriveInfo.GetDrives():
            if drive.Name == host_drive:
                free_hd_space = float(drive.TotalFreeSpace) / (1024**3)

                if free_hd_space < min_freespace:
                    logger.warning(
                        'Remaining space on local drive '
                        'is less than {}GB...'.format(min_freespace))
Beispiel #22
0
def main():
    if len(sys.argv) != 2:
        print "Usage: ipy run_compiled.py <testfile.py>"
        sys.exit(-1)
    
    testName = sys.argv[1]
    
    print "Compiling ", testName ,"..."
    clr.CompileModules("compiledTest.dll", testName)    
    File.Move(testName, testName+".bak")    
    try:
        print "Running test from compiled binary..."    
        clr.AddReference("compiledTest")    
        __import__(Path.GetFileNameWithoutExtension(testName))    
    finally:
        File.Move(testName+".bak" , testName)
def OptimizeAllIFCFilesinFolder(directoryPath):
    returnvalue = res.Result()
    # check if ifc optimizer is installed:
    if(cp.FileExist(solibriInstallPath_)):
        returnvalue.message = 'Solibri IFC optimizer is installed.'
        ifcFiles = cp.GetFiles(directoryPath, '.ifc')
        filesToDelete = []
        filesToRename = []
        if(len(ifcFiles) > 0):
            returnvalue.AppendMessage('found ifc files: ' + str(len(ifcFiles)))
            for ifcFile in ifcFiles:
                s = subprocess.check_call([r'C:\Program Files\Solibri\IFCOptimizer\Solibri IFC Optimizer.exe', '-in=' + ifcFile, '-out=' + directoryPath, '-ifc', '-force'])
                # check what came back
                if (s == 0):
                    #all went ok:
                    returnvalue.AppendMessage('Optimized file: '+str(ifcFile))
                    filesToDelete.append(ifcFile) # full file path
                    # get the rename information
                    # contains old and new file name
                    rename = []
                    p = cp.GetFolderPathFromFile(ifcFile)
                    if(p != ''):
                        newFilePath = str(p)+'\\'+ str(Path.GetFileNameWithoutExtension(ifcFile))+'_optimized.ifc'
                        rename.append(newFilePath)
                        rename.append(ifcFile)
                        filesToRename.append(rename)
                else:
                    # something went wrong
                    returnvalue.UpdateSep(False, 'Failed to optimize file: '+ str(ifcFile))
            # clean up
            for fileToDelete in filesToDelete:
                statusDelete = cp.FileDelete(fileToDelete)
                if(statusDelete):
                    returnvalue.AppendMessage('Deleted original file: ' + str(fileToDelete))
                else:
                    returnvalue.UpdateSep(False,'Failed to delete original file: '+ str(fileToDelete))
            for fileToRename in filesToRename:
                statusRename = cp.RenameFile(fileToRename[0], fileToRename[1])
                if(statusRename):
                    returnvalue.AppendMessage('Renamed original file: ' + str(fileToRename[0]) + ' to: ' + str(fileToRename[1]))
                else:
                    returnvalue.UpdateSep(False,'Failed to rename original file: '+ str(fileToRename[0]))
        else:
            returnvalue.AppendMessage('No IFC files found in directory: '+ str(directoryPath))
    else:
        returnvalue.UpdateSep(False, 'No IFC optimizer installed at: '+ str(solibriInstallPath_))
    return returnvalue
Beispiel #24
0
def _runscript():

    try:
        # loading config
        iniFile = Path.ChangeExtension(sys.argv[0],".ini")
        configLines = File.ReadAllLines(iniFile)
        config = {}
        for line in configLines:
            kv = line.split("=")
            config[kv[0].upper()] = kv[1]

            print "construct"
            app = Application()
            print "set connection"
            app.SetConnection("Host=" + config["HOST"]+";Database="+config["DATABASE"]+";port="+config["PORT"]+";dbflavour="+ config["DBFLAVOUR"]);
            print "login"
            app.Login(config["USER"],config["PW"],config["WORKSPACE"]);
            print "startup"
            app.StartUp();
            print "ready"

            scriptPath = sys.argv[1]
            print "scriptPath=" + scriptPath

            scr = app.Modules.Get("Script Manager")
            script = scr.ScriptList.Fetch(scriptPath)
            print "Setting up parameters ... "
            dictParam = Dictionary[String, Object]()
            for i in range(2,len(sys.argv)):
                kv = sys.argv[i].split('=')
                k = kv[0].strip()
                v = kv[1].strip()
                if v.startswith('"') and v.endswith('"'): v = v[1:-1]
                print k,"=",v
                dictParam.Add(k,v)
                print "Running " + scr.ScriptList.GetEntityDescriptor(script)
                output =  clr.Reference[String]()
                # avoid conflicting overloaded versions of ExecuteScript by supplying arguments by name
                result = scr.ExecuteScript(script=script, arguments=dictParam, tag=None, output=output)
                print "result=",result
                print "output:"
                print output.Value

                print "done"
    except Exception as e:
        print "ERROR"
        print str(e)
Beispiel #25
0
    def __init__(self):

        self.settingsJsonPath = Path.GetFullPath('settings.json').replace(
            '\\', '/')

        self.InitializeComponent()

        self.config = {
            'Root': ['C:'],
            'Ignore': [],
            'IgnoreHidden': True,
            'MaxFile': 20,
            'MaxFolder': 30,
            'Window': {
                'Left': 100,
                'Top': 100,
                'Width': 800,
                'Height': 600
            },
            'Cmd': 'C:/Windows/System32/cmd.exe'
        }

        try:
            self.config.update(LoadJson(self.settingsJsonPath))
        except:
            log_except(sys.exc_info())

            if File.Exists(self.settingsJsonPath):
                File.Copy(self.settingsJsonPath,
                          self.settingsJsonPath + '.bak', True)
                MessageBox.Show(
                    self.settingsJsonPath + ' の読み込みに失敗したため\n' +
                    self.settingsJsonPath + '.bak としてバックアップを取り、新規作成しました。',
                    'Error', MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

        rootList = self.config['Root']
        self.config['Root'] = ArrayList()
        self.config['Ignore'] = ArrayList(self.config['Ignore'])

        for i in rootList:
            self.AddRoot(i)

        for i in range(len(self.config['Ignore'])):
            self.config['Ignore'][i] = CorrectPath(self.config['Ignore'][i])

        SaveJson(self.settingsJsonPath, self.config)
def set_image_based_on_limit(green_limit,
                             yellow_limit,
                             file_name_list,
                             Matrix=None):
    r"""Select which image to display based upon limits, for example a traffic 
    light system or up and down arrows.
    
    This should be run per text shape to set the background image and size 
    based on the image selected. 
    
    Example:
    
    | file_name_list = list()
    | file_name_list.append("traffic-light-green.jpg")
    | file_name_list.append("traffic-light-yellow.jpg")
    | file_name_list.append("traffic-light-red.jpg")
    | 
    | texts.set_image_based_on_limit(0.3, 0.2, file_name_list, Matrix)
    
    """

    if Matrix is None:
        from globals import Matrix

    _green_image = file_name_list[0]
    _yellow_image = file_name_list[1]
    _red_image = file_name_list[2]

    _value = Matrix[0][0][0].GetNumericValue()
    _image_to_use = _red_image
    if (_value >= green_limit):
        _image_to_use = _green_image
    elif (_value >= yellow_limit):
        _image_to_use = _yellow_image
    try:
        set_bg_image_and_size(_image_to_use)
    except:
        # cannot find image, try standard utils\images location
        try:
            from System.IO import Path
            _my_dir = Path.GetDirectoryName(
                __file__)  #relative to the module file
            _image_path = _my_dir + "\\transformations\\utils\\images\\"
            set_bg_image_and_size(_image_path + _image_to_use)
        except:
            raise
Beispiel #27
0
def _check_magic_file(path_s):
    ''' ComicVine implementation of the identically named method in the db.py '''
    series_key_s = None
    file_s = None
    try:
        # 1. get the directory to search for a cvinfo file in, or None
        dir_s = path_s if path_s and Directory.Exists(path_s) else \
           Path.GetDirectoryName(path_s) if path_s else None
        dir_s = dir_s if dir_s and Directory.Exists(dir_s) else None

        if dir_s:
            # 2. search in that directory for a properly named cvinfo file
            #    note that Windows filenames are not case sensitive.
            for f in [dir_s + "\\" + x for x in ["cvinfo.txt", "cvinfo"]]:
                if File.Exists(f):
                    file_s = f

            # 3. if we found a file, read it's contents in, and parse the
            #    comicvine series id out of it, if possible.
            if file_s:
                with StreamReader(file_s, Encoding.UTF8, False) as sr:
                    line = sr.ReadToEnd()
                    line = line.strip() if line else line
                    match = re.match(r"^.*?\b(49|4050)-(\d{2,})\b.*$", line)
                    line = match.group(2) if match else line
                    if utils.is_number(line):
                        series_key_s = utils.sstr(int(line))
    except:
        log.debug_exc("bad cvinfo file: " + sstr(file_s))

    # 4. did we find a series key?  if so, query comicvine to build a proper
    #    SeriesRef object for that series key.
    series_ref = None
    if series_key_s:
        try:
            dom = cvconnection._query_series_details_dom(
                __api_key, utils.sstr(series_key_s))
            num_results_n = int(dom.number_of_total_results)
            series_ref =\
               __volume_to_seriesref(dom.results) if num_results_n==1 else None
        except:
            log.debug_exc("error getting SeriesRef for: " + sstr(series_key_s))

    if file_s and not series_ref:
        log.debug("ignoring bad cvinfo file: ", sstr(file_s))
    return series_ref  # may be None!
Beispiel #28
0
def loadMasterPluginIndex():
    """ Loads the Master Plugin Index List into a map
	"""
    import System
    from System.IO import Path
    from System import Environment
    file = Path.Combine(
        Environment.GetFolderPath(
            Environment.SpecialFolder.LocalApplicationData), 'Skyrim',
        'plugins.txt')
    with open(file, "rt") as f:
        first = f.readline().strip().lower()
        offset = first != 'skyrim.esm' and 1 or 0
        masterIdx = dict([(r.strip().lower(), i + offset)
                          for i, r in enumerate(f.readlines())])
        masterIdx[first] = offset
        if offset: masterIdx['skyrim.esm'] = 0
    return masterIdx
def createfolder(basedir, formatstring='%Y-%m-%d_%H-%M-%S'):
    # construct new directoty name nased on date and time
    newdir = Path.Combine(basedir, datetime.now().strftime(formatstring))
    # check if the new directory (for whatever reasons) already exists
    try:
        newdir_exists = Directory.Exists(newdir)
        if not newdir_exists:
            # create new directory if is does not exist
            Directory.CreateDirectory(newdir)
        if newdir_exists:
            # raise error if it really already exists
            raise SystemExit
    except OSError as e:
        if e.errno != errno.EEXIST:
            newdir = None
            raise  # This was not a "directory exist" error..

    return newdir
Beispiel #30
0
    def __start_scrape(self, book, num_remaining):
        '''
      This method gets called once for each comic that the ScrapeEngine is 
      scraping; the call happens just before the scrape begins.  The method 
      updates all necessary graphical components to reflect the current scrape.
      
      'book' -> the comic book object that is about to be scraped
      'num_remaining' -> the # of books left to scrape (including current one) 
      '''

        # 1. obtain a nice filename string to put into out Label
        book_name = Path.GetFileName(
            book.path_s.strip())  # path_s is never None
        fileless = book_name == ""
        if fileless:
            # 1a. this is a fileless book, so build up a nice, detailed name
            book_name = book.series_s
            if not book_name:
                book_name = "<" + i18n.get("ComicFormUnknown") + ">"
            book_name += (' #' + book.issue_num_s) if book.issue_num_s else ''
            book_name += (' ({0} {1})'.format(
               i18n.get("ComicFormVolume"), sstr(book.volume_year_n) ) ) \
               if book.volume_year_n >= 0 else (' ('+sstr(book.pub_year_n) +')') \
               if book.pub_year_n >= 0 else ''

        # 2. obtain a copy of the first (cover) page of the book to install
        page_image = book.create_image_of_page(0)
        page_count = book.page_count_n

        # 3. install those values into the ComicForm.  update progressbar.
        def delegate():
            # NOTE: now we're on the ComicForm Application Thread
            self.__current_book = book
            self.__current_page = 0
            self.__current_page_count = page_count
            self.__label.Text = i18n.get("ComicFormScrapingLabel") + book_name
            self.__pbox_panel.set_image(page_image)  # cover image may be None
            self.__progbar.PerformStep()
            self.__progbar.Maximum = self.__progbar.Value + num_remaining
            self.__cancel_button.Text=\
               i18n.get("ComicFormCancelButton").format(sstr(num_remaining))
            self.Update()

        utils.invoke(self, delegate, False)