Ejemplo n.º 1
0
    def add_dir(self, node, path, with_file):
        if path[-1] != '/':
            path = path + '/'
        if Directory.Exists(path):
            try:
                dir_cnt = 0
                for dir_path in Directory.GetDirectories(path):
                    if not self.is_ignore_item(dir_path):
                        dir_cnt += 1
                        if dir_cnt >= self.config['MaxFolder']:
                            if node.Nodes['*MaxFolder*'] == None:
                                d_node = TreeNode('. . .', 1, 1)
                                d_node.Name = '*MaxFolder*'
                                node.Nodes.Add(d_node)
                            break

                        s = Path.GetFileName(dir_path)
                        d_node = node.Nodes[s]

                        if d_node == None:
                            d_node = TreeNode(s)
                            d_node.Name = s
                            node.Nodes.Add(d_node)

                file_cnt = 0
                for file_path in Directory.GetFiles(path):
                    if not self.is_ignore_item(file_path):
                        file_cnt += 1
                        if file_cnt >= self.config['MaxFile']:
                            if node.Nodes['*MaxFile*'] == None:
                                f_node = TreeNode('. . .', 1, 1)
                                f_node.Name = '*MaxFile*'
                                node.Nodes.Add(f_node)
                            break

                        s = Path.GetFileName(file_path)
                        f_node = node.Nodes[s]
                        if f_node == None:
                            f_node = TreeNode(s)

                            img_key = file_path.replace('/', '')
                            try:
                                icon = System.Drawing.Icon.ExtractAssociatedIcon(
                                    '' + file_path)
                                self._imageList1.Images.Add(img_key, icon)
                                f_node.ImageKey = f_node.SelectedImageKey = img_key
                            except:
                                f_node.ImageIndex = f_node.SelectedImageIndex = 2
                            f_node.Name = s
                            node.Nodes.Add(f_node)

            except:
                log_except(sys.exc_info())
        else:
            node.BackColor = Color.Gray
Ejemplo n.º 2
0
def getshortfiles(filelist):
    # get the short filesnames from all list entries
    files_short = []
    for short in filelist:
        files_short.append(Path.GetFileName(short))

    return files_short
def CopyNWCFiles():
    status = True
    fileFilter = '*.nwc'
    # check whether any files match the filter
    for nwcFileNameStart, nwcTargetFolder in defaultNWCLocations_:
        files = cp.GetFilesWithFilter(sourcePath_, fileFilter,
                                      nwcFileNameStart + '*')
        if (files != None and len(files) > 0):
            Output('Copying nwc Files...' + str(len(files)))
            for file in files:
                try:
                    # extract file name only
                    fileName = Path.GetFileName(file)
                    src = sourcePath_ + '\\' + fileName
                    destinationFileName = GetNWCFileName(fileName)
                    dst = nwcTargetFolder + '\\' + destinationFileName
                    shutil.copy(src, dst)
                    status = status & True
                    Output('Copied file from ' + src + ' to ' + dst)
                except Exception:
                    Output('Failed to copy file from ' + src + ' to ' + dst)
                    status = False
        else:
            Output('No nwc files matching filter ' + fileFilter +
                   ' in source location: ' + sourcePath_)
    return status
Ejemplo n.º 4
0
def create_breakpoint(module, filename, linenum):
    reader = module.SymbolReader
    if reader == None:
        return None

    # currently, I'm only comparing filenames. This algorithm may need to get more
    # sophisticated to support differntiating files with the same name in different paths
    filename = Path.GetFileName(filename)
    for doc in reader.GetDocuments():
        if str.Compare(filename, Path.GetFileName(doc.URL), True) == 0:
            linenum = doc.FindClosestLine(linenum)
            method = reader.GetMethodFromDocumentPosition(doc, linenum, 0)
            function = module.GetFunctionFromToken(method.Token.GetToken())

            for sp in get_sequence_points(method):
                if sp.doc.URL == doc.URL and sp.start_line == linenum:
                    return function.ILCode.CreateBreakpoint(sp.offset)

            return function.CreateBreakpoint()
Ejemplo n.º 5
0
def getPageNameList(book):
    pageNameList = []
    imgProvider = book.OpenProvider(book.Pages.Count)

    for page in book.Pages:
        imgInfo = imgProvider.GetImageInfo(page.ImageIndex)
        filename = Path.GetFileName(imgInfo.Name)
        pageNameList.append(filename)

    return pageNameList
Ejemplo n.º 6
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
Ejemplo n.º 7
0
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")
Ejemplo n.º 8
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
Ejemplo n.º 9
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
Ejemplo n.º 10
0
    def pre_render_tasks(self):
        """Load config file and do remapping."""
        self.LogInfo("OpenPype Tile Assembler starting...")
        scene_filename = self.GetDataFilename()

        temp_scene_directory = self.CreateTempDirectory(
            "thread" + str(self.GetThreadNumber()))
        temp_scene_filename = Path.GetFileName(scene_filename)
        self.config_file = Path.Combine(temp_scene_directory,
                                        temp_scene_filename)

        if SystemUtils.IsRunningOnWindows():
            RepositoryUtils.CheckPathMappingInFileAndReplaceSeparator(
                scene_filename, self.config_file, "/", "\\")
        else:
            RepositoryUtils.CheckPathMappingInFileAndReplaceSeparator(
                scene_filename, self.config_file, "\\", "/")
            os.chmod(self.config_file, os.stat(self.config_file).st_mode)
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
 def __drawFolderThumbnail(self, parent):
     size = ThumbnailSize
     # create new image
     newImage = Bitmap(size, size)
     g = Graphics.FromImage(newImage)
     g.InterpolationMode = InterpolationMode.HighQualityBicubic
     # draw background
     if parent: bc = ParentFolderColor
     else: bc = ChildFolderColor
     b = LinearGradientBrush(Point(0, 0), Point(size, size), bc,
                             Color.GhostWhite)
     g.FillRectangle(b, 0, 0, size, size)
     b.Dispose()
     g.DrawRectangle(Pens.LightGray, 0, 0, size - 1, size - 1)
     # draw up to 4 subitems
     folderItems = self.GetFirstFolderItems(4)
     delta = 10
     side = (size - 3 * delta) / 2 - 1
     rects = (Rectangle(delta + 3, delta + 12, side, side),
              Rectangle(size / 2 + delta / 2 - 3, delta + 12, side, side),
              Rectangle(delta + 3, size / 2 + delta / 2 + 6, side, side),
              Rectangle(size / 2 + delta / 2 - 3, size / 2 + delta / 2 + 6,
                        side, side))
     for rect, item in zip(rects, folderItems):
         subImage = Bitmap.FromStream(MemoryStream(item.thumbnail()), False)
         g.DrawImage(subImage, rect)
         subImage.Dispose()
     for rect in rects:
         g.DrawRectangle(Pens.LightGray, rect)
     # draw folder name
     if parent: name = '[..]'
     else: name = Path.GetFileName(self.path)
     f = Font('Arial', 10)
     g.DrawString(name, f, Brushes.Black,
                  RectangleF(2, 2, size - 2, size - 2))
     f.Dispose()
     # get the bytes of the image
     imageBytes = BitmapToBytes(newImage)
     # cleanup
     g.Dispose()
     newImage.Dispose()
     return imageBytes
Ejemplo n.º 13
0
def GetFileToServer():
    try:
        uploader = tool.gtCtl('fileUploadCtrl')

        if uploader.HasFile:
            tool.logMsg('size of file : ' +
                        str(uploader.PostedFile.ContentLength))

            destDir = Server.MapPath('./data')
            fileName = Path.GetFileName(uploader.PostedFile.FileName)
            destination = Path.Combine(destDir, fileName)

            tool.logMsg('place of file  : ' + str(destination))

            uploader.SaveAs(destination)

            ImportPlaces(destination)

    except Exception, e:
        tool.log.w2lgError(traceback.format_exc())
def MoveFiles(fileData):
    status = True
    # get the date stamp
    folderName = cp.GetFolderDateStamp() + str('_Models')
    for fileFilter, targetLocation in fileData:
        # check if target root path still exists
        if (path.exists(targetLocation)):
            # check whether any files match the filter
            files = cp.GetFilesWithFilter(sourcePath_, '.*', fileFilter + '*')
            # copy any *.nwc files into the right folders first
            CopyNWCFiles()
            # move files into file in location
            if (files != None and len(files) > 0):
                flagGotFolder, folderName = CreateTargetFolder(
                    targetLocation, folderName)
                if (flagGotFolder):
                    Output('Moving Files...' + str(len(files)))
                    # move files
                    for file in files:
                        try:
                            # extract file name only
                            fileName = Path.GetFileName(file)
                            src = sourcePath_ + '\\' + fileName
                            dst = targetLocation + '\\' + folderName + '\\' + fileName
                            shutil.move(src, dst)
                            status = status & True
                            Output('Moved file from ' + src + ' to ' + dst)
                        except Exception:
                            Output('Failed to move file from ' + src + ' to ' +
                                   dst)
                            status = False
                else:
                    Output('Failed to create target folder ' + targetLocation)
            else:
                Output('No files matching filter ' + fileFilter +
                       ' in source location: ' + sourcePath_)
        else:
            Output(targetLocation + ' no longer exists!')
            status = False
    return status
Ejemplo n.º 15
0
    def __parse_extra_details_from_path(self):
        ''' 
      Series name, issue number, and volume year are all critical bits of data 
      for scraping purposes--yet fresh, unscraped files often do not have them.
      So when some or all of these values are missing, this method tries to fill
      them in by parsing them out of the comic's path.
      '''

        bd = self.__bookdata
        no_series = BookData.blank("series_s") == bd.series_s
        no_issuenum = BookData.blank("issue_num_s") == bd.issue_num_s
        no_year = BookData.blank("pub_year_n") == bd.pub_year_n
        if no_series or no_issuenum or no_year:
            if bd.path_s:
                # 1. at least one detail is missing, and we have a path name to
                #    work with, so lets try to extract some details that way.
                filename = Path.GetFileName(bd.path_s)
                config = self.__scraper.config
                regex = config.alt_search_regex_s
                extracted = None

                # 2. first, extract using the user specified regex, if there is one
                if regex:
                    extracted = fnameparser.regex(filename, regex)
                if not extracted:
                    extracted = fnameparser.extract(filename)  # never fails

                # 3. now that we have some extracted data, use it to fill in
                #    any gaps in our details.
                if no_series:
                    bd.series_s = extracted[0]
                if no_issuenum:
                    bd.issue_num_s = extracted[1]
                if no_year:
                    bd.pub_year_n = int(extracted[2]) \
                       if is_number(extracted[2])\
                          else BookData.blank("pub_year_n")
def SubmitButtonPressed(*args):
    global scriptDialog
    global integration_dialog

    try:
        submitScene = scriptDialog.GetValue("SubmitSceneBox")

        # Check if Integration options are valid
        if not integration_dialog.CheckIntegrationSanity():
            return

        warnings = []
        errors = []

        # Check if max files exist.
        sceneFiles = StringUtils.FromSemicolonSeparatedString(
            scriptDialog.GetValue("SceneBox"), False)
        if not sceneFiles:
            errors.append("No 3dsmax file specified")

        for sceneFile in sceneFiles:
            if not File.Exists(sceneFile):
                errors.append("3dsmax file %s does not exist" % sceneFile)
                return
            elif not submitScene and PathUtils.IsPathLocal(sceneFile):
                warnings.append(
                    "The scene file " + sceneFile +
                    " is local and is not being submitted with the job, are you sure you want to continue?"
                )

        # Check if path config file exists.
        pathConfigFile = scriptDialog.GetValue("PathConfigBox").strip()
        if pathConfigFile:
            if not File.Exists(pathConfigFile):
                errors.append("Path configuration file %s does not exist" %
                              pathConfigFile)

        # Check if PreLoad script file exists.
        preLoadFile = scriptDialog.GetValue("PreLoadBox").strip()
        if preLoadFile:
            if not File.Exists(preLoadFile):
                errors.append("PreLoad MAXScript file %s does not exist" %
                              preLoadFile)

        # Check if PostLoad script file exists.
        postLoadFile = scriptDialog.GetValue("PostLoadBox").strip()
        if postLoadFile:
            if not File.Exists(postLoadFile):
                errors.append("PostLoad MAXScript file %s does not exist" %
                              postLoadFile)

        # Check if PreFrame script file exists.
        preFrameFile = scriptDialog.GetValue("PreFrameBox").strip()
        if preFrameFile:
            if not File.Exists(preFrameFile):
                errors.append("PreFrame MAXScript file %s does not exist" %
                              preFrameFile)

        # Check if PostFrame script file exists.
        postFrameFile = scriptDialog.GetValue("PostFrameBox").strip()
        if postFrameFile:
            if not File.Exists(postFrameFile):
                errors.append("PostFrame MAXScript file %s does not exist" %
                              postFrameFile)

        # Check if a valid frame range has been specified.
        frames = scriptDialog.GetValue("FramesBox")
        if scriptDialog.GetValue("DBRModeBox") != "Disabled":
            frameArray = FrameUtils.Parse(frames)
            if len(frameArray) != 1:
                errors.append(
                    "Please specify a single frame for distributed rendering in the Frame List."
                )
            elif not FrameUtils.FrameRangeValid(frames):
                errors.append(
                    "Please specify a valid single frame for distributed rendering in the Frame List."
                )

            frames = "0-" + str(scriptDialog.GetValue("DBRServersBox") - 1)
        else:
            if not FrameUtils.FrameRangeValid(frames):
                errors.append("Frame range %s is not valid" % frames)

        # If using 'select GPU device Ids' then check device Id syntax is valid
        if scriptDialog.GetValue(
                "GPUsPerTaskBox") == 0 and scriptDialog.GetValue(
                    "GPUsSelectDevicesBox"):
            regex = re.compile("^(\d{1,2}(,\d{1,2})*)?$")
            validSyntax = regex.match(
                scriptDialog.GetValue("GPUsSelectDevicesBox"))
            if not validSyntax:
                errors.append(
                    "'Select GPU Devices' syntax is invalid!\nTrailing 'commas' if present, should be removed.\nValid Examples: 0 or 2 or 0,1,2 or 0,3,4 etc"
                )

            # Check if concurrent threads > 1
            if scriptDialog.GetValue("ConcurrentTasksBox") > 1:
                errors.append(
                    "If using 'Select GPU Devices', then 'Concurrent Tasks' must be set to 1"
                )

        if errors:
            scriptDialog.ShowMessageBox(
                "The following errors were encountered:\n\n%s\n\nPlease resolve these issues and submit again.\n"
                % ("\n\n".join(errors)), "Errors")
            return

        if warnings:
            result = scriptDialog.ShowMessageBox(
                "Warnings:\n\n%s\n\nDo you still want to continue?" %
                ("\n\n".join(warnings)), "Warnings", ("Yes", "No"))
            if result == "No":
                return

        successes = 0
        failures = 0

        # Submit each scene file separately.
        for sceneFile in sceneFiles:
            jobName = scriptDialog.GetValue("NameBox")
            if len(sceneFiles) > 1:
                jobName = jobName + " [" + Path.GetFileName(sceneFile) + "]"

            # Create job info file.
            jobInfoFilename = Path.Combine(ClientUtils.GetDeadlineTempPath(),
                                           "max_job_info.job")
            writer = StreamWriter(jobInfoFilename, False, Encoding.Unicode)
            writer.WriteLine("Plugin=3dsmax")
            writer.WriteLine("Name=%s" % jobName)
            writer.WriteLine("Comment=%s" %
                             scriptDialog.GetValue("CommentBox"))
            writer.WriteLine("Department=%s" %
                             scriptDialog.GetValue("DepartmentBox"))
            writer.WriteLine("Pool=%s" % scriptDialog.GetValue("PoolBox"))
            writer.WriteLine("SecondaryPool=%s" %
                             scriptDialog.GetValue("SecondaryPoolBox"))
            writer.WriteLine("Group=%s" % scriptDialog.GetValue("GroupBox"))
            writer.WriteLine("Priority=%s" %
                             scriptDialog.GetValue("PriorityBox"))
            writer.WriteLine("TaskTimeoutMinutes=%s" %
                             scriptDialog.GetValue("TaskTimeoutBox"))
            writer.WriteLine("EnableAutoTimeout=%s" %
                             scriptDialog.GetValue("AutoTimeoutBox"))
            writer.WriteLine("ConcurrentTasks=%s" %
                             scriptDialog.GetValue("ConcurrentTasksBox"))
            writer.WriteLine("LimitConcurrentTasksToNumberOfCpus=%s" %
                             scriptDialog.GetValue("LimitConcurrentTasksBox"))

            writer.WriteLine("MachineLimit=%s" %
                             scriptDialog.GetValue("MachineLimitBox"))
            if scriptDialog.GetValue("IsBlacklistBox"):
                writer.WriteLine("Blacklist=%s" %
                                 scriptDialog.GetValue("MachineListBox"))
            else:
                writer.WriteLine("Whitelist=%s" %
                                 scriptDialog.GetValue("MachineListBox"))

            writer.WriteLine("LimitGroups=%s" %
                             scriptDialog.GetValue("LimitGroupBox"))
            writer.WriteLine("JobDependencies=%s" %
                             scriptDialog.GetValue("DependencyBox"))
            writer.WriteLine("OnJobComplete=%s" %
                             scriptDialog.GetValue("OnJobCompleteBox"))

            if scriptDialog.GetValue("SubmitSuspendedBox"):
                writer.WriteLine("InitialStatus=Suspended")

            writer.WriteLine("Frames=%s" % frames)
            if scriptDialog.GetValue("DBRModeBox") == "Disabled":
                writer.WriteLine("ChunkSize=%s" %
                                 scriptDialog.GetValue("ChunkSizeBox"))

            # Integration
            extraKVPIndex = 0
            groupBatch = False

            if integration_dialog.IntegrationProcessingRequested():
                extraKVPIndex = integration_dialog.WriteIntegrationInfo(
                    writer, extraKVPIndex)
                groupBatch = groupBatch or integration_dialog.IntegrationGroupBatchRequested(
                )

            if groupBatch:
                writer.WriteLine("BatchName=%s\n" % jobName)

            writer.Close()

            # Create plugin info file.
            pluginInfoFilename = Path.Combine(
                ClientUtils.GetDeadlineTempPath(), "max_plugin_info.job")
            writer = StreamWriter(pluginInfoFilename, False, Encoding.Unicode)

            writer.WriteLine("Version=%s" %
                             scriptDialog.GetValue("VersionBox"))
            writer.WriteLine("IsMaxDesign=%s" %
                             scriptDialog.GetValue("IsMaxDesignBox"))

            if int(scriptDialog.GetValue("VersionBox")) < 2014:
                writer.WriteLine("MaxVersionToForce=%s" %
                                 scriptDialog.GetValue("BuildBox"))
                writer.WriteLine("MaxVersionToForce0=None")
                writer.WriteLine("MaxVersionToForce1=32bit")
                writer.WriteLine("MaxVersionToForce2=64bit")

            writer.WriteLine("UseSlaveMode=%d" %
                             (not scriptDialog.GetValue("WorkstationModeBox")))
            if scriptDialog.GetValue("WorkstationModeBox"):
                writer.WriteLine("UseSilentMode=%s" %
                                 (scriptDialog.GetValue("SilentModeBox")))
            else:
                writer.WriteLine("UseSilentMode=False")

            writer.WriteLine("ShowFrameBuffer=%s" %
                             scriptDialog.GetValue("ShowVfbBox"))
            writer.WriteLine("RemovePadding=%s" %
                             scriptDialog.GetValue("RemovePaddingBox"))
            writer.WriteLine("RestartRendererMode=%s" %
                             scriptDialog.GetValue("RestartRendererBox"))
            writer.WriteLine(
                "IgnoreMissingExternalFiles=%s" %
                scriptDialog.GetValue("IgnoreMissingExternalFilesBox"))
            writer.WriteLine("IgnoreMissingUVWs=%s" %
                             scriptDialog.GetValue("IgnoreMissingUVWsBox"))
            writer.WriteLine("IgnoreMissingXREFs=%s" %
                             scriptDialog.GetValue("IgnoreMissingXREFsBox"))
            writer.WriteLine("IgnoreMissingDLLs=%s" %
                             scriptDialog.GetValue("IgnoreMissingDLLsBox"))
            writer.WriteLine("LocalRendering=%s" %
                             scriptDialog.GetValue("LocalRenderingBox"))
            writer.WriteLine("DisableMultipass=%s" %
                             scriptDialog.GetValue("DisableMultipassBox"))
            writer.WriteLine("OneCpuPerTask=%s" %
                             scriptDialog.GetValue("OneCpuPerTaskBox"))

            if pathConfigFile:
                writer.WriteLine("PathConfigFile=%s" %
                                 Path.GetFileName(pathConfigFile))
                writer.WriteLine("MergePathConfigFile=%s" %
                                 scriptDialog.GetValue("MergePathConfigBox"))

            if preLoadFile:
                writer.WriteLine("PreLoadScript=%s" %
                                 Path.GetFileName(preLoadFile))

            if postLoadFile:
                writer.WriteLine("PostLoadScript=%s" %
                                 Path.GetFileName(postLoadFile))

            if preFrameFile:
                writer.WriteLine("PreFrameScript=%s" %
                                 Path.GetFileName(preFrameFile))

            if postFrameFile:
                writer.WriteLine("PostFrameScript=%s" %
                                 Path.GetFileName(postFrameFile))

            pluginIniOverride = scriptDialog.GetValue("PluginIniBox").strip()
            if pluginIniOverride:
                writer.WriteLine("OverridePluginIni=%s" % pluginIniOverride)

            writer.WriteLine("GammaCorrection=%s" %
                             scriptDialog.GetValue("GammaCorrectionBox"))
            writer.WriteLine("GammaInput=%s" %
                             scriptDialog.GetValue("GammaInputBox"))
            writer.WriteLine("GammaOutput=%s" %
                             scriptDialog.GetValue("GammaOutputBox"))

            if int(scriptDialog.GetValue("VersionBox")) >= 2013:
                if scriptDialog.GetValue("OverrideLanguageBox"):
                    writer.WriteLine("Language=%s" %
                                     scriptDialog.GetValue("LanguageBox"))
                else:
                    writer.WriteLine("Language=Default")

            camera = scriptDialog.GetValue("CameraBox")
            if camera:
                writer.WriteLine("Camera=%s" % camera)
                writer.WriteLine("Camera0=")
                writer.WriteLine("Camera1=%s" % camera)

            if not submitScene:
                writer.WriteLine("SceneFile=%s" % sceneFile)

            if scriptDialog.GetValue("DBRModeBox") != "Disabled":
                if scriptDialog.GetValue("DBRModeBox") == "VRay DBR":
                    writer.WriteLine("VRayDBRJob=True")
                elif scriptDialog.GetValue(
                        "DBRModeBox") == "Mental Ray Satellite":
                    writer.WriteLine("MentalRayDBRJob=True")
                elif scriptDialog.GetValue("DBRModeBox") == "VRay RT DBR":
                    writer.WriteLine("VRayRtDBRJob=True")
                writer.WriteLine("DBRJobFrame=%s" %
                                 scriptDialog.GetValue("FramesBox"))

            if scriptDialog.GetValue("DBRModeBox") == "Disabled":
                writer.WriteLine("GPUsPerTask=%s" %
                                 scriptDialog.GetValue("GPUsPerTaskBox"))
                writer.WriteLine("GPUsSelectDevices=%s" %
                                 scriptDialog.GetValue("GPUsSelectDevicesBox"))

            writer.Close()

            # Setup the command line arguments.
            arguments = [jobInfoFilename, pluginInfoFilename]
            if scriptDialog.GetValue("SubmitSceneBox"):
                arguments.append(sceneFile)

            if pathConfigFile:
                arguments.append(pathConfigFile)
            if preLoadFile:
                arguments.append(preLoadFile)
            if postLoadFile:
                arguments.append(postLoadFile)
            if preFrameFile:
                arguments.append(preFrameFile)
            if postFrameFile:
                arguments.append(postFrameFile)

            if len(sceneFiles) == 1:
                results = ClientUtils.ExecuteCommandAndGetOutput(arguments)
                scriptDialog.ShowMessageBox(results, "Submission Results")
            else:
                # Now submit the job.
                exitCode = ClientUtils.ExecuteCommand(arguments)
                if exitCode == 0:
                    successes += 1
                else:
                    failures += 1

        if len(sceneFiles) > 1:
            scriptDialog.ShowMessageBox(
                "Jobs submitted successfully: %d\nJobs not submitted: %d" %
                (successes, failures), "Submission Results")
    except:
        scriptDialog.ShowMessageBox(traceback.format_exc(), "")
Ejemplo n.º 17
0
    def onSignInClick(source, rea):
        config = None
        directory = Path.Combine(
            Environment.GetFolderPath(
                Environment.SpecialFolder.ApplicationData),
            Assembly.GetEntryAssembly().GetName().Name)
        backgroundBrush = None
        textColor = SystemColors.ControlTextBrush

        if Directory.Exists(directory):
            fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location)

            for fileName2 in Directory.EnumerateFiles(directory, "*.config"):
                if fileName1.Equals(
                        Path.GetFileNameWithoutExtension(fileName2)):
                    exeConfigurationFileMap = ExeConfigurationFileMap()
                    exeConfigurationFileMap.ExeConfigFilename = fileName2
                    config = ConfigurationManager.OpenMappedExeConfiguration(
                        exeConfigurationFileMap, ConfigurationUserLevel.None)

        if config is None:
            config = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None)
            directory = None

        if config.AppSettings.Settings["BackgroundImage"] is not None:
            fileName = config.AppSettings.Settings[
                "BackgroundImage"].Value if directory is None else Path.Combine(
                    directory,
                    config.AppSettings.Settings["BackgroundImage"].Value)
            fs = None
            bi = BitmapImage()

            try:
                fs = FileStream(fileName, FileMode.Open, FileAccess.Read,
                                FileShare.Read)

                bi.BeginInit()
                bi.StreamSource = fs
                bi.CacheOption = BitmapCacheOption.OnLoad
                bi.CreateOptions = BitmapCreateOptions.None
                bi.EndInit()

            finally:
                if fs is not None:
                    fs.Close()

            backgroundBrush = ImageBrush(bi)
            backgroundBrush.TileMode = TileMode.Tile
            backgroundBrush.ViewportUnits = BrushMappingMode.Absolute
            backgroundBrush.Viewport = Rect(0, 0, bi.Width, bi.Height)
            backgroundBrush.Stretch = Stretch.None

            if backgroundBrush.CanFreeze:
                backgroundBrush.Freeze()

        if backgroundBrush is None and config.AppSettings.Settings[
                "BackgroundColor"] is not None:
            if config.AppSettings.Settings["BackgroundColor"].Value.Length > 0:
                backgroundBrush = SolidColorBrush(
                    ColorConverter.ConvertFromString(
                        config.AppSettings.Settings["BackgroundColor"].Value))

                if backgroundBrush.CanFreeze:
                    backgroundBrush.Freeze()

        if config.AppSettings.Settings["TextColor"] is not None:
            if config.AppSettings.Settings["TextColor"].Value.Length > 0:
                textColor = ColorConverter.ConvertFromString(
                    config.AppSettings.Settings["TextColor"].Value)

        textBrush = SolidColorBrush(textColor)

        if textBrush.CanFreeze:
            textBrush.Freeze()

        window = Window()

        def onClick(source, args):
            global username, password

            if not String.IsNullOrEmpty(
                    usernameTextBox.Text) and not String.IsNullOrEmpty(
                        passwordBox.Password):
                username = usernameTextBox.Text
                password = passwordBox.Password

                def onSave():
                    try:
                        fs = None
                        sr = None
                        sw = None

                        try:
                            fs = FileStream(__file__, FileMode.Open,
                                            FileAccess.ReadWrite,
                                            FileShare.Read)
                            encoding = UTF8Encoding(False)
                            sr = StreamReader(fs, encoding, True)
                            lines = Regex.Replace(
                                Regex.Replace(
                                    sr.ReadToEnd(), "username\\s*=\\s*\"\"",
                                    String.Format("username = \"{0}\"",
                                                  username),
                                    RegexOptions.CultureInvariant),
                                "password\\s*=\\s*\"\"",
                                String.Format("password = \"{0}\"", password),
                                RegexOptions.CultureInvariant)
                            fs.SetLength(0)
                            sw = StreamWriter(fs, encoding)
                            sw.Write(lines)

                        finally:
                            if sw is not None:
                                sw.Close()

                            if sr is not None:
                                sr.Close()

                            if fs is not None:
                                fs.Close()

                    except Exception, e:
                        Trace.WriteLine(e.clsException.Message)
                        Trace.WriteLine(e.clsException.StackTrace)

                def onCompleted(task):
                    global menuItem

                    for window in Application.Current.Windows:
                        if window is Application.Current.MainWindow and window.ContextMenu is not None:
                            if window.ContextMenu.Items.Contains(menuItem):
                                window.ContextMenu.Items.Remove(menuItem)
                                window.ContextMenu.Opened -= onOpened

                                if window.ContextMenu.Items[10].GetType(
                                ).IsInstanceOfType(window.ContextMenu.Items[
                                        window.ContextMenu.Items.Count - 4]):
                                    window.ContextMenu.Items.RemoveAt(10)

                    menuItem = None

                Task.Factory.StartNew(
                    onSave, TaskCreationOptions.LongRunning).ContinueWith(
                        onCompleted,
                        TaskScheduler.FromCurrentSynchronizationContext())

            window.Close()
Ejemplo n.º 18
0
from System.IO import Path, File, Directory, FileInfo
from System.Diagnostics import Process
import os

# clear console output
Zen.Application.MacroEditor.ClearMessages()

CZIfiles_short = []
CZIdict = {}
# get all open documents
opendocs = Zen.Application.Documents
for doc in opendocs:
    image = Zen.Application.Documents.GetByName(doc.Name)
    if image.FileName.EndsWith('.czi'):
        # get the filename of the current document only when it ends with '.czi'
        CZIfiles_short.append(Path.GetFileName(image.FileName))
        CZIdict[Path.GetFileName(image.FileName)] = image.FileName

# define possible separators
separator_list = ['tab', 'comma', 'semicolon']
# define image formats for saving figure
saveformat_list = ['jpg', 'png', 'tiff']

# this location might have to be adapted
SCRIPT = r'showZsurface.bat'

# activate GUI
wd = ZenWindow()
wd.Initialize('PlaneTable Tool')
# add components to dialog
wd.AddLabel('Extract PlaneData from CZI using Python-BioFormats.')
Ejemplo n.º 19
0
 def __init__(self, path):
     self.Path = path
     self.Title = Path.GetFileName(path)
Ejemplo n.º 20
0
"""
# start Fiji and execute the macro
app = Process();
app.StartInfo.FileName = IMAGEJ
app.StartInfo.Arguments = option
app.Start()
# wait until the script is finished
app.WaitForExit()
excode = app.ExitCode
print('Exit Code: ', excode)
"""

# read parameters again after external image analysis
params = jt.readjson(jsonfilepath)

# initialize ZenTable object
SingleObj = ZenTable()

# read the result table and convert into a Zentable
SingleObj = ft.ReadResultTable(params['RESULTTABLE'], 1, '\t', 'FijiTable',
                               SingleObj)

# change the name of the table
SingleObj.Name = Path.GetFileNameWithoutExtension(
    Path.GetFileName(params['RESULTTABLE']))

# show and save data tables to the specified folder
Zen.Application.Documents.Add(SingleObj)

print('Done.')
Ejemplo n.º 21
0
def getshortfiles(filelist):
    files_short = []
    for short in filelist:
        files_short.append(Path.GetFileName(short))

    return files_short
Ejemplo n.º 22
0
# clear output
Zen.Application.MacroEditor.ClearMessages()

# Adapt this to your Fiji macro folder
default_macro_folder = r'C:\Users\Public\Documents\Fiji\macros\Zen_Test'
print 'Current Macro Folder : ', default_macro_folder

# Fiji macro for opening the CZI windowless --&gt; default macro for opening a CZI without the BioFormats input window
bf_windowless = r'c:\Users\Public\Documents\Fiji\macros\Zen_Test\Open_CZI_BioFormats_Windowless.ijm'

macros = Directory.GetFiles(default_macro_folder)
macrofiles_short = []
Macrodict = {}
# get all macros from folder
for macro in macros:
    macrofiles_short.append(Path.GetFileName(macro))
    Macrodict[Path.GetFileName(macro)] = macro

CZIfiles_short = []
CZIdict = {}

# get all open documents
opendocs = Zen.Application.Documents
for doc in opendocs:
    #print doc.Name
    image = Zen.Application.Documents.GetByName(doc.Name)
    
    if image.FileName.EndsWith('.czi'):
        # get the filename of the current document only when it ends with '.czi'
        CZIfiles_short.append(Path.GetFileName(image.FileName))
        CZIdict[Path.GetFileName(image.FileName)] = image.FileName
Ejemplo n.º 23
0
# clear console output
Zen.Application.MacroEditor.ClearMessages()

CZIfiles_short = []
CZIdict = {}

# get all open documents from ZEN
opendocs = Zen.Application.Documents

for doc in opendocs:
    # check if document is an image
    if isinstance(doc, ZenImage):

        # get the filename of the current document
        CZIfiles_short.append(Path.GetFileName(doc.FileName))
        CZIdict[Path.GetFileName(doc.FileName)] = doc.FileName

# check the location of folder where experiment setups and image analysis settings are stored
docfolder = Zen.Application.Environment.GetFolderPath(
    ZenSpecialFolder.UserDocuments)
imgfolder = Zen.Application.Environment.GetFolderPath(
    ZenSpecialFolder.ImageAutoSave)

# or you your own default folder
imgfolder = r'c:\Output\Intellesis_Batch_Test'

# maximum number of classes
maxclass = 16
classlist = createidstr(maxclass)
# start Fiji script in headless mode
app = Process()
#app.StartInfo.FileName = IMAGEJ
app.StartInfo.FileName = "java"
app.StartInfo.Arguments = fijistr
app.Start()
# wait until the script is finished
app.WaitForExit()
excode = app.ExitCode

print('Exit Code: ', excode)
print('Fiji Analysis Run Finished.')

# read metadata JSON - the name of the file must be specified correctly
md_out = jt.readjson(jsonfilepath)
print('ResultTable: ', md_out['RESULTTABLE'])

# initialize ZenTable object
SingleObj = ZenTable()
# read the result table and convert into a ZenTable
SingleObj = ct.ReadResultTable(md_out['RESULTTABLE'], 1, '\t', 'FijiTable',
                               SingleObj)
# change the name of the table
SingleObj.Name = Path.GetFileNameWithoutExtension(
    Path.GetFileName(md_out['RESULTTABLE']))
# show and save data tables to the specified folder
Zen.Application.Documents.Add(SingleObj)

print('Done.')
Ejemplo n.º 25
0
def onOpened(s, e):
    global menuItem

    menuItem.Items.Clear()

    config = None
    directory = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        Assembly.GetEntryAssembly().GetName().Name)

    if Directory.Exists(directory):
        fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location)

        for fileName2 in Directory.EnumerateFiles(directory, "*.config"):
            if fileName1.Equals(Path.GetFileNameWithoutExtension(fileName2)):
                exeConfigurationFileMap = ExeConfigurationFileMap()
                exeConfigurationFileMap.ExeConfigFilename = fileName2
                config = ConfigurationManager.OpenMappedExeConfiguration(
                    exeConfigurationFileMap, ConfigurationUserLevel.None)

    if config is None:
        config = ConfigurationManager.OpenExeConfiguration(
            ConfigurationUserLevel.None)
        directory = None

    if config.AppSettings.Settings["ActivateThreshold"] is not None:
        threshold = Int64.Parse(
            config.AppSettings.Settings["ActivateThreshold"].Value)

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "トーク間隔"
        else:
            childMenuItem.Header = "Talking Interval"

        menuItem.Items.Add(childMenuItem)

        intervalMenuItem1 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem1.Header = "15秒"
        else:
            intervalMenuItem1.Header = "15 seconds"

        if threshold == 150000000:
            intervalMenuItem1.IsChecked = True

        def onIntervalClick1(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "150000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem1.Click += onIntervalClick1

        childMenuItem.Items.Add(intervalMenuItem1)

        intervalMenuItem2 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem2.Header = "30秒"
        else:
            intervalMenuItem2.Header = "30 seconds"

        if threshold == 300000000:
            intervalMenuItem2.IsChecked = True

        def onIntervalClick2(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "300000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem2.Click += onIntervalClick2

        childMenuItem.Items.Add(intervalMenuItem2)

        intervalMenuItem3 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem3.Header = "1分"
        else:
            intervalMenuItem3.Header = "1 minute"

        if threshold == 600000000:
            intervalMenuItem3.IsChecked = True

        def onIntervalClick3(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "600000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem3.Click += onIntervalClick3

        childMenuItem.Items.Add(intervalMenuItem3)

        intervalMenuItem4 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem4.Header = "2分"
        else:
            intervalMenuItem4.Header = "2 minutes"

        if threshold == 1200000000:
            intervalMenuItem4.IsChecked = True

        def onIntervalClick4(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "1200000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem4.Click += onIntervalClick4

        childMenuItem.Items.Add(intervalMenuItem4)

        intervalMenuItem5 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem5.Header = "3分"
        else:
            intervalMenuItem5.Header = "3 minutes"

        if threshold == 1800000000:
            intervalMenuItem5.IsChecked = True

        def onIntervalClick5(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "1800000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem5.Click += onIntervalClick5

        childMenuItem.Items.Add(intervalMenuItem5)

    childMenuItem = MenuItem()

    if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
        childMenuItem.Header = "テーマ"
    else:
        childMenuItem.Header = "Theme"

    menuItem.Items.Add(Separator())
    menuItem.Items.Add(childMenuItem)

    menuItem1 = MenuItem()
    menuItem2 = MenuItem()
    menuItem3 = MenuItem()
    menuItem4 = MenuItem()
    menuItem5 = MenuItem()
    menuItem6 = MenuItem()
    menuItem7 = MenuItem()
    menuItem8 = MenuItem()
    menuItem9 = MenuItem()
    menuItem10 = MenuItem()

    if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
        menuItem1.Header = "ブループリント"
        menuItem2.Header = "ドット"
        menuItem3.Header = "布"
        menuItem4.Header = "リネン"
        menuItem5.Header = "ノイズ1"
        menuItem6.Header = "ノイズ2"
        menuItem7.Header = "紙"
        menuItem8.Header = "ペンタゴン"
        menuItem9.Header = "雪"
        menuItem10.Header = "ストライプ"
    else:
        menuItem1.Header = "Blueprint"
        menuItem2.Header = "Dots"
        menuItem3.Header = "Fabric"
        menuItem4.Header = "Linen"
        menuItem5.Header = "Noise 1"
        menuItem6.Header = "Noise 2"
        menuItem7.Header = "Paper"
        menuItem8.Header = "Pentagon"
        menuItem9.Header = "Snow"
        menuItem10.Header = "Stripes"

    if config.AppSettings.Settings[
            "BackgroundColor"] is not None and config.AppSettings.Settings[
                "BackgroundImage"] is not None and config.AppSettings.Settings[
                    "TextColor"] is not None and config.AppSettings.Settings[
                        "LinkColor"]:
        backColor = config.AppSettings.Settings["BackgroundColor"].Value
        backImage = config.AppSettings.Settings["BackgroundImage"].Value
        textColor = config.AppSettings.Settings["TextColor"].Value
        linkColor = config.AppSettings.Settings["LinkColor"].Value

        if backColor.Equals("#FF2574B0") and backImage.Equals(
                "Assets\\Background-Blueprint.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFEEC27"):
            menuItem1.IsChecked = True

        def onClick1(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF2574B0"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Blueprint.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFEEC27"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem1.Click += onClick1

        if backColor.Equals("#FF252525") and backImage.Equals(
                "Assets\\Background-Dots.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FF00C0FF"):
            menuItem2.IsChecked = True

        def onClick2(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF252525"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Dots.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FF00C0FF"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem2.Click += onClick2

        if backColor.Equals("#FFEAEAEA") and backImage.Equals(
                "Assets\\Background-Fabric.png") and textColor.Equals(
                    "#FF000000") and linkColor.Equals("#FFFF0066"):
            menuItem3.IsChecked = True

        def onClick3(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFEAEAEA"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Fabric.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF000000"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF0066"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem3.Click += onClick3

        if backColor.Equals("#FF252525") and backImage.Equals(
                "Assets\\Background-Linen.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFF6600"):
            menuItem4.IsChecked = True

        def onClick4(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF252525"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Linen.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem4.Click += onClick4

        if backColor.Equals("#FFF2F2F2") and backImage.Equals(
                "Assets\\Background-Noise1.png") and textColor.Equals(
                    "#FF333333") and linkColor.Equals("#FFFF0066"):
            menuItem5.IsChecked = True

        def onClick5(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFF2F2F2"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Noise1.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF333333"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF0066"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem5.Click += onClick5

        if backColor.Equals("#FF262727") and backImage.Equals(
                "Assets\\Background-Noise2.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFF6600"):
            menuItem6.IsChecked = True

        def onClick6(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF262727"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Noise2.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem6.Click += onClick6

        if backColor.Equals("#FFFCFCFC") and backImage.Equals(
                "Assets\\Background-Paper.png") and textColor.Equals(
                    "#FF000000") and linkColor.Equals("#FFFF0099"):
            menuItem7.IsChecked = True

        def onClick7(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFFCFCFC"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Paper.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF000000"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF0099"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem7.Click += onClick7

        if backColor.Equals("#FFEEEEEE") and backImage.Equals(
                "Assets\\Background-Pentagon.png") and textColor.Equals(
                    "#FF333333") and linkColor.Equals("#FF00A0E9"):
            menuItem8.IsChecked = True

        def onClick8(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFEEEEEE"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Pentagon.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF333333"
            config.AppSettings.Settings["LinkColor"].Value = "#FF00A0E9"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem8.Click += onClick8

        if backColor.Equals("#FFFBFBFB") and backImage.Equals(
                "Assets\\Background-Snow.png") and textColor.Equals(
                    "#FF000000") and linkColor.Equals("#FF00A0E9"):
            menuItem9.IsChecked = True

        def onClick9(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFFBFBFB"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Snow.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF000000"
            config.AppSettings.Settings["LinkColor"].Value = "#FF00A0E9"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem9.Click += onClick9

        if backColor.Equals("#FF39343D") and backImage.Equals(
                "Assets\\Background-Stripes.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFF6600"):
            menuItem10.IsChecked = True

        def onClick10(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF39343D"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Stripes.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem10.Click += onClick10

    childMenuItem.Items.Add(menuItem1)
    childMenuItem.Items.Add(menuItem2)
    childMenuItem.Items.Add(menuItem3)
    childMenuItem.Items.Add(menuItem4)
    childMenuItem.Items.Add(menuItem5)
    childMenuItem.Items.Add(menuItem6)
    childMenuItem.Items.Add(menuItem7)
    childMenuItem.Items.Add(menuItem8)
    childMenuItem.Items.Add(menuItem9)
    childMenuItem.Items.Add(menuItem10)

    if config.AppSettings.Settings["DropShadow"] is not None:
        dropShadow = Boolean.Parse(
            config.AppSettings.Settings["DropShadow"].Value)

        childMenuItem = MenuItem()
        childMenuItem.IsCheckable = True
        childMenuItem.IsChecked = dropShadow

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "ドロップシャドウを有効にする"
        else:
            childMenuItem.Header = "Enable Drop Shadow"

        def onClick(sender, args):
            config.AppSettings.Settings[
                "DropShadow"].Value = sender.IsChecked.ToString()
            config.Save(ConfigurationSaveMode.Modified)

        childMenuItem.Click += onClick

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

    menuItem.Items.Add(Separator())

    if config.AppSettings.Settings["FontFamily"] is not None:
        fontFamilyName = config.AppSettings.Settings["FontFamily"].Value

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フォント"
        else:
            childMenuItem.Header = "Font"

        menuItem.Items.Add(childMenuItem)

        for fontFamily in [
                "Arial", "Calibri", "Cambria", "Candara", "Constantia",
                "Corbel", "Courier New", "Geogia", "MS UI Gothic", "Segoe UI",
                "Tahoma", "Times New Roman", "Verdana", "メイリオ", "MS ゴシック"
        ]:
            fontMenuItem = MenuItem()
            fontMenuItem.Header = fontFamily

            if fontFamily.Equals(fontFamilyName):
                fontMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["FontFamily"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            fontMenuItem.Click += onClick

            childMenuItem.Items.Add(fontMenuItem)

    if config.AppSettings.Settings["FontSize"] is not None:
        fontSize = config.AppSettings.Settings["FontSize"].Value

        fontSizeConverter = FontSizeConverter()
        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フォントサイズ"
        else:
            childMenuItem.Header = "Font Size"

        menuItem.Items.Add(childMenuItem)

        for size in [
                "8pt", "9pt", "10pt", "11pt", "12pt", "14pt", "16pt", "18pt",
                "20pt", "22pt", "24pt"
        ]:
            fontMenuItem = MenuItem()
            fontMenuItem.Header = size

            if fontSize.Equals(size):
                fontMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["FontSize"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            fontMenuItem.Click += onClick

            childMenuItem.Items.Add(fontMenuItem)

        if config.AppSettings.Settings["LineHeight"] is not None:
            lineHeight = Double.Parse(
                config.AppSettings.Settings["LineHeight"].Value)
            maxLineHeight = Convert.ToInt32(
                fontSizeConverter.ConvertFromString(fontSize)) * 2

            if maxLineHeight < lineHeight:
                maxLineHeight = lineHeight

            childMenuItem2 = MenuItem()

            if CultureInfo.CurrentCulture.Equals(
                    CultureInfo.GetCultureInfo("ja-JP")):
                childMenuItem2.Header = "行間"
            else:
                childMenuItem2.Header = "Line Height"

            menuItem.Items.Add(childMenuItem2)

            for i in range(
                    Convert.ToInt32(
                        fontSizeConverter.ConvertFromString(fontSize)),
                    Convert.ToInt32(maxLineHeight) + 1):
                lineHeightMenuItem = MenuItem()
                lineHeightMenuItem.Header = i.ToString()

                if lineHeight == i:
                    lineHeightMenuItem.IsChecked = True

                def onClick(sender, args):
                    config.AppSettings.Settings[
                        "LineHeight"].Value = sender.Header
                    config.Save(ConfigurationSaveMode.Modified)

                lineHeightMenuItem.Click += onClick

                childMenuItem2.Items.Add(lineHeightMenuItem)

    if config.AppSettings.Settings["FrameRate"] is not None:
        frameRate = Double.Parse(
            config.AppSettings.Settings["FrameRate"].Value)

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フレームレート"
        else:
            childMenuItem.Header = "Frame Rate"

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

        for i in [24, 30, 60]:
            frameRateMenuItem = MenuItem()
            frameRateMenuItem.Header = i.ToString()

            if frameRate == Convert.ToDouble(i):
                frameRateMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["FrameRate"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            frameRateMenuItem.Click += onClick

            childMenuItem.Items.Add(frameRateMenuItem)

    if config.AppSettings.Settings["Subscriptions"] is not None:
        path = config.AppSettings.Settings["Subscriptions"].Value

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フィード"
        else:
            childMenuItem.Header = "Subscriptions"

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

        editMenuItem = MenuItem()
        editMenuItem.Tag = path

        def onEdit(sender, args):
            global program

            path = sender.Tag

            def onStart(state):
                Process.Start(state)

            psi = ProcessStartInfo()

            if String.IsNullOrEmpty(program):
                psi.FileName = path
            else:
                psi.FileName = program
                psi.Arguments = path

            Task.Factory.StartNew(onStart, psi)

        editMenuItem.Click += onEdit

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            editMenuItem.Header = "フィードの編集..."
        else:
            editMenuItem.Header = "Edit..."

        childMenuItem.Items.Add(editMenuItem)
        childMenuItem.Items.Add(Separator())

        if directory is not None:
            fileName = Path.Combine(directory, path)

            if File.Exists(fileName):
                path = fileName

        def parseOutline(m, n):
            if not n.HasChildNodes:
                return None

            for xmlNode in n.ChildNodes:
                if xmlNode.Name.Equals("outline"):
                    text = None
                    xmlUrl = None
                    htmlUrl = None

                    for xmlAttribute in xmlNode.Attributes:
                        if xmlAttribute.Name.Equals(
                                "title") or xmlAttribute.Name.Equals("text"):
                            text = xmlAttribute.Value
                        elif xmlAttribute.Name.Equals("xmlUrl"):
                            xmlUrl = xmlAttribute.Value
                        elif xmlAttribute.Name.Equals("htmlUrl"):
                            htmlUrl = xmlAttribute.Value

                    if not String.IsNullOrEmpty(text):
                        if String.IsNullOrEmpty(xmlUrl):
                            mi = MenuItem()
                            mi.Header = text

                            parsedMenuItem = parseOutline(mi, xmlNode)

                            if parsedMenuItem is None:
                                m.Items.Add(mi)
                            else:
                                m.Items.Add(parsedMenuItem)
                        elif not String.IsNullOrEmpty(xmlUrl):
                            mi = MenuItem()

                            def onClick(sender, args):
                                if not String.IsNullOrEmpty(sender.Tag):

                                    def onStart(state):
                                        Process.Start(state)

                                    Task.Factory.StartNew(onStart, sender.Tag)

                            mi.Header = text
                            mi.Click += onClick
                            mi.Tag = htmlUrl

                            m.Items.Add(mi)

            return m

        doc = XmlDocument()
        doc.Load(path)

        for xmlNode in doc.SelectNodes("/opml/body"):
            parseOutline(childMenuItem, xmlNode)

    if config.AppSettings.Settings["Timeout"] is not None:
        timeout = Int32.Parse(config.AppSettings.Settings["Timeout"].Value)

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "タイムアウト"
        else:
            childMenuItem.Header = "Timeout"

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

        for i in [15000, 30000, 60000, 120000, 180000]:
            timeMenuItem = MenuItem()
            timeMenuItem.Header = i.ToString()

            if timeout == i:
                timeMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["Timeout"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            timeMenuItem.Click += onClick

            childMenuItem.Items.Add(timeMenuItem)

    if config.AppSettings.Settings["Cache"] is not None:
        path = config.AppSettings.Settings["Cache"].Value

        if directory is not None:
            path = Path.Combine(directory, path)

        childMenuItem = MenuItem()
        childMenuItem.Tag = path

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "キャッシュをクリア"
        else:
            childMenuItem.Header = "Clear Cache"

        def onClick(sender, args):
            if Directory.Exists(childMenuItem.Tag):
                for fileName in Directory.EnumerateFiles(childMenuItem.Tag):
                    File.Delete(fileName)

        childMenuItem.Click += onClick

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

    childMenuItem = MenuItem()

    if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
        childMenuItem.Header = "GCを強制的に実行"
    else:
        childMenuItem.Header = "Force Garbage Collection"

    def onClick(sender, args):
        GC.Collect()

    childMenuItem.Click += onClick

    menuItem.Items.Add(childMenuItem)
Ejemplo n.º 26
0
from System.IO import Path, File, Directory, FileInfo

version = 0.2

CZIfiles_short = []

# get all open documents
opendocs = Zen.Application.Documents

for doc in opendocs:

    image = Zen.Application.Documents.GetByName(doc.Name)
    if image.FileName.EndsWith('.czi'):
        # get the filename of the current document only when it ends with '.czi'
        CZIfiles_short.append(Path.GetFileName(image.FileName))

formats = ['*.czi', '*.jpg', '*.tiff', '*.ome.tiff']
imgfolder = Path.Combine(
    Zen.Application.Environment.GetFolderPath(ZenSpecialFolder.Images),
    'OAD-Test')

# Initialize the dialog window for the required user inputs
wd = ZenWindow()
wd.Initialize('Save Tiles as Single Images - Version: ' + str(version))
wd.AddDropDown('czi', 'Select CZI Image Data', CZIfiles_short, 0, '0', '0')
wd.AddFolderBrowser('savefolder', 'Specify Save Folder', imgfolder, '1', '0')
wd.AddDropDown('saveformat', 'Select Image Format', formats, 0, '2', '0')

# show the window
result = wd.Show()
    return jobjectSnapshotData[SNAPSHOT_DATA__REVIT_JOURNAL_FILE].ToObject[str]()

def CopySnapshotRevitJournalFile(snapshotDataFolderPath, output):
    revitJournalFilePath = None
    try:
        snapshotDataFilePath = GetSnapshotDataFilePath(snapshotDataFolderPath)
        revitJournalFilePath = ReadSnapshotDataRevitJournalFilePath(snapshotDataFilePath)
    except Exception, e:
        output()
        output("WARNING: failed to read journal file path from snapshot data file.")
        exception_util.LogOutputErrorDetails(e, output)
        output()
        output("Attempting to read journal file path from temporary snapshot data file instead.")
        snapshotDataFilePath = GetTemporarySnapshotDataFilePath(snapshotDataFolderPath)
        revitJournalFilePath = ReadSnapshotDataRevitJournalFilePath(snapshotDataFilePath)
    revitJournalFileName = Path.GetFileName(revitJournalFilePath)
    snapshotRevitJournalFilePath = Path.Combine(snapshotDataFolderPath, revitJournalFileName)
    File.Copy(revitJournalFilePath, snapshotRevitJournalFilePath)
    return

def ConsolidateSnapshotData(dataExportFolderPath, output):
    try:
        snapshotDataFilePath = GetSnapshotDataFilePath(dataExportFolderPath)
        temporarySnapshotDataFilePath = GetTemporarySnapshotDataFilePath(dataExportFolderPath)
        if File.Exists(snapshotDataFilePath):
            if File.Exists(temporarySnapshotDataFilePath):
                File.Delete(temporarySnapshotDataFilePath)
        elif File.Exists(temporarySnapshotDataFilePath):
            File.Move(temporarySnapshotDataFilePath, snapshotDataFilePath)
        else:
            output()
# show result image
rimage = Zen.Application.LoadImage(md_out['RESULTIMAGE'])
Zen.Application.Documents.Add(rimage)

# auto-dosplay min-max
ids = rimage.DisplaySetting.GetAllChannelIds()
for id in ids:
    rimage.DisplaySetting.SetParameter(id, 'IsAutoApplyEnabled', True)

# initialize ZenTable object
SingleObj = ZenTable()
# read the result table and convert into a ZenTable
SingleObj = ct.ReadResultTable(md_out['RESULTTABLE'], 1, '\t', 'FijiTable', SingleObj)
# change the name of the table
SingleObj.Name = Path.GetFileNameWithoutExtension(Path.GetFileName(md_out['RESULTTABLE']))
# show and save data tables to the specified folder
Zen.Application.Documents.Add(SingleObj)

# check the table for the required colums
colrequired = ['BX', 'BY', 'Width', 'Height']
colID, columnOK = ct.CheckTableColumns(SingleObj, requiredcols=colrequired)

if columnOK == False:
    message = 'Required column(s) not found. No Detailed Experiment is possible.'
    print message
    raise SystemExit

# check the number of detected objects = rows inside image analysis table
num_POI = SingleObj.RowCount
Ejemplo n.º 29
0
    def PreRenderTasks(self):
        self.LogInfo("Starting V-Ray Task")

        # Get the scene file to render.
        sceneFilename = self.GetPluginInfoEntry("InputFilename")
        sceneFilename = RepositoryUtils.CheckPathMapping(sceneFilename)
        sceneFilename = PathUtils.ToPlatformIndependentPath(sceneFilename)

        # If we're rendering separate files per frame, need to get the vrscene file for the current frame.
        separateFilesPerFrame = self.GetBooleanPluginInfoEntryWithDefault(
            "SeparateFilesPerFrame", False)
        if separateFilesPerFrame:
            currPadding = FrameUtils.GetFrameStringFromFilename(sceneFilename)
            paddingSize = len(currPadding)
            newPadding = StringUtils.ToZeroPaddedString(
                self.GetStartFrame(), paddingSize, False)
            sceneFilename = sceneFilename.replace(currPadding, newPadding)

        # Check if we should be doing path mapping.
        slaveInfo = RepositoryUtils.GetSlaveInfo(self.GetSlaveName(), True)
        if self.GetBooleanConfigEntryWithDefault(
                "EnableVrscenePathMapping",
                True) or slaveInfo.IsAWSPortalInstance:
            self.LogInfo("Performing path mapping on vrscene file")

            tempSceneDirectory = self.CreateTempDirectory(
                "thread" + str(self.GetThreadNumber()))
            tempSceneFileName = Path.GetFileName(sceneFilename)
            self.tempSceneFilename = os.path.join(tempSceneDirectory,
                                                  tempSceneFileName)

            mappedFiles = set()
            filesToMap = [(sceneFilename, os.path.dirname(sceneFilename))]
            while filesToMap:
                curFile, originalSceneDirectory = filesToMap.pop()
                #Include directives normally contain relative paths but just to be safe we must run pathmapping again.
                curFile = RepositoryUtils.CheckPathMapping(curFile)

                if not os.path.isabs(curFile):
                    curFile = os.path.join(originalSceneDirectory, curFile)

                if not os.path.exists(curFile):
                    self.LogInfo("The include file %s does not exist." %
                                 curFile)
                    continue

                if os.path.basename(curFile) in mappedFiles:
                    self.LogInfo(
                        "The include file %s has already been mapped." %
                        curFile)
                    continue

                self.LogInfo("Starting to map %s" % curFile)

                mappedFiles.add(os.path.basename(curFile))
                tempFileName = os.path.join(tempSceneDirectory,
                                            os.path.basename(curFile))

                foundFiles = self.map_vrscene_includes_cancelable(
                    curFile, tempFileName)
                newOriginDirectory = os.path.dirname(curFile)
                for foundFile in foundFiles:
                    filesToMap.append((foundFile, newOriginDirectory))

                map_files_and_replace_slashes(tempFileName, tempFileName)
                if self.IsCanceled():
                    self.FailRender(
                        "Received cancel task command from Deadline.")

        else:
            self.tempSceneFilename = sceneFilename

        self.tempSceneFilename = PathUtils.ToPlatformIndependentPath(
            self.tempSceneFilename)
Ejemplo n.º 30
0
from System.Collections.Generic import List
from System.Configuration import ConfigurationManager, ConfigurationUserLevel, ExeConfigurationFileMap
from System.Globalization import CultureInfo
from System.Reflection import Assembly
from System.Xml.Linq import XDocument, XElement, XAttribute
from System.Xml.Serialization import XmlSerializer
from System.Windows import Point, Size
from Apricot import Character

config = None
directory = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
    Assembly.GetEntryAssembly().GetName().Name)

if Directory.Exists(directory):
    fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location)

    for fileName2 in Directory.EnumerateFiles(directory, "*.config"):
        if fileName1.Equals(Path.GetFileNameWithoutExtension(fileName2)):
            exeConfigurationFileMap = ExeConfigurationFileMap()
            exeConfigurationFileMap.ExeConfigFilename = fileName2
            config = ConfigurationManager.OpenMappedExeConfiguration(
                exeConfigurationFileMap, ConfigurationUserLevel.None)

if config is None:
    config = ConfigurationManager.OpenExeConfiguration(
        ConfigurationUserLevel.None)
    directory = None

if config.AppSettings.Settings["Characters"] is not None:
    path = config.AppSettings.Settings[