Exemplo n.º 1
0
def writeToFile(text):

    line = '\n This is %s' % (text) + '\n'
    fstream = F.FileWriter(filename, 1)
    out = F.BufferedWriter(fstream)
    out.newLine()
    out.write(line)
    out.close()
Exemplo n.º 2
0
def writeToFile(text):

    line = (strftime("[%Y.%m.%d  %H:%M:%S] ")) + (text) + '\n'
    fstream = F.FileWriter(filename, 1)
    out = F.BufferedWriter(fstream)
    out.newLine()
    out.write(line)
    out.close()
Exemplo n.º 3
0
    def saveAs(self):
        try:
            self.chooser.setCurrentDirectory(self.defaultPath)
            text = self.gui.editor.getText()
            self.chooser.setApproveButtonText("Save File")

            returnVal = self.chooser.showSaveDialog(self.gui)
            if returnVal == 0:  #User has chosen a file, so now it can be saved
                #DNR
                #file = open(self.chooser.getSelectedFile().getPath(),'w+')
                #self.gui.setFileName(self.chooser.getSelectedFile().getName())
                #text = text.splitlines(1)
                #file.writelines(text)
                #self.filename = file.name
                #file.close()
                #Commented out by AW: Trying to see if using java instead of jython
                #gets rid of the newline errors

                filePath = self.chooser.getSelectedFile().getPath()
                self.filename = os.path.normpath(filePath)

                fileWriter = io.FileWriter(filePath, 0)
                fileWriter.write(text)
                fileWriter.close()

                self.defaultPath = self.chooser.getCurrentDirectory()
                self.gui.editor.modified = 0
                self.gui.setFileName(os.path.basename(self.filename))
                self.logBuffer.saveLogFile(self.filename)

                #Now write the backup
                if JESConfig.getInstance().getBooleanProperty(
                        JESConfig.CONFIG_BACKUPSAVE):
                    backupPath = filePath + "bak"
                    fileWriter = io.FileWriter(backupPath, 0)
                    fileWriter.write(text)
                    fileWriter.close()

            return 1

        except lang.Exception, e:
            #TODO - fix
            #Error handling for saveAs
            e.printStackTrace()
            return 0
Exemplo n.º 4
0
    def saveFile(self):
        try:
            if self.filename != '':
                text = self.gui.editor.getText()
                #self.chooser.setCurrentDirectory(self.defaultPath)
                #file = open(self.chooser.getSelectedFile().getPath(),'w+')
                #David - testing something out
                #text = text.splitlines(1)
                #file.writelines(text)
                #self.filename = file.name
                #file.close()
                #Commented out by AW: Trying to see if using java instead of jython
                #gets rid of the newline errors

                filePath = self.chooser.getSelectedFile().getPath()
                self.filename = os.path.normpath(filePath)

                fileWriter = io.FileWriter(filePath, 0)
                fileWriter.write(text)
                fileWriter.close()

                self.defaultPath = self.chooser.getCurrentDirectory()
                self.logBuffer.saveLogFile(self.filename)
                self.gui.editor.modified = 0
                self.gui.setFileName(os.path.basename(self.filename))

                #Now write the backup
                if JESConfig.getInstance().getBooleanProperty(
                        JESConfig.CONFIG_BACKUPSAVE):
                    backupPath = filePath + "bak"
                    fileWriter = io.FileWriter(backupPath, 0)
                    fileWriter.write(text)
                    fileWriter.close()
                return 1
            else:
                return self.saveAs()
        except:
            #Error handling for saveFile
            return self.saveAs()
Exemplo n.º 5
0
username = '******'
password = '******'

# tiene que ser URL de algun Managed Server
URL = 't3://127.0.0.1:7001'

outputDir = '/Users/German/tmp'

# get the date to add to the file name
from datetime import date
today = date.today()
filedate = today.isoformat()

# libraries output saved to this file
libraryOutputFile = outputDir + "/" + "libraries-in-wls-" + filedate + ".txt"
libraryOutputFileWriter = javaio.FileWriter(libraryOutputFile)

# applications output saved to this file
appOutputFile = outputDir + "/" + "app-deployments-in-wls-" + filedate + ".txt"
appOutputFileWriter = javaio.FileWriter(appOutputFile)
"""
---------------------------------------------------------------------
Function to find the libraries
---------------------------------------------------------------------
"""


def getLibraryListing(mbeanPosition):
    cd(mbeanPosition)
    libraryListing = ls('c', returnMap='true')
    print(libraryListing.size())
Exemplo n.º 6
0
def base(det, e0, withPoisson, nTraj, dose, sf, bf, name, buildSample, buildParams, xtraParams):
   """base(det, e0, withPoisson, nTraj, dose, sf, bf, name, buildSample, buildParams) represents \
   a generic mechanism for Monte Carlo simulation of x-ray spectra.  The argument buildSample \
   is a method buildSample(monte,origin,buildParams) taking an instance of MonteCarloSS, the \
   position of the origin and a dictionary of build parameters.  This method should construct \
   the sample geometry.  The other arguments are the detector, the beam energy (keV), whether \
   to add Poisson noise, the number of electron trajectories to simulate, whether to simulate \
   characteristic secondary fluorescence and Bremsstrahlung secondary fluorescence, the name \
   to assign to the resulting spectrum."""
   if e0 < 0.1:
       raise "The beam energy must be larger than 0.1 keV."
   if nTraj < 1:
       raise "The number of electron trajectories must be larger than or equal to 1."
   if dose <= 0.0:
       raise "The electron dose must be larger than zero."
   name = name.strip()
   if xtraParams.has_key("Postfix"):
      name = "%s - %s" % (name, xtraParams["Postfix"])
   # Place the sample at the optimal location for the detector
   origin = epq.SpectrumUtils.getSamplePosition(det.getProperties())
   # Create a simulator and initialize it
   monte = nm.MonteCarloSS()
   if xtraParams.has_key("Gun"):
      gun = xtraParams["Gun"]
      gun.setCenter([0.0, 0.0, -0.099])
      monte.setElectronGun(gun)
   if xtraParams.has_key("PosX"):
      beamX  = xtraParams["PosX"]
      beamY  = xtraParams["PosY"]
      beamZ  = xtraParams["PosZ"]
      beamNM = xtraParams["nmSize"]
      beam=nm.GaussianBeam(beamNM*1.0e-9)
      beam.setCenter([beamX, beamY, beamZ]) 
      monte.setElectronGun(beam)
   chamber = monte.getChamber()
   if xtraParams.has_key("VP"):
       pathLength, gas = xtraParams["VP"]
       dim = 0.5 * nm.MonteCarloSS.ChamberRadius;
       dims = epu.Math2.plus(epu.Math2.v3(dim, dim, dim), epu.Math2.z3(2.0 * pathLength))
       pt = epu.Math2.plus(origin, epu.Math2.z3(0.5 * dim));
       shape = nm.MultiPlaneShape.createBlock(dims, pt, 0.0, 0.0, 0.0);
       msm = nm.BasicMaterialModel(gas);
       chamber = monte.addSubRegion(chamber, msm, shape);
   monte.setBeamEnergy(epq.ToSI.keV(e0))
   buildSample(monte, chamber, origin, buildParams)
   # Add event listeners to model characteristic radiation
   chXR = nm3.CharacteristicXRayGeneration3.create(monte)
   xrel = nm3.XRayTransport3.create(monte, det, chXR)
   brXR = nm3.BremsstrahlungXRayGeneration3.create(monte)
   brem = nm3.XRayTransport3.create(monte, det, brXR)
   chSF, brSF, bremFluor, charFluor  = None, None, None, None
   hasCharAcc = xtraParams.has_key('Characteristic Accumulator') and xtraParams['Characteristic Accumulator']
   if sf or hasCharAcc or xtraParams.has_key("Compton"):
      charFluor = nm3.FluorescenceXRayGeneration3.create(monte, chXR)
      if xtraParams.has_key("Compton"):
         charFluor.setIncludeCompton(True)
      chSF = nm3.XRayTransport3.create(monte, det, charFluor)
   hasBremFluorAcc = xtraParams.has_key('Brem Fluor Accumulator') and xtraParams['Brem Fluor Accumulator']
   if bf or hasBremFluorAcc:    
      bremFluor = nm3.FluorescenceXRayGeneration3.create(monte, brXR)       
      brSF = nm3.XRayTransport3.create(monte, det, bremFluor)
   hasTrans = xtraParams.has_key("Transitions")
   if hasTrans:
       if xtraParams.has_key("Emission Images"):
           eis = []
           dim = xtraParams["Emission Images"]
           for xrt in xtraParams["Transitions"]:
               size = xtraParams["Emission Size"]
               ei = nm3.EmissionImage3(size, size, xrt)
               xrel.addXRayListener(ei)
               if chSF:
                   chSF.addXRayListener(ei)
               if brSF:
                   brSF.addXRayListener(ei)
               ei.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim)
               ei.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim)
               eis.append(ei)
       if hasCharAcc:
           cxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Characteristic", dose * 1.0e-9)
           xrel.addXRayListener(cxra)
       hasCharFluorAcc = xtraParams.has_key('Char Fluor Accumulator') and xtraParams['Char Fluor Accumulator']
       if hasCharFluorAcc or chSF or sf:
           cfxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Characteristic Fluorescence", dose * 1.0e-9)
           chSF.addXRayListener(cfxra) 
       if hasBremFluorAcc or brSF or bf:
           bfxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Continuum Fluorescence", dose * 1.0e-9)
           brSF.addXRayListener(bfxra)
   contImgs = []
   if xtraParams.has_key('Continuum Images'):
       dim = xtraParams['Continuum Images']
       size = xtraParams['Continuum Size']
       energies = xtraParams['Continuum Energies']
       for eMin, eMax in energies:
           ci3 = nm3.ContinuumImage3(size, size, epq.ToSI.keV(eMin), epq.ToSI.keV(eMax))
           ci3.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim)
           ci3.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim)
           brem.addXRayListener(ci3)
           contImgs.append(ci3)
   doPRZ = xtraParams.has_key("PhiRhoZ")
   if doPRZ:
      depth = xtraParams["PhiRhoZ"]
      prz = nm3.PhiRhoZ3(xrel, origin[2] - 0.1 * depth, origin[2] + 1.1 * depth, 110)
      xrel.addXRayListener(prz)
   voxelated = xtraParams.has_key('Voxelated')
   vox = None
   if voxelated:
      dim = xtraParams['Voxelated']
      gen = xtraParams['GeneratedV']
      size = xtraParams['SizeV']
      vox = nm3.VoxelatedDetector((origin[0], origin[1], origin[2] - 0.1 * size), (size, size, size), (dim, dim, dim), gen)
      xrel.addXRayListener(vox)
   doTraj = xtraParams.has_key('Trajectories')
   if doTraj:
      dim = xtraParams['Trajectories']
      size = xtraParams['TrajSize']
      ti = nm.TrajectoryImage(size, size, dim)
      ti.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim)
      ti.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim)
      monte.addActionListener(ti)
   defOut = (dtsa2.DefaultOutput if dtsa2.DefaultOutput else dtsa2.reportPath())
   do = ("%s\\%s" % (xtraParams["Output"], dtsa2.normalizeFilename(name)) if xtraParams.has_key("Output") else "%s/%s" % (defOut, dtsa2.normalizeFilename(name)))
   do = do.replace("\\", "/")
   fdo = jio.File(do)
   fdo.mkdirs()
   doVRML = xtraParams.has_key('VRML')
   vrmlWr = None
   if doVRML:
      vrmlFile = jio.File.createTempFile("vrml", ".wrl", fdo)
      print "VRML in " + str(vrmlFile)
      vrmlWr = jio.FileWriter(vrmlFile)
      vrml = nm.TrajectoryVRML(monte, vrmlWr)
      vrml.setDisplayBackscatter(False)
      vrml.setDisplayXRayEvent(True)
      vrml.setMaxTrajectories(xtraParams['VRML'])
      vrml.setTrajectoryWidth(1.0e-9)
      vrml.setMaxRadius(1.0)
      vrml.setEmissive(True)
      vrml.addView("Y-Axis", epu.Math2.plus(origin, (0.0, 5.0e-6, 0.0)), origin)
      vrml.addView("Gun", epu.Math2.plus(origin, (0.0, 0.0, -5.0e-6)), origin)
      vrml.addView("X-Axis", epu.Math2.plus(origin, (-5.0e-6, 0.0, 0.0)), origin)
      vrml.renderSample()
      monte.addActionListener(vrml)
   scatter = None
   if xtraParams.has_key("Scatter"):
      scatter = nm.ScatterStats(epq.ToSI.eV(50.0))
      monte.addActionListener(scatter)
   # Reset the detector and run the electrons
   det.reset()
   monte.runMultipleTrajectories(nTraj)
   # Get the spectrum and assign properties
   spec = det.getSpectrum((dose * 1.0e-9) / (nTraj * epq.PhysicalConstants.ElectronCharge))
   props = spec.getProperties()
   props.setNumericProperty(epq.SpectrumProperties.LiveTime, dose)
   props.setNumericProperty(epq.SpectrumProperties.FaradayBegin, 1.0)
   props.setNumericProperty(epq.SpectrumProperties.BeamEnergy, e0)
   epq.SpectrumUtils.rename(spec, name)
   if withPoisson:
      spec = epq.SpectrumUtils.addNoiseToSpectrum(spec, 1.0)
   printAcc = xtraParams.has_key('Print Accumulators') and xtraParams['Print Accumulators']
   if printAcc:
      sw0 = jio.StringWriter()
      sw = jio.PrintWriter(sw0)
   if hasTrans or scatter:
      pw = None
      if hasCharAcc or (hasBremFluorAcc and bf) or (hasCharFluorAcc and sf) or scatter:
         jio.File(do).mkdirs()
         pw = jio.PrintWriter("%s/Intensity.csv" % do)
         pw.println(name)
      if hasCharAcc:
         pw.println("Characteristic") 
         cxra.dump(pw)
         if printAcc:
             sw.println("Characteristic") 
             cxra.dump(sw)
      if hasBremFluorAcc and brSF and bf:
         pw.println("Bremsstrahlung Fluorescence")
         bfxra.dump(pw)
         if printAcc:
             sw.println("Bremsstrahlung Fluorescence") 
             bfxra.dump(sw)
      if hasCharFluorAcc and chSF and sf:
         pw.println("Characteristic Fluorescence")
         cfxra.dump(pw)
         if printAcc:
             sw.println("Characteristic Fluorescence")
             cfxra.dump(sw)
      if printAcc:
          print sw0.toString()
          sw.close()
          sw0.close()
      if scatter:
         scatter.header(pw)
         scatter.dump(pw)
      if pw:
         pw.close()
      imgs = []
      if xtraParams.has_key("Emission Images"):
         nm3.EmissionImageBase.scaleEmissionImages(eis)
         print eis
         print do          
         nm3.EmissionImage3.dumpToFiles(eis, do)
         print u"Writing emission images to %s" % do
         imgs.extend(eis)
      if xtraParams.has_key("Continuum Images"):
         imgs.extend(contImgs)      
         nm3.EmissionImageBase.scaleEmissionImages(imgs)
         print contImgs
         print do          
         nm3.ContinuumImage3.dumpToFiles(contImgs, do)
         print u"Writing continuum images to %s" % do
   if doPRZ:
       jio.File(do).mkdirs()
       pw = jio.PrintWriter(u"%s/PhiRhoZ.csv" % do)
       prz.write(pw)
       pw.close()
       print u"Writing emission images to %s" % do
   if doTraj:
      ti.dumpToFile(do)
      print u"Writing trajectory images to %s" % do
   if vrmlWr:
       vrmlWr.close()
   if vox:
      jio.File(do).mkdirs()
      objs = list(vox.getAccumulatorObjects())
      xx = {}
      for obj in objs:
          iio.write(vox.createXZSum(400, obj), "png", jio.File(do, "Voxelated[XZ,Sum][%s].png" % obj))
          iio.write(vox.createXYSum(400, obj), "png", jio.File(do, "Voxelated[XY,Sum][%s].png" % obj))
          iio.write(vox.createXZView(400, obj), "png", jio.File(do, "Voxelated[XZ, Max][%s].png" % obj))
          iio.write(vox.createXYView(400, obj), "png", jio.File(do, "Voxelated[XY, Max][%s].png" % obj))
          vox.writeXZPlanar(400, obj, jio.File(do, "Voxilated[XZ,planar,%s].tif" % obj))
          vox.writeXYPlanar(400, obj, jio.File(do, "Voxilated[XY,planar,%s].tif" % obj))
          for f in (0.1, 0.5, 0.8, 0.9):
              iio.write(vox.createXZFraction(400, obj, f), "png", jio.File(do, "Voxelated[XZ,f=%g][%s].png" % (f, obj)))
          xx[obj] = vox.createRadialCDF(origin, obj)
      hdr = "Radius"
      for obj in objs:
          hdr = "%s\t%s" % (hdr, obj)
      print hdr
      first = xx[objs[0]]
      for i, (d, f) in enumerate(first):
          ln = "%g" % d
          for obj in objs:
              rcdf = xx[obj][i]
              ln = "%s\t%g" % (ln, rcdf[1])
          print ln
   #if bremFluor:
       #print "Stats[Scale] = %s" % bremFluor.getScaleStats()         
   return dtsa2.wrap(spec)
Exemplo n.º 7
0
def run(config):
    """Identifies Configuration Changes"""
    
    admin_name = config.getProperty('wls.admin.name')
    log.info("Admin server's name is '" + admin_name + "'")

    repodir = config.getProperty('ConfigNOW.home') + "/repository/" + config.getProperty('ConfigNOW.environment') + "/" + config.getProperty('ConfigNOW.configuration') + "/"

    # What is todays date
    date_today = datetime.now()
    current_config = str(date_today.year) + '-' + str(date_today.month) + '-' + str(date_today.day) 

    # This field may be a date or constant
    # Date previous sets an absolute previous date
    if config.getProperty('config.date_previous') is not None:
        base_config = config.getProperty('config.date_previous')
    
    # Date diff looks for the difference in dates
    if config.getProperty('config.date_diff') is not None:
        if config.getProperty('config.date_diff') is "previous" or "baseline":
            base_config = config.getProperty('config.date_diff')
        else:
            date_diff = int(config.getProperty('config.date_diff'))
            date_N_days_ago = datetime.now() - timedelta(days=date_diff)  
            base_config = str(date_N_days_ago.year) + '-' + str(date_N_days_ago.month) + '-' + str(date_N_days_ago.day)   


    __connectAdminServer(config)
    serverConfig()

    redirect(config.getProperty('java.io.tmpdir') ,'false')
    log.info("Walking the configuration tree, depending on the size of your instance this may take some time")
    walkTree('/',0)    
    redirect(config.getProperty('java.io.tmpdir') ,'true')

    output_content.sort()

    create_repo(repodir,current_config)

    # Output the findings from this pass
    if output_content is not None and len(output_content) > 0:
        outputfw=javaio.FileWriter(repodir + '/' + current_config + '/MBeans.txt') 
        for line in output_content :
            outputfw.write(line + "\r\n")       
        outputfw.close()
        
         # Also update the previous and baseline as appropiate
    if output_content is not None and len(output_content) > 0:
        # Also update the previous folder so that this is now counted as the previous run
        outputfw=javaio.FileWriter(repodir + '/previous/MBeans.txt') 
        for line in output_content :
            outputfw.write(line + "\r\n")       
        outputfw.close()

        # If there is no baseline file, write it now
    if os.path.isfile(repodir + 'baseline/MBeans.txt') is False:
        outputfw=javaio.FileWriter(repodir + 'baseline/MBeans.txt') 
        for line in output_content :
            outputfw.write(line + "\r\n")       
        outputfw.close()


    # Do the diff potentially against older releases
    diff(current_config, base_config, repodir, "ConfigChanges.html", config.getProperty('ConfigNOW.home') + "/repository/template/report.html", config.getProperty('ConfigNOW.environment'), config.getProperty('ConfigNOW.configuration'))
Exemplo n.º 8
0
def writeProject(idx, file):
    """writeQCProject(idx, file)
   Write the QC project with the specified index to the specified file."""
    wr = jio.FileWriter(file)
    d2.Database.writeQCProject(idx, wr)
    wr.close()
Exemplo n.º 9
0
"""
Check that a Writer can be assigned to sys.stdout.
"""

import support
from java import io
import sys

o = io.FileWriter("test004.out")
sys.stdout = o
print "spam",

f = open("test004.out", "r")
s = f.read(-1)
f.close()

if s != "spam":
    raise support.TestError('Wrong redirected stdout ' + ` s `)
Exemplo n.º 10
0
# To see the output printed to the console in Network Workbench, use the
# switch "-console" when opening Network Workbench from the command line.
from java import io

print "Here is the value you gave me when you ran the algorithm..."
print sample_attr

print "Here is what I got from CIShell (the graph you highlighted)"
print arg0
graph = arg0
edge_count = graph.getEdgeCount()

print "Here is the number of edges in the graph you provided..."
print edge_count

aFile = io.File("whatever.txt")
writer = io.BufferedWriter(io.FileWriter(aFile))
writer.write(str(edge_count))
writer.close()

print "I will now return the original graph, and the edge count in a file"

aFile = io.File("whatever.txt")
writer = io.BufferedWriter(io.FileWriter(aFile))
writer.write(str(edge_count))
writer.close()

result0 = arg0
result1 = aFile