コード例 #1
0
def createfolder(basedir, formatstring='%Y-%m-%d_%H-%M-%S'):
    # construct new directoty name nased on date and time
    newdir = Path.Combine(basedir, datetime.now().strftime(formatstring))
    # check if the new directory (for whatever reasons) already exists
    try:
        newdir_exists = Directory.Exists(newdir)
        if not newdir_exists:
            # create new directory if is does not exist
            Directory.CreateDirectory(newdir)
        if newdir_exists:
            # raise error if it really already exists
            raise SystemExit
    except OSError as e:
        if e.errno != errno.EEXIST:
            newdir = None
            raise  # This was not a "directory exist" error..

    return newdir
コード例 #2
0
    def InitializePath(self):
        searchPath = []
        currentDir = Directory.GetCurrentDirectory()
        searchPath.append(currentDir)
        filePathDir = Path.GetDirectoryName(
            Path.Combine(currentDir, self.fileName))
        searchPath.append(filePathDir)
        entryDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
        searchPath.append(entryDir)
        siteDir = Path.Combine(entryDir, "Lib")
        searchPath.append(siteDir)
        devStdLibDir = Path.Combine(
            entryDir,
            '../../External.LCA_RESTRICTED/Languages/IronPython/27/Lib')
        searchPath.append(devStdLibDir)
        dllsDir = Path.Combine(entryDir, "DLLs")
        if Directory.Exists(dllsDir):
            searchPath.append(dllsDir)

        self.engine.SetSearchPaths(Array[str](searchPath))
コード例 #3
0
def SaveFamiliesOfCategory(doc, run):
    # Function to save the families of the categories specified in the project information
    # of the document
    elements = []
    familyList = []
    docPath = doc.PathName
    docPath = re.findall(r"^.*\\", docPath)[0]
    saveAsOptions = SaveAsOptions()
    saveAsOptions.OverwriteExistingFile = True
    category = doc.ProjectInformation.LookupParameter("Author").AsString()
    if not category:
        return "No category set to Author parameter"
    else:
        categories = doc.Settings.Categories
        category = categories.get_Item(category)

    collector = FilteredElementCollector(doc).OfClass(Family)
    for family in collector:
        if family.FamilyCategoryId.ToString() == category.Id.ToString():
            elements.append(family)
    for element in elements:
        eName = element.Name
        famDirectory = docPath + category.Name + "\\"
        famPath = famDirectory + eName + ".rfa"
        famPathBackup = famDirectory + eName + ".0001.rfa"
        if run:
            if not Directory.Exists(famDirectory):
                Directory.CreateDirectory(famDirectory)
            if File.Exists(famPath):
                File.Delete(famPath)
            famDoc = doc.EditFamily(element)
            famDoc.SaveAs(famPath, saveAsOptions)
            famDoc.Close(False)
            familyList.append(famPath)
            if File.Exists(famPathBackup):
                File.Delete(famPathBackup)
        else:
            familyList.append(famPath)
    return familyList
コード例 #4
0
def ImportAsciiRaster(folder, gisgroup):
    """
    <Script>
    <Author>admin</Author>
    <Description>Please enter script description here</Description>
    <Parameters>
    <Parameter name="folder" type="string">path on disk to the directory of ascii grid -files</Parameter>
    <Parameter name="gisgroup" type="string">target group - will be created if it does not exist</Parameter>
    </Parameters>
    </Script>
    """

    # Variables
    gisgroup = '/WRIS/Overlays'
    coordinateSystemName = 'GGRS87 / Greek Grid'
    folder = 'C:\Temp\MIKEFLOODCheckedOut01\OUTPUT_DATA\TemporalRasterMaxH'
    itemName = 'Water Level'
    unitName = 'meter'
    gisgrouppath = '/WRIS/Overlays/TemporalRasterMaxH'
    gisgrouppath2 = '/WRIS/Overlays/RasterName'

    gisManager = app.Modules.Get('GIS Manager')
    existingRaster = gisManager.RasterList.Fetch(gisgrouppath2)

    gisManager.RasterList.Delete(existingRaster)

    if (Directory.Exists(folder) == False):
        raise Exception('Source directory does not exist: ' + folder)

    gisManager = app.Modules.Get('GIS Manager')

    # Find the coordinate system.
    coordinateSystem = None

    for cSystem in gisManager.CoordinateSystemList.GetAll():
        if (cSystem.Name == coordinateSystemName):
            coordinateSystem = cSystem
            break

    if (coordinateSystem == None):
        raise Exception('Coordinate system not found: ' + coordinateSystemName)

    # Find the raster group to import the raster to (input item).
    rasterGroup = gisManager.RasterGroupList.Fetch(gisgroup)

    if (rasterGroup == None):
        raise Exception('Import raster group was not found: ' +
                        rasterGroupPath)

    # Find the id of the item and unit number of the item.
    eumItem = clr.StrongBox[int]()
    eumUnit = clr.StrongBox[int]()

    EUMWrapper.GetItemTypeTag(itemName, eumItem)
    EUMWrapper.GetUnitTag(unitName, eumUnit)

    existingRaster = gisManager.RasterList.Fetch(gisgrouppath)

    if (existingRaster <> None):

        gisManager.RasterList.Delete(existingRaster)

    tool = app.Tools.CreateNew('Import temporal rasters from ASCII files')
    tool.InputItems.Add(rasterGroup)
    tool.DirectoryPath = folder
    tool.DateTimeFilenameMask = 'yyyyMMddHHmm'
    tool.CoordinateSystem = coordinateSystem
    tool.AddToExistingRaster = False
    tool.Enum_Item = eumItem.Value
    tool.Enum_Unit = eumUnit.Value
    #
    tool.Execute()
    try:

        rasterPath = gisgroup + '/TemporalRasterMaxH'
        raster = gisManager.RasterList.Fetch(rasterPath)

        raster.Name = "RasterName"
        raster.DefaultSymbology = "<RasterLayerDefinition StyleType=\"Simple\" RasterStyleType=\"ValueRanges\" Name=\"4?�e?? ??????s? �????? ?at????s?? (m)\" IsVisible=\"True\" OwnOverlay=\"False\" ShowInLegend=\"True\" DispalyMapScale=\"1:577,791\"><LayerStyleDefinition Attribute=\"\" BaseColor=\"Color [Black]\" ResetMaxMin=\"True\" NumOfIntervals=\"4\" Color=\"Color [A=255, R=176, G=225, B=255]\" Transparency=\"0\" ColorTransparency=\"0\" OuterLineType=\"Solid\" OuterLineThickness=\"1\"><ValueRangeStyleDefinition MinValue=\"0.5\" MaxValue=\"1\" Color=\"Color [A=255, R=176, G=225, B=255]\" ColorTransparency=\"0\" /><ValueRangeStyleDefinition MinValue=\"1\" MaxValue=\"1.5\" Color=\"Color [A=255, R=0, G=128, B=192]\" ColorTransparency=\"0\" /><ValueRangeStyleDefinition MinValue=\"1.5\" MaxValue=\"2\" Color=\"Color [A=255, R=0, G=64, B=128]\" ColorTransparency=\"0\" /><ValueRangeStyleDefinition MinValue=\"2\" MaxValue=\"20\" Color=\"Color [A=255, R=255, G=0, B=128]\" ColorTransparency=\"0\" /><AllOtherValuesStyleDefinition /></LayerStyleDefinition><LayerScaleRange /></RasterLayerDefinition>"

        gisManager.RasterList.Update(raster)

    except Exception as e:
        print str(e)

    gisManager.RasterList.Update(raster)
    return
コード例 #5
0
ファイル: Gmail.py プロジェクト: soracoder/Apricot
    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()
コード例 #6
0
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

doc = DocumentManager.Instance.CurrentDBDocument
ui_app = DocumentManager.Instance.CurrentUIApplication
app = ui_app.Application
uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument

path_to_folder_file = 'C:/RS_logs/'
log_file_name = 'TaskDialogs_info.log'
path_to_log_file = "{}{}".format(path_to_folder_file, log_file_name)
test = []

if not Directory.Exists(path_to_folder_file):
	Directory.CreateDirectory(path_to_folder_file)


def LogSave(info):
	if info:
		string_list_info = []
		string_list_info.append("")
		string_list_info.append(DateTime.Now.ToLocalTime().ToString())
		# string_list_info.append(python_file_name)
		string_list_info.extend(info)
		IO.File.AppendAllLines(path_to_log_file, string_list_info, Text.Encoding.Unicode)


def UiAppOnDialogBoxShowing(sender_uiapp, args):
	activ_doc = sender_uiapp.ActiveUIDocument.Document
コード例 #7
0
# At least on Windows the kernel may be in here 2x with the "idle" process
# It should be safe to remove dupes
vtero.MemAccess.MapViewSize = 128 * 1024
vtero.KernelProc.InitSymbolsForVad()
#db = HashDB("C:\\temp\\iv.DB", "c:\\temp\\reloc", 1024*1024*1024*2)

for proc in proc_arr:  
    if proc.CR3Value == vtero.KernelProc.CR3Value:
        CollectKernel = True
    else:
        CollectKernel = False
    OSFileName = getattr(proc, "OSFileName", None)
    if OSFileName is None:
        OSFileName = "UNK"
    currProcBase = newdir + "\\" + OSFileName + " PID[" + proc.ProcessID.ToString() + "] CR3[" + proc.CR3Value.ToString("X") + "]"
    if Directory.Exists(currProcBase):
        continue
    dir = Directory.CreateDirectory(currProcBase)
    #proc.HDB = db
    proc.MemAccess = Mem(vtero.MemAccess)
    proc.KernelSection = vtero.KernelProc.KernelSection 
    proc.CopySymbolsForVad(vtero.KernelProc)
    PerProcDumpTime = Stopwatch.StartNew()
    #DumpProc uses PageTable to map memory for dump
    #if CollectKernel:
    #    entries = proc.DumpProc(currProcBase + "\\", False, CollectKernel)
    #else:
        # VADDUmp is based on VAD as source for dumping
    proc.VADDump(currProcBase + "\\", CollectKernel, False)
    print "Dumped Process: %s, time: %s " % (proc.ShortName, PerProcDumpTime.Elapsed.ToString())
    # use Reloc.Delocate.DeLocateFile to repair a dumped section into a block that matches disk representation 
コード例 #8
0
def GetOutputDir():
    path = Path.Combine(Environment.CurrentDirectory, "tests/TestOutput")
    if (not Directory.Exists(path)):
        Directory.CreateDirectory(path)
    return path
コード例 #9
0
    # get the module parameters for the specified module
    module_params = ZenApeer.Onsite.GetSampleModuleParameters(
        ams.ModuleName, ams.ModuleVersion)

    # get the module input programmatically
    module_inputs = get_module_inputs(module_params)

    # create the required dictionary with the correct key and value
    input_image = {module_inputs[0]: savepath_ovscan}

    # create the path to save the results
    #savepath_apeer = Path.Combine(OutputFolder, 'apeer_results')
    savepath_apeer = OutputFolder

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

    # run the local APEER module with using keywords
    try:
        runoutputs, status, log = ZenApeer.Onsite.RunModule(
            moduleName=ams.ModuleName,
            moduleVersion=ams.ModuleVersion,
            inputs=input_image,
            parameters=ams.Parameters,
            storagePath=savepath_apeer)

        for op in runoutputs.GetEnumerator():
            print('-----    Outputs   -----')
            print(op.Key, ' : ', op.Value)
コード例 #10
0
window.AddFolderBrowser('destfolder', 'Destination Folder', images)
window.AddDropDown('osval', 'Output Image type',
                   ['.czi', '.jpeg', '.ome.tiff', '.png', '.tiff'], 0)

# get and check results result=window.Show()

# check, if Cancel button was clicked
if result.HasCanceled:
    sys.exit('Macro aborted with Cancel!')

# get string name of source folder/destination folder
path = str(result.GetValue('sourcefolder'))
newPath = str(result.GetValue('destfolder'))

# Check, if path exists
if not Directory.Exists(path):
    strMessage = 'Path: ' + path + ' does not exist!\nRestart macro and select an existing path!'
    sys.exit(strMessage)

# Check, if newPath exists
if not Directory.Exists(newPath):
    strMessage = 'Path: ' + newPath + ' does not exist!\nRestart macro and select an existing path!'
    sys.exit(strMessage)

# get file type
itype = str(result.GetValue('isval'))
otype = str(result.GetValue('osval'))
files = Directory.GetFiles(path, itype)

# Check, if image type exists
if files.Length == 0:
コード例 #11
0
def exists(dir):
    if Directory.Exists(dir):
        return True
    return False
コード例 #12
0
ファイル: api.py プロジェクト: recs12/save_pdf
def is_exist(path_to_check):
    return Directory.Exists(path_to_check)
コード例 #13
0
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the  Microsoft Permissive License, 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 Microsoft Permissive License.
#
# 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

import sys
from System.IO import Directory, Path

parent = Path.Combine(sys.prefix, '..')
lib = Path.Combine(parent, 'Lib')
if Directory.Exists(lib):
コード例 #14
0

def MoveParameterToGroup(doc, fparam, toGroup, name):
    isInstance = fparam.IsInstance
    defination = fparam.Definition
    eDef = GetSharedParameter(defination.Name)
    fparam = doc.FamilyManager.ReplaceParameter(fparam, name, toGroup,
                                                isInstance)
    doc.FamilyManager.ReplaceParameter(fparam, eDef, toGroup, isInstance)


need_params = IN[1]  # noqa
param_groups = IN[2]  # noqa
dir_path = IN[3]  # noqa

if Directory.Exists(dir_path):
    files = os.listdir(dir_path)
    files_rfa_path = filter(lambda x: x.endswith('.rfa'), files)
    families_path = []
    for f in files_rfa_path:
        if "000" not in f:
            families_path.append(f)

    report = []

    for path in families_path:
        filepath = os.path.join(dir_path, path)
        family_doc = app.OpenDocumentFile(filepath)
        paramList = [i for i in family_doc.FamilyManager.Parameters]

        filtered_params = []
コード例 #15
0
# parse the mode from the query string
if Request.QueryString.mode is not None:
    mode = int(Request.QueryString.mode)
else:
    mode = 0

# parse the path from the query string
if Request.QueryString.path is not None:
    vpath = VPATH(Request.QueryString.path)
    if not vpath.underRoot():
        raise HttpException('invalid path - not in the handler scope')
else:
    vpath = VPATH.root()

ppath = vpath.physicalPath()
isFolder = Directory.Exists(ppath)
if not isFolder and not File.Exists(ppath):
    raise HttpException('invalid path - not found')

# perform the action depending on the mode
if mode > 0:
    # response is an image
    if mode == PreviewImageMode:
        imageResponse = GetPicture(ppath).DrawResizedImage(PreviewSize)
    elif mode == ThumbnailImageMode:
        if isFolder: imageResponse = GetFolder(ppath).thumbnail()
        else:        imageResponse = GetPicture(ppath).thumbnail()
    elif mode == ParentThumbnailImageMode:
        imageResponse = GetFolder(ppath).parentThumbnail()
    
    # output the image in Page_Unload event        
コード例 #16
0
ファイル: runworkbook.py プロジェクト: masroore/resolver
import clr
import sys

from System.IO import Directory, Path

x86path = r'C:\Program Files\Resolver One\bin'
x64path = r'C:\Program Files (x86)\Resolver One\bin'

if Directory.Exists(x86path):
    topLevel = Path.GetDirectoryName(x86path)
    bin = x86path
else:
    topLevel = Path.GetDirectoryName(x64path)
    bin = x64path

Directory.SetCurrentDirectory(topLevel)
sys.path.extend((topLevel, bin))

# This adds references to all .NET assemblies
# that Resolver One spreadsheets use
clr.AddReference('TopLevel')
import LoadAssemblies
LoadAssemblies.binDir = bin
import LoadRequiredAssemblies

# Needed to configure caches
from MarketData import Bloomberg, Thomson

from Library.Workbook import Workbook
from Library.ContextDependent import MakeContextDependentFunctions
コード例 #17
0
 def CreateTestModeFolder(self):
     if not str.IsNullOrWhiteSpace(self.TestModeFolderPath):
         Directory.CreateDirectory(self.TestModeFolderPath)
     if not Directory.Exists(self.TestModeFolderPath):
         raise Exception("ERROR: failed to create the test mode folder!")
     return
コード例 #18
0
print "\tToolset: " + toolset
print "\tProject file: " + buildFile
print "\tTasks: " + tasks
print "\tConfiguration: " + configuration
print "\tPlatform: " + platform
print "\tDisable PostBuildEvent: " + str(DISABLE_POST_BUILD_EVENT)

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 + '"',
コード例 #19
0
from System.IO import Directory, SearchOption
dir = IN[0]
searchstring = IN[1]
if Directory.Exists(dir):
    OUT = Directory.GetFiles(dir, searchstring, SearchOption.AllDirectories)
else:
    OUT = list()
コード例 #20
0
ファイル: Settings.py プロジェクト: soracoder/Apricot
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)
コード例 #21
0
def deleteDirectory(directory):
    if Directory.Exists(directory):
        Directory.Delete(directory, True)
コード例 #22
0
ファイル: Settings.py プロジェクト: soracoder/Apricot
 def onClick(sender, args):
     if Directory.Exists(childMenuItem.Tag):
         for fileName in Directory.EnumerateFiles(childMenuItem.Tag):
             File.Delete(fileName)
コード例 #23
0
# create list of images to be processed
imglist = []

for file in Directory.GetFiles(sourcefolder, itype):
    imglist.append(file)

# create the required dict with the correct key and value
# the required value here: list of the input images
input_images = {'list_input_images': imglist}

# define the savepath
savepath = Path.Combine(sourcefolder, '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_kernel_size': 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,
    inputs=input_images,
    parameters=my_parameters,
    storagePath=savepath)
コード例 #24
0
    def ParseImages(self, weekname, data):
        """
		This is where the images are downloaded from the rss feed
		
		Variables:
			weekname is the name of the week to scrape
			data should be the data table to add to
		"""
        print "Starting to find images"

        #Fetched rss feed entrys are stored in the imageRssDownloaded with a key of the url
        for rss in self.imageRssList:
            imgItems = self.rssCache[rss]
            for imgItem in imgItems:
                Application.DoEvents()

                try:
                    if re.search(
                            "\d*/\d*/\d*",
                            imgItem['title'].InnerText).group(0) == weekname:

                        #Load rss into htmldocument for ease of navigation

                        htdoc = HtmlAgilityPack.HtmlDocument()
                        htdoc.LoadHtml(imgItem['description'].InnerText)
                        imgTags = htdoc.DocumentNode.SelectNodes(
                            "table/tr/td/a/img")

                        for tag in imgTags:
                            Application.DoEvents()

                            imgTitle = tag.GetAttributeValue("title", None)

                            imgSrc = tag.GetAttributeValue("src", None)

                            #If we have both and title and src. No point in doing all this if there is no src or title
                            if imgTitle and imgSrc:

                                #find rows that have a simular title.
                                #NOTE: replace occurences of ' with '' to avoid errors
                                imgRows = data.Select(
                                    "Title LIKE '%" +
                                    imgTitle.replace("'", "''") + "%'")

                                for imgRow in imgRows:
                                    Application.DoEvents()
                                    try:
                                        #Create the imagedownloaded
                                        imgDownloader = System.Net.WebClient()

                                        #Replace illegal charachers in the file name
                                        imgFileName = re.sub(
                                            '[\\\\<>\|:"\*/\?]', "", imgTitle)
                                        imgdirname = re.sub(
                                            '[\\\\<>\|:"\*/\?]', "", weekname)

                                        #Make sure the directory is not already there
                                        if not Directory.Exists(localdir +
                                                                imgdirname):
                                            Directory.CreateDirectory(
                                                localdir + imgdirname)

                                        #In the case of varients and other duplicates. This fixes an bug in 0.5
                                        if not File.Exists(localdir +
                                                           imgdirname + "\\" +
                                                           imgFileName +
                                                           ".jpg"):
                                            imgDownloader.DownloadFile(
                                                imgSrc, localdir + imgdirname +
                                                "\\" + imgFileName + ".jpg")

                                        #Now set the image column to the path of the image. Note that this is already set to a blank string when the list was first downloaded.
                                        imgRow[
                                            "Image"] = localdir + imgdirname + "\\" + imgFileName + ".jpg"
                                    except Exception, ex:
                                        print "Error 1"
                                        print str(ex)
                except Exception, ex:
                    print "Error 2"
                    print ex
コード例 #25
0
ファイル: Create_Z_stack.py プロジェクト: yoser-alrawi/OAD
window = ZenWindow()
Images = Zen.Application.Environment.GetFolderPath(ZenSpecialFolder.Images)
window.Initialize('Create Z stack from czi files')
window.AddFolderBrowser('sourcefolder','Source folder                   ',)
window.AddFolderBrowser('destfolder','Destination folder            ',)

## do setup
result=window.Show()
## check, if Cancel button was clicked
if result.HasCanceled == True:
    sys.exit('Macro aborted with Cancel!')
## get string name of source folder/destination folder
strFolder = str(result.GetValue('sourcefolder'))
newstrFolder = str(result.GetValue('destfolder'))
## Check, if path exists
if (Directory.Exists(strFolder)== False):
    strMessage = 'Path: ' + strFolder + ' does not exist!\nRestart macro and select an existing path!'
    sys.exit(strMessage)
## Check, if newPath exists
if (Directory.Exists(newstrFolder)== False):
    strMessage = 'Path: ' + newstrFolder + ' does not exist!\nRestart macro and select an existing path!'
    sys.exit(strMessage)

imgSeries = ZenImage()

t = 0
c = 0
z = 0

files = Directory.GetFiles(strFolder, "*czi")
コード例 #26
0
imagefiles = []

if not segactiveimg:
    # get list with all existing images and a short version of that list
    imagefiles = Directory.GetFiles(sourcefolder, fileext)

    if is_empty(imagefiles):
        # in case the folder contains no images with specified extension
        message = 'No images found in specified folder: '
        print(message, sourcefolder)
        raise SystemExit

    # check for existing subfolder inside source folder
    seg_subfolder = Path.Combine(sourcefolder, 'Seg')

    if Directory.Exists(seg_subfolder):
        if len(Directory.GetFiles(seg_subfolder)) != 0:
            # subfolder exist and is not empty - stop here
            message = 'Subfolder already exits and is not empty. Stopping Execution.'
            print(message, sourcefolder)
            raise SystemExit
        if len(Directory.GetFiles(seg_subfolder)) == 0:
            print(
                'Subfolder already exists but is empty. Proceed with Segmentation.'
            )

    if not Directory.Exists(seg_subfolder):
        # subfolder does not exist - create one
        Directory.CreateDirectory(seg_subfolder)
        print('Created subfolder for segmentation results : ', seg_subfolder)
コード例 #27
0
ファイル: env_indigo.py プロジェクト: uleming/Indigo
def dir_exists(path_):
    if sys.platform == 'cli' and os.name != 'nt':
        return Directory.Exists(path_)
    else:
        return os.path.isdir(path_)
コード例 #28
0
categories = IN[0]
if not isinstance(categories, list):
    categories = [categories]
saveBool = IN[1]
outList = []

collector = FilteredElementCollector(doc).OfClass(Family)
for category in categories:
    elements = []
    for family in collector:
        if family.FamilyCategoryId.ToString() == category.Id.ToString():
            elements.append(family)

    famDirectory = docPath + category.Name + "\\"
    if saveBool:
        if not Directory.Exists(famDirectory):
            Directory.CreateDirectory(famDirectory)

    for element in elements:
        eName = element.Name
        famPath = famDirectory + eName + ".rfa"
        famPathBackup = famDirectory + eName + ".0001.rfa"
        if saveBool:
            try:
                if not Directory.Exists(famDirectory):
                    Directory.CreateDirectory(famDirectory)
            except:
                outList.append("Could not create directory")
            try:
                if File.Exists(famPath):
                    File.Delete(famPath)
コード例 #29
0
def DirectoryExists(folderPath):
    return Directory.Exists(folderPath)
コード例 #30
0
                        if srt_subnode.Name == material.Name:
                            srt.Export(Path.Combine(path, srt.Name + ".srt0"))
                            break
                
                # only once
                break

if BrawlAPI.RootNode != None:

    # prompt for preset name
    preset = BrawlAPI.UserStringInput("New Preset Name", "")
    if preset != None:

        # check if preset already exists
        path = Path.Combine(BrawlAPI.PluginPath, "MKWii Animations", preset)
        if not Directory.Exists(path):

            # prompt for target material
            target = BrawlAPI.UserStringInput("Target Material", "")
            if target != None:

                textures = []
                export_animations()

                # edit and include import and delete script to preset folder
                import_script = File.ReadAllText(Path.Combine(BrawlAPI.PluginPath, "MKWii Animations", "Import Preset.txt"))
                import_script = import_script.Replace("preset_name = \"\"", "preset_name = \"" + preset + "\"")

                delete_script = File.ReadAllText(Path.Combine(BrawlAPI.PluginPath, "MKWii Animations", "Remove Preset.txt"))
                delete_script = delete_script.Replace("preset_name = \"\"", "preset_name = \"" + preset + "\"")