示例#1
0
def GetSessionFolderPath(dataExportFolderPath, sessionStartTime):
  return Path.Combine(
      dataExportFolderPath,
      snapshot_data_util.GetSnapshotFolderName(sessionStartTime.ToLocalTime())
    )
示例#2
0
__author__ = "soopercool101"
__version__ = "1.0.0"

from BrawlCrate.API import BrawlAPI
from System.IO import Path

BrawlAPI.OpenTemplate(
    Path.Combine(BrawlAPI.PluginPath, "Project M 3.6 Stage Templates",
                 "STGVILLAGE_nv.pac"))
示例#3
0
# Run ApoTome Processing automatically after acquisition
# Script by Sven Terclavers - [email protected]

from System.IO import File, Directory, FileInfo, Path
OutImage = r'C:\\ZEN_Output'

#Read Active Image & prepare Output Image

image = Zen.Application.Documents.ActiveDocument

#Process ApoTome Active Raw Image

nb_phase = image.Bounds.SizeH
apotome_image = Zen.Processing.Utilities.ApoTomeSimConvert(
    image, ZenApoTomeProcessingMode.Sectioned,
    ZenSimCorrectionMode.LocalIntensity, ZenNormalizeMode.Clip,
    ZenApoTomeFilter.Off, False)
Zen.Application.Documents.Add(apotome_image)

#Save Processed file

image_name = image.Name.Replace('.czi', '_Apotome.czi')
imageName = Path.Combine(OutImage, image_name)
apotome_image.Save(imageName)
示例#4
0
#####################################################################################
#
#  Copyright (c) Microsoft Corporation. All rights reserved.
#
#  This source code is subject to terms and conditions of the Shared Source License
#  for IronPython. A copy of the license can be found in the License.html file
#  at the root of this distribution. If you can not locate the Shared Source License
#  for IronPython, please send an email to [email protected].
#  By using this source code in any fashion, you are agreeing to be bound by
#  the terms of the Shared Source License for IronPython.
#
#  You must not remove this notice, or any other, from this software.
#
######################################################################################

import sys
import clr
from System.IO import Path, Directory, FileInfo

dir = Path.Combine(sys.prefix, 'DLLs')
if Directory.Exists(dir):
    sys.path.append(dir)
    files = Directory.GetFiles(dir)
    for file in files:
        if file.lower().endswith('.dll'):
            try:
                clr.AddReference(FileInfo(file).Name)
            except:
                pass
示例#5
0
文件: 3.1.0.0.py 项目: wlk0/OCTGN
def wd(relativePath):
    return Path.Combine(_wd, relativePath)
示例#6
0
from System.IO import Directory, Path

def getshortfiles(filelist):
    files_short = []
    for short in filelist:
        files_short.append(Path.GetFileName(short))

    return files_short

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


# get list with all existing experiments and image analysis setup and a short version of that list
expfiles = Directory.GetFiles(Path.Combine(docfolder, 'Experiment Setups'), '*.czexp')
ipfiles = Directory.GetFiles(Path.Combine(docfolder, 'Image Analysis Settings'), '*.czias')
expfiles_short = getshortfiles(expfiles)
ipfiles_short = getshortfiles(ipfiles)

# Initialize Dialog
window = ZenWindow()

# add components to dialog
window.AddLabel('1) Select Overview Experiment  ------------------------------')
window.AddDropDown('overview_exp', 'Overview Scan Experiment', expfiles_short, 0)
window.AddLabel('2) Select Image Analysis to detect objects  ----------------------')
window.AddDropDown('ip_pipe', 'Image Analysis Pieline', ipfiles_short, 0)

# show the window
result = window.Show()
示例#7
0
##############################################################################

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

# 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'

# get list with all existing models and a short version of that list
modelfolder = Path.Combine(docfolder, 'Model-Repository')
modelfiles = Directory.GetFiles(modelfolder, '*.xml')

if is_empty(modelfiles):
    # catch exception in case the folder contains no models at all
    message = 'No modelfiles found in specified folder: '
    print(message, Path.Combine(docfolder, 'Model-Repository'))
    raise SystemExit

# get the list of filename use only the basefilename
modelfiles_short = getshortfiles(modelfiles)
modeldict = {}

# create list for the short modelnames to be used iside UI of dialog
modelnames_short = []
print
print "Starting..."

if configuration not in EXPECTED_CONFIGS:
    raise Exception("Unexpected configuration specified: '" + configuration +
                    "'")

VC_FOLDER_PATH = VC_FOLDER_PATHS.Where(
    lambda p: Directory.Exists(p)).LastOrDefault()

if VC_FOLDER_PATH is None:
    raise Exception(
        "Could not locate MSBuild toolset (for vcvarsall.bat, etc.)")

COMMAND_PARTS = [
    r'"' + Path.Combine(VC_FOLDER_PATH, VC_VARS_ALL_FILENAME) + '"',
    toolset,
    "&&",
    MSBUILD_FILENAME,
    '"' + buildFile + '"',
    "/m",  # enables parallel build
    "/t:" + tasks,
    "/p:Configuration=" + configuration,
    "/p:Platform=" + '"' + platform + '"',
]

if configuration == RELEASE_CONFIG:
    COMMAND_PARTS.extend(
        ["/p:AllowedReferenceRelatedFileExtensions=none", "/p:DebugType=none"])

if DISABLE_POST_BUILD_EVENT:
示例#9
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)
示例#10
0
# default folder for output
imgfolder = r'c:\Temp\output'

# minimum number of polygon points for an ROI
minpoints_polygon = 10

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

# check the location of experiment setups and image analysis settings are stored
docfolder = Zen.Application.Environment.GetFolderPath(
    ZenSpecialFolder.UserDocuments)
format = '%Y-%m-%d_%H-%M-%S'

# get list with all existing experiments and image analysis setup and a short version of that list
expfiles = Directory.GetFiles(Path.Combine(docfolder, 'Experiment Setups'),
                              '*.czexp')
ipfiles = Directory.GetFiles(
    Path.Combine(docfolder, 'Image Analysis Settings'), '*.czias')
expfiles_short = getshortfiles(expfiles)
ipfiles_short = getshortfiles(ipfiles)

# Initialize Dialog
smartD = ZenWindow()
smartD.Initialize('Smart Dynamcis - Version : 0.1.0')
# add components to dialog
smartD.AddLabel(
    '1) Select Dynamics Experiment  ------------------------------')
smartD.AddDropDown('dynamics_exp', 'Dynamics Experiment', expfiles_short, 0)
smartD.AddCheckbox('fs_before_exp',
                   'OPTION - FindSurface (DF only) before Overview', False)
示例#11
0
def CreateRegionsFromIA(exp,
                        snap,
                        iasname,
                        expblock=0,
                        accuracy='high',
                        color=Colors.GreenYellow,
                        minpoints=10,
                        acquistion=True,
                        bleaching=False,
                        analysis=True,
                        folder=r'c:\Temp'):

    # get the scaling from the image and calculate stageTopLeft
    scaling = snap.Metadata.ScalingMicron
    stageTopLeft = exp.GetStageTopLeftOfImage(scaling, snap)

    # clear all existing experiment regions
    exp.ClearExperimentRegionsAndPositions(expblock)

    # set position regions relative to image
    exp.SetPositionRegionsRelativeToImage(expblock, False)

    # load analysis setting and analyze the image
    ias = ZenImageAnalysisSetting()
    ias.Load(iasname, ZenImageAnalysisSettingDirectory.User)
    Zen.Analyzing.Analyze(snap, ias)

    # create the table and save them as CSZ files
    # Create Zen table with results for all detected objects (parent class)
    all_obj = Zen.Analyzing.CreateRegionsTable(snap)

    # Create Zen table with results for each single object
    single_obj = Zen.Analyzing.CreateRegionTable(snap)

    # show and save data tables to the specified folder
    Zen.Application.Documents.Add(all_obj)
    Zen.Application.Documents.Add(single_obj)
    all_obj.Save(Path.Combine(folder, 'objects_all.csv'))
    single_obj.Save(Path.Combine(folder, 'objects_single.csv'))

    # check the number of detected objects = rows inside image analysis table
    num_obj = single_obj.RowCount

    # get classes and derive regions names from that
    iasclasses = getclassnames(ias)
    regionsclassname = iasclasses['2']
    regions = Zen.Analyzing.GetRegions(snap, regionsclassname)

    print('RegionClassNames: ', iasclasses)
    print('Analysis found ' + str(regions.Count) + 'regions!')

    # loop over all regions and get the points of polygon outlins of the region
    for i in range(0, regions.Count):
        # use the desired level of detail
        if accuracy == 'high':
            points = regions[i].GetPolygonHighDetails()
        if accuracy == 'low':
            points = regions[i].GetPolygon()

        if points.Length > minpoints:
            exp.AddPolygonExperimentRegion(scaling, stageTopLeft, expblock,
                                           points, color, acquistion,
                                           bleaching, analysis)
            print('Experiment region generated with region id ' + str(i + 2) +
                  ' with ' + str(points.Length) + ' points')
        else:
            print('For region id ' + str(i + 2) +
                  ' no experiment region created. No enough Polygon Points.')

    # save the experiment with the new regions
    exp.Save()

    return exp
示例#12
0
# -*- coding: utf-8 -*-
#作者:王卫生
#时间:2013-3-30

import sys
import clr
#import System

#添加VB DLL的目录
from System.IO import Directory, Path
directory = Directory.GetCurrentDirectory()
binpath = Path.Combine(directory, 'bin\\')
binpath = 'D:\\wangws\\sap_interface_project\\SAPAutomation\\SAPGuiInspector\\bin\\release\\'
#sys.path.append(r'D:\wangws\sap_interface_project\SAPAutomation\SAPGuiInspector\bin\Debug')
#sys.path.append(System.AppDomain.CurrentDomain.BaseDirectory)
sys.path.append(binpath)

filename = 'SapGuiApplicationVB.dll'

clr.AddReferenceToFile(filename)

from SapGuiApplicationVB import *
sapgui = SapGuiConnector()

Session = sapgui.getSessionByTcode("MB03")

import System
from System.Collections import *
h = Hashtable()
h["a"] = "IronPython"
示例#13
0
文件: Test.py 项目: zparr/ATF
def GetOutputDir():
    path = Path.Combine(Environment.CurrentDirectory, "tests/TestOutput")
    if (not Directory.Exists(path)):
        Directory.CreateDirectory(path)
    return path
示例#14
0
__author__ = "soopercool101"
__version__ = "1.0.0"

from BrawlCrate.API import BrawlAPI
from System.IO import Path

BrawlAPI.OpenTemplate(Path.Combine(BrawlAPI.PluginPath, "Project M 3.6 Stage Templates", "STGGREENHILL.pac"))
ias.Load(iasfilename)
classnames = ias.GetRegionClassNames()

if analyze_inplace:
    Zen.Analyzing.Analyze(image, ias)

# run the image analyis pipeline and directly create a table
all_tables = Zen.Analyzing.AnalyzeToTable(image, ias)

for class_table in all_tables:

    if show_tables:
        Zen.Application.Documents.Add(class_table)

    print('Saving table for class: ', class_table.Name + '.csv')
    class_table_filename = Path.Combine(outputpath, class_table.Name + '.csv')
    class_table.Save(class_table_filename)

    if not show_tables:
        class_table.Close()

# close the image and image analysis setting
if close_image:
    image.Close()

# close image analysis setting
ias.Close()

#############################################################################

# define parameters etc.
# get the module parameters for the specified module
params = ZenApeer.Onsite.GetSampleModuleParameters(module_name, module_version)

# show the required module inputs
print '------ Module Inputs ------'
for ip in params.Inputs:
    print ip.Key, ' : ', ip.Value

# show the required parameters and their defaults
print '------ Module Parameters ------'
for p in params.Parameters:
    print p.Key, ' : ', p.Value

# define the input file
input_image = {'IMAGEPATH': r'C:\Users\test\images\fiji_filter_image\01_3CH.ome.tiff'}
savepath = Path.Combine(Path.GetDirectoryName(input_image['IMAGEPATH']), 'saved_results')

# create the output directory if not existing
if not Directory.Exists(savepath):
    Directory.CreateDirectory(savepath)

# define the processing parameters (or use the defaults: params.Parameters
my_parameters = {'FILTERTYPE': 'MEDIAN',
                 'FILTER_RADIUS': 7}

# or use default parameters from the module
my_parameters = params.Parameters

# run the local APEER module with using keywords
runoutputs, status, log = ZenApeer.Onsite.RunModule(moduleName=module_name,
                                                    moduleVersion=module_version,
示例#17
0
 def join(self, path, *args):
     args = list(args[::-1])
     while args:
         path = Path.Combine(path, args.pop())
     return path
示例#18
0
import System.IO
from System.IO import Path, Directory, File, FileInfo

#
#############   **** USER CONFIGURABLE VARIABLES ***    ###########################################
#
#          see http://code.google.com/p/comicrack-duplicates-manager/wiki/UserConfiguration for details
#
#          These may also be set in the "dmrules.dat" rules file using this syntax:  "@ OPTION VALUE". Values
#           found in the "dmrules.dat" file override the defaults set in this file.

MOVEFILES = False
REMOVEFROMLIB = False
UPDATEINFO = False

DUPESDIRECTORY = Path.Combine("C:\\", "__dupes__")

C2C_NOADS_GAP = 5  # Difference of pages between c2c and noads
SIZEMARGIN = 0  # Preserve comics within sizemargin % size
COVERPAGES = 4  # Minimal number of pages to be considered "covers only"

VERBOSE = False  # Logging level (true/false)
DEBUG = False  # Logging level (true/false)

#
############   DON'T MODIFY BELOW THIS LINE ######
#

VERSION = "0.9"

SCRIPTDIRECTORY = __file__[0:-len("constants.py")]
示例#19
0
        Zen.Processing.Utilities.ExportHeightmapFromTopography(imgtop, topo_filepath)
        print('Exported to : ', topo_filepath)
        imgtop.Close()

    return image


###########################################################################

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

# check the location of experiment setups and image analysis settings are stored
docfolder = Zen.Application.Environment.GetFolderPath(ZenSpecialFolder.UserDocuments)
imgfolder = Zen.Application.Environment.GetFolderPath(ZenSpecialFolder.ImageAutoSave)
imgfolder = Path.Combine(imgfolder, 'Guided_Acquisition')
# imgfolder = r'c:\Output\Guided_Acquisition'
format = '%Y-%m-%d_%H-%M-%S'

# get list with all existing experiments and image analysis setup and a short version of that list
expfiles = Directory.GetFiles(Path.Combine(docfolder, 'Experiment Setups'), '*.czexp')
ipfiles = Directory.GetFiles(Path.Combine(docfolder, 'Image Analysis Settings'), '*.czias')
expfiles_short = getshortfiles(expfiles)
ipfiles_short = getshortfiles(ipfiles)

# Initialize Dialog
GuidedAcqDialog = ZenWindow()
GuidedAcqDialog.Initialize('Guided Acquisition - Version : ' + str(version))
# add components to dialog
GuidedAcqDialog.AddLabel('1) Select Overview Experiment  ------------------------------')
GuidedAcqDialog.AddDropDown('overview_exp', 'Overview Scan Experiment', expfiles_short, 0)
    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:
示例#21
0
method = 1

#### Analyze, Create Table and Export tables explicitly #######
if method == 1:

    Zen.Analyzing.Analyze(image, ias)
    # Create data list with results for all regions
    table_all = Zen.Analyzing.CreateRegionsTable(image)
    Zen.Application.Documents.Add(table_all)
    # Create data list with results for each region
    table_single = Zen.Analyzing.CreateRegionTable(image)
    Zen.Application.Documents.Add(table_single)

    # Save data list for all regions
    table_all_filename = Path.Combine(outputpath, image.Name[:-4] + '_All.csv')
    table_all.Save(table_all_filename)

    # Save data list for all single regions
    table_single_filename = Path.Combine(outputpath,
                                         image.Name[:-4] + '_Single.csv')
    table_single.Save(table_single_filename)

#### Analyze directly to CSV file #######
if method == 2:

    Zen.Analyzing.AnalyzeToFile(image, ias, outputpath, image.Name[:-4], False)

# close the image and image analysis setting
# image.Close()
# ias.Close()
def GetSnapshotDataFilePath(snapshotDataFolderPath):
    return Path.Combine(snapshotDataFolderPath, SNAPSHOT_DATA_FILENAME)
示例#23
0
import System
from System.IO import Path, FileInfo
import iniReadWrite
from System import Array
from System import StringSplitOptions
from iniReadWrite import *
from System.Collections.Generic import Dictionary
#clr.AddReference("ComicRack.Engine")
from cYo.Projects.ComicRack.Engine import MangaYesNo, YesNo

############Set Paths##############
FOLDER = FileInfo(
    __file__).DirectoryName + Path.DirectorySeparatorChar.ToString()
IMGFOLDER = FOLDER + 'images' + Path.DirectorySeparatorChar.ToString()
DATFILE = Path.Combine(
    FOLDER,
    'dataMan.dat')  #can load 1.24 text files or 2.3.1 xml files saves as xml
SAMPLEFILE = Path.Combine(FOLDER, 'dataManSample.dat')
INIFILE = Path.Combine(FOLDER, 'dataMan.ini')
USERINI = Path.Combine(FOLDER, 'user.ini')
BAKFILE = Path.Combine(FOLDER, 'dataMan.bak')
ERRFILE = Path.Combine(FOLDER, 'dataMan.err')
TMPFILE = Path.Combine(FOLDER, 'dataMan.tmp')
LOGFILE = Path.Combine(FOLDER, 'dataMan.log')
CHKFILE = Path.Combine(
    FOLDER, 'dataMan.chk')  # will be created once the configuration is saved
GUIEXE = Path.Combine(FOLDER, 'crdmgui.exe')

##############End Set Paths##############

################Set Constant variables##############
def GetTemporarySnapshotDataFilePath(snapshotDataFolderPath):
    return Path.Combine(snapshotDataFolderPath, TEMP_SNAPSHOT_DATA_FILENAME)
示例#25
0
###########################################################################

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

# check the location of experiment setups and image analysis settings are stored
docfolder = Zen.Application.Environment.GetFolderPath(
    ZenSpecialFolder.UserDocuments)
imgfolder = Zen.Application.Environment.GetFolderPath(
    ZenSpecialFolder.ImageAutoSave)
imgfolder = r'c:\Output\Guided_Acquisition'
format = '%Y-%m-%d_%H-%M-%S'

# get list with all existing experiments and image analysis setup and a short version of that list
expfiles = Directory.GetFiles(Path.Combine(docfolder, 'Experiment Setups'),
                              '*.czexp')
ipfiles = Directory.GetFiles(
    Path.Combine(docfolder, 'Image Analysis Settings'), '*.czias')
apfiles = Directory.GetFiles(Path.Combine(docfolder, 'APEER Module Settings'),
                             '*.czams')
expfiles_short = getshortfiles(expfiles)
ipfiles_short = getshortfiles(ipfiles)
apfiles_short = getshortfiles(apfiles)

# Initialize Dialog
GuidedAcqDialog = ZenWindow()
GuidedAcqDialog.Initialize('Guided Acquisition - Version : ' + str(version))
# add components to dialog
GuidedAcqDialog.AddLabel('------   Select Overview Experiment   ------')
GuidedAcqDialog.AddDropDown('overview_exp', 'Overview Scan Experiment',
示例#26
0
Zen.Application.MacroEditor.ClearMessages()

# 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)

# get list with all existing models and a short version of that list
modelfolder = Path.Combine(docfolder, 'Model-Repository')
modelfiles = Directory.GetFiles(modelfolder, '*.xml')

if is_empty(modelfiles):
    # catch exception in case the folder contains no models at all
    message = 'No modelfiles found in specified folder: '
    print(message, Path.Combine(docfolder, 'Model-Repository'))
    raise SystemExit

# get the list of filename use only the basefilename
modelfiles_short = getshortfiles(modelfiles)
modeldict = {}

# create list for the short modelnames to be used iside UI of dialog
modelnames_short = []
示例#27
0
# define the image analysis setting and run the image analysis on the active image
iasfilename = r'c:\Users\M1SRH\Documents\Carl Zeiss\ZEN\Documents\Image Analysis Settings\Count_Cells_DAPI_96well.czias'
ias = ZenImageAnalysisSetting()
ias.Load(iasfilename)
Zen.Analyzing.Analyze(image, ias)

# Create data list with results for all regions (e.g. all nuclei)
table_all = Zen.Analyzing.CreateRegionsTable(image)
Zen.Application.Documents.Add(table_all)
# Create data list with results for each region (e.g. every single nucleus)
table_single = Zen.Analyzing.CreateRegionTable(image)
Zen.Application.Documents.Add(table_single)

# Save both data lists as CSV files
table_all_filename = Path.Combine(outputpath, resultname + '_All.csv')
table_all.Save(table_all_filename)
table_single_filename = Path.Combine(outputpath, resultname + '_Single.csv')
table_single.Save(table_single_filename)

# close the image and image analysis setting
#image.Close()
ias.Close()

# define the external plot script or tool
pythonexe = r'c:\Anaconda3\python.exe'
#pythonexe =  r'c:\Anaconda3\envs\py27\python.exe'
script = r'c:\Users\M1SRH\Documents\Projects\OAD\External_Python_Scripts_for_OAD\test_wellplate_from_ZEN_py3.py'

# define the actual CSV file and the parameters
csvfile = Path.Combine(outputpath, table_single_filename)
示例#28
0
def non_steam_shortcuts():
    games_updated = 0
    games_new = 0
    games_skipped_no_action = []
    games_skipped_steam_native = []
    games_skipped_bad_emulator = []
    games_url = []

    if not isdir(join(STEAM_USERDATA, "config")):
        PlayniteApi.Dialogs.ShowErrorMessage(
            "Please configure this extension by setting the path to your Steam profile's userdata folder. "
            "Edit the nonsteam.py file of this extension and update STEAM_USERDATA.",
            "Error: Extension not configured")
        return

    if isfile(SHORTCUTS_VDF):
        try:
            shutil.copyfile(SHORTCUTS_VDF, SHORTCUTS_VDF+".bak")
        except Exception as e:
            PlayniteApi.Dialogs.ShowErrorMessage(
                traceback.format_exc(),
                "Error backing up shortcuts.vdf")
            return

        try:
            with open(SHORTCUTS_VDF, "rb") as f:
                steam_shortcuts = parse_shortcuts(f)
        except Exception as e:
            PlayniteApi.Dialogs.ShowErrorMessage(
                traceback.format_exc(),
                "Error loading shortcuts.vdf")
            return
    else:
        steam_shortcuts = {}

    for game in PlayniteApi.MainView.SelectedGames:
        play_action = find_play_action(game)

        # If a game somehow has no PlayAction, skip it
        if not play_action:
            games_skipped_no_action.append(game.Name)
            continue

        # Skip the game if it is handled by the Steam plugin
        if game.PluginId == STEAM_PLUGIN_GUID:
            games_skipped_steam_native.append(game.Name)
            continue

        # If a game has a URL PlayAction, use it anyway but log it
        if play_action.Type == GameActionType.URL:
            games_url.append(game.Name)

        # Create/Update Non-Steam shortcut
        play_action_expanded = PlayniteApi.ExpandGameVariables(game, play_action)
        if play_action_expanded.Type == GameActionType.Emulator:
            emulator = PlayniteApi.Database.Emulators.Get(play_action.EmulatorId)
            if emulator.Profiles:
                profile = emulator.Profiles.FirstOrDefault(lambda a: a.Id == play_action.EmulatorProfileId)
            else:
                profile = None
            if not profile:
                games_skipped_bad_emulator.append(game.Name)
                continue
            profile_expanded = emulator_expand_variables(profile, game)
            start_dir = profile_expanded.WorkingDirectory
            exe = profile_expanded.Executable
            arguments = profile_expanded.Arguments or ""
            if play_action_expanded.AdditionalArguments:
                arguments += " " + play_action_expanded.AdditionalArguments
            if play_action_expanded.OverrideDefaultArgs:
                arguments = play_action_expanded.Arguments or ""
        elif play_action_expanded.Type == GameActionType.File:
            start_dir = play_action_expanded.WorkingDir
            exe = play_action_expanded.Path
            arguments = play_action_expanded.Arguments or ""
        elif play_action_expanded.Type == GameActionType.URL:
            exe = play_action_expanded.Path
            start_dir = ""
            arguments = ""
        if not play_action_expanded.Type == GameActionType.URL:
            if not start_dir:
                start_dir = FileInfo(exe).Directory.FullName
            exe = Path.Combine(start_dir, exe)
        if game.Icon:
            icon = PlayniteApi.Database.GetFullFilePath(game.Icon)
        else:
            icon = ""
        shortcut = {
            "icon": icon,
            "exe": '"{}"'.format(exe),
            "startdir": '"{}"'.format(start_dir),
            "appname": game.Name,
            "launchoptions": arguments,
        }
        if game.Name in steam_shortcuts:
            games_updated += 1
            steam_shortcuts[game.Name].update(shortcut)
            shortcut = steam_shortcuts[game.Name]
        else:
            games_new += 1
            shortcut.update(SHORTCUT_DEFAULTS)
            steam_shortcuts[game.Name] = shortcut

        # Update Playnite actions
        # Only run once, don't create duplicate OtherActions
        if play_action == game.PlayAction:
            old_action = game.PlayAction
            steam_action = GameAction(
                Name="Non-Steam Steam Shortcut",
                Type=GameActionType.URL,
                Path=steam_URL(shortcut),
                IsHandledByPlugin=False,
            )
            game.PlayAction = steam_action
            if not game.OtherActions:
                game.OtherActions = ObservableCollection[GameAction]()
            old_action.Name = "Launch without Steam"
            game.OtherActions.Insert(0, old_action)
        else:
            # play_action is already an OtherAction
            # Just make sure the URL is up to date on the main PlayAction
            game.PlayAction.Path = steam_URL(shortcut)

    # Save updated shortcuts.vdf
    try:
        with open(SHORTCUTS_VDF, "wb") as f:
            dump_shortcuts(f, steam_shortcuts)
    except Exception as e:
        PlayniteApi.Dialogs.ShowErrorMessage(
            traceback.format_exc(),
            "Error saving shortcuts.vdf")
        if isfile(SHORTCUTS_VDF+".bak"):
            try:
                shutil.copyfile(SHORTCUTS_VDF+".bak", SHORTCUTS_VDF)
                PlayniteApi.Dialogs.ShowMessage(
                    "Successfully restored shortcuts.vdf backup")
            except Exception as e:
                PlayniteApi.Dialogs.ShowErrorMessage(
                    traceback.format_exc(),
                    "Error restoring shortcuts.vdf backup")
        else:
            os.remove(SHORTCUTS_VDF)
        return

    message = "Please relaunch Steam to update non-Steam shortcuts!\n\n"
    message += "Updated {} existing non-Steam shortcuts\n".format(games_updated)
    message += "Created {} new non-Steam shortcuts".format(games_new)
    if games_skipped_steam_native:
        message += "\n\nSkipped {} native Steam game(s):\n".format(len(games_skipped_steam_native))
        message += "\n".join(games_skipped_steam_native)
    if games_skipped_no_action:
        message += "\n\nSkipped {} game(s) without any PlayAction set (not installed?):\n".format(len(games_skipped_no_action))
        message += "\n".join(games_skipped_no_action)
    if games_skipped_bad_emulator:
        message += "\n\nSkipped {} emulated game(s) with bad emulator profiles:\n".format(len(games_skipped_bad_emulator))
        message += "\n".join(games_skipped_bad_emulator)
    if games_url:
        message += "\n\nWarning: Some games had URL launch actions. (Typically managed by a library plugin.) "
        message += "You may wish to update their actions and recreate non-Steam shortcuts. "
        message += "Steam will still launch these games, but the Steam overlay will not function."
        message += "\n\nThe following {} game(s) had URL launch actions:\n".format(len(games_url))
        message += "\n".join(games_url)
    PlayniteApi.Dialogs.ShowMessage(
        message,
        "Updated Non-Steam Shortcuts"
    )
示例#29
0
 def _makeDatabasePath(self, filename):
     return Path.Combine(self._dataDirectory, filename)
示例#30
0
img = Zen.Application.LoadImage(czifile, False)
Zen.Application.Documents.Add(img)

IMAGEJ = 'c:\\Fiji\\ImageJ-win64.exe'
IMAGEJDIR = Path.GetDirectoryName(IMAGEJ)
SCRIPT = 'c:\\Fiji\\scripts\\GuidedAcq_fromZEN.py'

# define script parameters
params = {}
params['IMAGEJ'] = IMAGEJ
params['IMAGEJDIR'] = IMAGEJDIR
params['IMAGEJSCRIPT'] = SCRIPT
params['IMAGE'] = czifile
params['IMAGEDIR'] = Path.GetDirectoryName(czifile)
params['FILEWOEXT'] = Path.GetFileNameWithoutExtension(czifile)
params['JSONPARAMSFILE'] = Path.Combine(params['IMAGEDIR'],
                                        params['FILEWOEXT'] + '.json')
params['BIN'] = 4
params['RANKFILTER'] = 'Median'
params['RADIUS'] = 3.0
params['MINSIZE'] = 10000
params['MINCIRC'] = 0.01
params['MAXCIRC'] = 0.99
params['THRESHOLD'] = 'Triangle'
params['THRESHOLD_BGRD'] = 'black'
params['CORRFACTOR'] = 1.0
params['PASAVE'] = True
params['SAVEFORMAT'] = 'ome.tiff'
params['RESULTTABLE'] = ''
params['RESULTIMAGE'] = ''
# additional parameters
params['CenterX'] = img.Metadata.StagePositionMicron.X