New object inside loop condition

I would like to create new object inside loop condition and use in its body
while(new File(localization).exists()){
     //now would like use File object created above
}What's the notation for that?

YoungWinston wrote:
TheGreatEmperor wrote:
I would like to create new object inside loop condition and use in its body
while(new File(localization).exists()){
//now would like use File object created above
}What's the notation for that?Encephalopathic gave it to you, but I'd worry about ending up with a never-ending loop. What about
if ((myFile = new File(fileString)).exists()) { ...instead?
Winston1) Same thing I put (except change the name "f" with "myFile")
2) you could get a never-ending loop with your answer (depending on the body)
3) The previous answer by Encephalopathic would NOT give a never-ending loop unless there was a never-ending listing of files with the name:
"Foo" + fileCounter + ".txt"; where "fileCounter" is incrementing (as done in his code)

Similar Messages

  • JMM: legal to optimize non-volatile flag out of particular loop condition?

    Does Java Memory Model allow JIT compiler to optimize non-volatile flag out of loop conditions in code like as follows...
    class NonVolatileConditionInLoop {
      private int number;
      private boolean writingReady = true; // non-volatile, always handled inside synchronized block
      public synchronized void setNumber(int n) {
        while (!writingReady) { // non-volatile flag in loop condition
          try { wait(); }
          catch (InterruptedException e) { e.printStackTrace(); }
        this.number = n;
        this.writingReady = false;
        notifyAll();
      public synchronized int getNumber() {
        while (writingReady) { // non-volatile flag in loop condition
          try { wait(); }
          catch (InterruptedException e) { e.printStackTrace(); }
        this.writingReady = true;
        notifyAll();
        return number;
    }...so that it will execute like this:
    class NonVolatileConditionInLoopHacked {
      private int number;
      private boolean writingReady = true; // non-volatile, always handled inside synchronized block
      public synchronized void setNumber(int n) {
        if (!writingReady) { // moved out of loop condition
          while (true) {
            try { wait(); }
            catch (InterruptedException e) { e.printStackTrace(); }
        this.number = n;
        this.writingReady = false;
        notifyAll();
      public synchronized int getNumber() {
        if (writingReady) { // moved out of loop condition
          while (true) {
            try { wait(); }
            catch (InterruptedException e) { e.printStackTrace(); }
        this.writingReady = true;
        notifyAll();
        return number;
    This question was recently discussed in [one of threads|http://forums.sun.com/thread.jspa?messageID=11001801#11001801|thread] at New To Java forum.
    My take on it is that optimization like above is legal. From the perspective of single-threaded program, repeated checks for writingReady are redundant because it is not modified within the loop. As far as I understand, unless explicitly forced by volatile modifier (and in our case it is not), optimizing compiler "has a right" to optimize based on single-thread execution assumption.
    Opposite opinion is that JMM prohibits such an optimization because methods containing the loop(s) are synchronized.

    gnat wrote:
    ...so that it will execute like this:
    class NonVolatileConditionInLoopHacked {
    private int number;
    private boolean writingReady = true; // non-volatile, always handled inside synchronized block
    public synchronized void setNumber(int n) {
    if (!writingReady) { // moved out of loop condition
    while (true) {
    try { wait(); }
    catch (InterruptedException e) { e.printStackTrace(); }
    this.number = n;
    this.writingReady = false;
    notifyAll();
    public synchronized int getNumber() {
    if (writingReady) { // moved out of loop condition
    while (true) {
    try { wait(); }
    catch (InterruptedException e) { e.printStackTrace(); }
    this.writingReady = true;
    notifyAll();
    return number;
    This question was recently discussed in [one of threads|http://forums.sun.com/thread.jspa?messageID=11001801#11001801|thread] at New To Java forum.
    My take on it is that optimization like above is legal. From the perspective of single-threaded program, repeated checks for writingReady are redundant because it is not modified within the loop. As far as I understand, unless explicitly forced by volatile modifier (and in our case it is not), optimizing compiler "has a right" to optimize based on single-thread execution assumption.
    Opposite opinion is that JMM prohibits such an optimization because methods containing the loop(s) are synchronized.One of the problems with wait() and your the proposed optimization is that "interrupts and spurious wakeups are possible" from wait() . See [http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait()] Therefore your wait() would loop without checking if this optimization would occur and a interrupt or spurious wake-up happened. Therefore for this reason I do not believe writingReady would be rolled out of the loop. Also the code isn't even equivalent. Once all the threads wake-up due to the notifyAll() they would spin in the while(true) and wait() again. I don't think the JMM prohibits such an optimization because methods containing the loop(s) are synchronized, but because it contains a wait(). The wait() is kind of a temporary flow control escape out of the loop.
    Example:
    writingReady is true
    Thread A calls getNumber(). It waits().
    Thread B calls setNumber(). It calls notifyAll() and writingReady is now false;
    Thread A wakes up in getNumber() and while(true) loop and waits again(). //Big problem.

  • Endless loop condition

    Hi there,
    Working on a client/server chat application. On the client side app, everytime I want to send a message I create a new Thread called "SendingThread". See below.
    import java.io.*;
    import java.net.*;
    public class SendingThread extends Thread
      private Socket clientSocket;
      private String messageToSend;
      public SendingThread(Socket socket, String userName, String message)
           super("SendingThread: " + socket);
           clientSocket = socket;
           messageToSend = userName + Constants.MESSAGE_SEPERATOR + message;
      public void run()
           try
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                writer.println(messageToSend);
                writer.flush();
                writer.close();
           catch(IOException ioe)
                System.out.println("Server must have closed connection");
                ioe.printStackTrace();
    }As you can see the line writer.close() is important in regard to a Thread that is running on the server app called "ReceivingThread" (see below). In the ReceivingThread there is a line:
    if((temp = input.readLine()) != null)
    It blocks until I actually send a message to read in. This is expected. However, now I have a catch 22 situation. On the client side app, since I called writer.close(), this was necessary in order to get a null value during the readLine() call on the ReceivingThread on the server. The one line gets processed as expected. The stream is now closed and on the server side app, since this is true, the next iteration of the while loop attempts to read in another line but now it is alway null and thus I wind up with an endless loop condition. I introduced a "count" variable and a condition only so that the loop wouldn't get away too far. I was hoping it would block again, but it isn't. I believe the ReceivingThread is written correctly, but I need to somehow obtain a null value on the stream for message completion and also have the ReceivingThread block for the next message coming in.
    Please advise,
    Alan
    public class ReceivingThread extends Thread
      private BufferedReader input;
      private MessageListener messageListener;
      private boolean keepListening = true;
      public ReceivingThread(MessageListener listener, Socket clientSocket)
           super("ReceivingThread: " + clientSocket);
           messageListener = listener;
           try
                clientSocket.setSoTimeout(50000);
                input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
           catch(IOException ioe){ioe.printStackTrace();}
      public void run()
           StringBuffer messageBuffer = new StringBuffer();
           String temp = "";
           int messageCount = 0;
           int count = 0;
             //START:
             while(keepListening)
               while(true)
                  try
                    //In order to receive a null, the client app
                    //has to close the stream!  Otherwise, this
                    //will block indefinitely.
                    System.out.println("blocking...");
                    if((temp = input.readLine()) != null)
                       if(messageCount == 0)
                            messageBuffer.append(temp);
                            messageCount++;
                            System.out.println("temp: " + temp);
                       else
                         //When we use the readLine method, it strips
                         //off the newline character, so we need to
                         //put it back.
                         messageBuffer.append("\n" + temp);
                         System.out.println("temp: " + temp);
                    else
                         break;
                  catch(IOException ioe)
                       System.out.println("IOException...");
                       ioe.printStackTrace();
                       //break;
               }//end while
                //System.out.println("out of inner while loop...message:\n" + messageBuffer.toString());
                String message = messageBuffer.toString();
                System.out.println("message: " + message);
                StringTokenizer tokenizer = new StringTokenizer(message, Constants.MESSAGE_SEPERATOR);
                if(tokenizer.countTokens() == 2)
                     System.out.println("message received");
                     messageListener.messageReceived(tokenizer.nextToken(), tokenizer.nextToken());
                     //reset string variables
                     messageCount = 0;
                     temp = "";
                     messageBuffer.delete(0, messageBuffer.length());
                     message = "";
                else
                    //System.out.println("checking disconnect string: " + message);
                   if(message.equalsIgnoreCase(Constants.MESSAGE_SEPERATOR + Constants.DISCONNECT_STRING))
                          stopListening();
                count++;
                if(count > 3)break;
             }//end while
             try
               //System.out.println("closing ReceivingThread");
               input.close();        
             catch(IOException ioe){ioe.printStackTrace();}
      public void stopListening()
           keepListening = false;
    }Edited by: ashiers on Nov 21, 2007 7:33 AM
    Edited by: ashiers on Nov 21, 2007 7:34 AM

    I'm not quite sure what you want to happen here. Here is what I would expect from the code you posted:
    *1.* The client connects and sends its message to the server.
    *2.* The server iterates through the line-reading loop until it exhausts the input (input.readLine() == null) and breaks out of the while (true) loop. The "temp: foo" messages are written to standard output accordingly.
    *3.* The server reaches the message portion of the loop and writes the "message: foo" to standard output.
    *4.* The server hits the end of the "while (keepListening)" loop and (assuming that you didn't receive a disconnect message) keepListening is still true. So it loops back around.
    *5.* The first time through the while (true) loop, the input is still empty (of course). So you get a null.
    *6.* Next, you get a "message: foo" output.
    *7.* Repeat *4* through *6* until your computer hardware fails or you abort the program. (Except that you added that count thing, so it'll loop three times and then break.)
    What are you trying to make the "keepListening" loop do? It doesn't seem like it should be there at all. At no point does this reading thread get the opportunity to read from any other socket. It almost seems like you want to spawn one ReceivingThread for each Socket you receive from the ServerSocket; if that's the case, the main thread (or whichever thread you have running that code and spawning the ReceivingThreads should be inside of the while (keepListening) loop.
    Any help?

  • How to get the values of the objects inside an object??

    Hi,
    I am trying to write code to display name and memory usage of all session attributes, in a recursive way.
    I suppose reflection is needed here, but I can’t figure out how to get the values of the objects inside an object...
    private void handleIt(String attributeName, Object attributeValue) {
         boolean isPrimitiveOrNull = ((null == attributeValue) ||
              (attributeValue.getClass().isPrimitive()));                                         
         if (isPrimitiveOrNull) {
              sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "}");
         } else {
              sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "{");               
              Field[] fields = attributeValue.getClass().getDeclaredFields();
              int lim = fields.length;
              String name;
              Object value = null;
              for (int i = 0; i < lim; i++) {
                   name = fields.getName();
                   //LOOK AT THIS LINE: !!!!!!!!!!!!!!!!!!!!!!!!!!!
                   value = fields[i].get(obj); //I don´t know what 'obj' should be??
                   handleIt(name, value);
              sb.append("}");               
    Any suggestions will be greatly appreciated...

    I realized that massive int objects called MAX_VALUE, MIN_VALUE and SIZE where causing the StackOverflow, so I removed them from the analysis.
    This is the resultant code. But I think it isn’t accurate in calculating the real size of objects being got using reflexion.
    Do you or somebody have any more suggestions?
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.lang.reflect.Field;
    import java.util.Enumeration;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    public class SessionMeasurer extends HttpServlet {
         private static final long serialVersionUID = 1470488362727841992L;
         private StringBuilder sb = new StringBuilder();
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              performTask(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              performTask(request, response);
         public void performTask(HttpServletRequest request, HttpServletResponse response) {
              HttpSession     session = request.getSession(false);     
              String attributeName = "";
              Object attributeValue = null;
              for (Enumeration<?> attributeNames = session.getAttributeNames(); attributeNames.hasMoreElements();) {
                   attributeName = (String)attributeNames.nextElement();
                   attributeValue = session.getAttribute(attributeName);
                   handleIt(attributeName, attributeValue);               
              System.out.println(sb.toString());
         private void handleIt(String attributeName, Object attributeValue) {           
              if (attributeValue != null) {          
                   boolean isPrimitive = attributeValue.getClass().isPrimitive();
                   if (isPrimitive) {
                        sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "}");
                   } else {
                        sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "{");               
                        Field[] fields = attributeValue.getClass().getDeclaredFields();
                        String name;
                        Object value = null;
                        int lim = fields.length;
                        for (int i = 0; i < lim; i++) {
                             name = fields.getName();                                                                                                         
                             if (!name.endsWith("_VALUE") && !name.equals("SIZE") && !name.equals("serialVersionUID")) {
                                  try {
                                       value = fields[i].get(attributeValue);
                                  } catch(Exception e) {
                                       //PENDIENTE: Tratamiento excepción
                                  handleIt(name, value);
                        sb.append("}");               
         private int sizeOf(Object obj) {
              //Valid only for Serializables
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              ObjectOutputStream oos = null;     
              byte[] bytes = null;               
              try {          
                   oos = new ObjectOutputStream(baos);
                   oos.writeObject(obj);
                   bytes = baos.toByteArray();
              } catch(Exception e) {               
                   //PENDIENTE: Tratamiento excepción
              } finally {
                   if (oos != null) {
                        try {
                             oos.close();
                        } catch(Exception e) {
                             //PENDIENTE: Tratamiento excepción                         
                   if (baos != null) {
                        try {
                             baos.close();
                        } catch(Exception e) {
                             //PENDIENTE: Tratamiento excepción                         
              int size = -1;
              if (bytes != null) {
                   size = bytes.length;
              return size;          

  • Multiple SQL task objects inside a package object is not generating proper DTSX

    
    I am programmatically adding multiple ExecuteSQLtask objects inside a package. I am specifying all the required properties to the ExecuteSQLtask objects.  However, when I save the package object to dtsx, the package looses the properties of some
    of the ExecuteSQLtask object.
    In the below example, I have created 3 ExecuteSQL task objects using the function AddSqlTask. However, once you run it, one of the objects will loose its properties. What makes it more weird is the fact that sometimes, object 1 looses the properties,
    some times, its object number 2. Its random. I know that these objects are COM objects. Is there something I need to careful of when setting the properties ? Why are the values lost when I save them to DTSX ?
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Timers;
    using Microsoft.SqlServer.Dts.Runtime;
    using Microsoft.SqlServer.Dts.Runtime;
    using Microsoft.SqlServer.Dts.Tasks.FileSystemTask;
    using Microsoft.SqlServer.Dts.Tasks.BulkInsertTask;
    using Microsoft.SqlServer.Dts.Runtime;
    using Microsoft.SqlServer.Dts.Pipeline;
    using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
    using Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask;
    using Microsoft.SqlServer.Dts.Tasks.ExecutePackageTask;
    namespace PackageCreator
    class Program
    static void Main(string[] args)
    #region Package 1
    Package package1 = new Package();
    #region ConnectionString
    AddSqlConnection(
    package1,
    ConfigurationManager.AppSettings["ServerHostName"],
    ConfigurationManager.AppSettings["SqlServerDefaultDB"]
    #endregion
    AddSqlTask(package1, "P1 - Task1");
    AddSqlTask(package1, "P1 - Task2");
    AddSqlTask(package1, "P1 - TaskFinal");
    #region Add Dependencies
    package1.PrecedenceConstraints.Add(
    package1.Executables[0] as TaskHost,
    package1.Executables[1] as TaskHost
    package1.PrecedenceConstraints.Add(
    package1.Executables[1] as TaskHost,
    package1.Executables[2] as TaskHost
    #endregion
    #endregion
    #region Package 2
    Package package2 = new Package();
    #region ConnectionString
    AddSqlConnection(
    package2,
    ConfigurationManager.AppSettings["ServerHostName"],
    ConfigurationManager.AppSettings["SqlServerDefaultDB"]
    #endregion
    AddSqlTask(package2, "P2 - TaskFinal");
    #region ExecutePackageTaskClass
    Executable exec1 = package2.Executables.Add("STOCK:ExecutePackageTask");
    TaskHost th = exec1 as TaskHost;
    ExecutePackageTask myTask = th.InnerObject as ExecutePackageTask;
    myTask.PackageID = package1.ID;
    #endregion
    #region Add Dependencies
    package2.PrecedenceConstraints.Add(
    package2.Executables[0] as TaskHost,
    package2.Executables[1] as TaskHost
    #endregion
    #endregion
    //new Ispac(package1, package1.ID).DeployAndRun();
    SavePackage(package1);
    SavePackage(package2);
    var packageList = new List<Package>();
    packageList.Add(package1);
    packageList.Add(package2);
    new IspacPackageCollections(packageList).DeployAndRun();
    Console.Read();
    private static void AddSqlTask(Package package, string component)
    //Thread.Sleep(5000);
    package.Executables.Add("STOCK:SQLTask");
    ExecuteSQLTask executeSQLTask = (package.Executables[package.Executables.Count - 1]
    as TaskHost).InnerObject
    as ExecuteSQLTask;
    executeSQLTask.Connection = package.Connections[0].ID;
    executeSQLTask.SqlStatementSource = "insert into [dbo].[SupersetPackageDependencies] (Component) values ('" +
    component + @"')";
    private static void SavePackage(Package package)
    string packageNetworkLocation = @""
    + ConfigurationManager.AppSettings["packageNetworkLocation"]
    + @"\" + package.ID + ".dtsx";
    new Application().SaveToXml(
    packageNetworkLocation,
    package,
    null
    //new Application().SaveToSqlServer(
    // package,
    // null,
    // "ANUPN8470P",
    // null,
    // null
    #region AddConnectionManager
    private static ConnectionManager AddSqlConnection(Package package, string server, string database)
    return AddConnection(
    package,
    "OLEDB",
    String.Format(
    CultureInfo.InvariantCulture,
    "Provider=SQLOLEDB.1;Data Source={0};Persist Security Info=False;Initial Catalog={1};Integrated Security=SSPI;",
    server,
    database)
    private static ConnectionManager AddConnection(Package package, string type, string connectionString)
    ConnectionManager manager = package.Connections.Add(type);
    manager.ConnectionString = connectionString;
    manager.Name = String.Format(
    CultureInfo.InvariantCulture,
    "{0} Connection",
    type);
    return manager;
    #endregion
    public static void AddExecuteSqlTask(
    Package _package,
    string _componentId
    _package.Executables.Add("STOCK:SQLTask");
    // Get the task host wrapper
    ExecuteSQLTask executeSQLTask = (_package.Executables[_package.Executables.Count - 1]
    as TaskHost).InnerObject
    as ExecuteSQLTask;
    #region Set required properties
    executeSQLTask.Connection = _package.Connections[0].ID;
    executeSQLTask.SqlStatementSource = "insert into [dbo].[SupersetPackageDependencies] (Component) values ('" +
    _componentId + @"')";
    #endregion
    //return executeSQLTask;

    Why you do not tell what properties get lost?
    And why is the same get repeated (you want parallel?):
    package1.Executables[0] as TaskHost,
    package1.Executables[1] as TaskHost
    package1.PrecedenceConstraints.Add(
    package1.Executables[1] as TaskHost,
    package1.Executables[1]
    And why not to add them
    like
    package1.PrecedenceConstraints.Add(
    package1.Executables[0] as TaskHost);,
    package1.PrecedenceConstraints.Add( package1.Executables[1] as TaskHost
    Arthur
    MyBlog
    Twitter

  • Problem in reading an object inside another obj in C thru JNI

    Hi All,
    I am passing a java class object from Jave to C thru JNI.
    This object has many integer fields + one object of another class, which also has some fields.
    I am able to read integer fields from C but not able to read fields inside another object.
    Can anyone plz help me in reading the object inside another object from C.
    I m pasting class here for better understanding :
    public class ImageMergeInformation {
    public ImageInformation outputImageInfo;
    public ImageInformation[] inputImageInfo = new ImageInformation[8];
    public int topMargin;
    public int bottomMargin;
    I wanna read ImageInformation obj.
    Plz help me...
    Thanks in Advance,
    Regards,
    Sneha

    You have to get the field id (getFieldID) of the variable you want, e.g. outputImageInfo, then get the object (getObjectField) in that field. At this point, you can start over (get the class, get the field id, get the object).

  • Design and registration of new objects

    We have the following three objects:
    - Order, which contains:
    -- OrderStatus
    -- Vector: OrderStatusHistoryItem
    Whenever order.setStatus(newStatus) is called we would like to create a new OrderStatusHistoryItem and add that to the vector of history inside the Order.
    Our first guess was to put this in the setStatus method of the Order object, so that noone would bypass the adding to history. But... When creating the OrderStatusHistoryItem inside the Order we of course get an error from TopLink, saying that the object was not registered in the UOW.
    Is there some way that we can tell TopLink that this relationship should be registered automatically on commit? If not, what would be the best way to design this? Of course we do not want to expose our domain layer to the internals of TopLink. Would a factory be the best way to handle registration upon creation?
    Thanks,
    Anders,

    Anders,
    New objects created and attached to working copies will be discovered during commit cycle and added to the persistent model including the appropriate INSERT. The only issue you will have is that you must make sure that setStatus(newStatus) is ONLY called on working copies read from or registered with a UnitOfWork. If this is true you should be able to create the new OrderStatusHistoryItem within the setStatus method and add it to the collection without registering it in the UnitOfWork.
    Doug

  • Dynamic Variables and New-Object - in a GUI

    so, i have not found anything that i can parlay into a solution for what i am attempting to do.  
    Basically i am using powershell to build a GUI to manage websites on various servers.  
    in a nutshell:
    - i have an array with the servers i want to query
    - a foreach loop gets me the site names for each server (number of sites can vary on a server).
    - need put checkboxes on a GUI for every site to do something (25-30 sites across 8 servers).
    currently i am passing the $dir.name variable to a function that will create the new variable using this command:
    $pName = $dir.name New-variable -name $pName -value (New-Object System.Windows.Forms.CheckBox)
    $pName.Location -value (New-Object System.Drawing.Size(10,$i))
    $pName.Size -value (New-Object System.Drawing.Size(100,20))
    $Pname.Text -value $dir.name
    $groupBox.Controls.Add($pName) 
    Problem is i am not able to do anything with my newly created variable.  I am trying to use the following code to position the new checkbox but i get nothing (same for text, size, etc.)  I am not seeing any errors, so i don't know what i have going
    wrong.  
    is this even possible?
    I am able to create static checkboxes, and i can create dynamic variables.  But i can't mix the two...

    Here is how we normally use listboxes to handle form situations like this one.  The listboxes can automatically select subgroups.
    The hash of arrays can be loaded very easily with a script or the results of the first list can be used to lookup and set the contents of the second.
    Notice how little code is actually used.  This is all of the setup code needed aside from the from definition:
    $FormEvent_Load={
    $global:serversToSites=@{
    Server1=@('S1_SITE1','S1_SITE2','S1_SITE3')
    Server2=@('S2_SITE1','S2_SITE2','S2_SITE3')
    Server3=@('S3_SITE1','S3_SITE2','S3_SITE3')
    $listbox1.Items.AddRange($serversToSites.Keys)
    $listbox1_SelectedIndexChanged={
    $listbox2.Items.Clear()
    $listbox2.Items.AddRange($global:serversToSites[$listbox1.SelectedItem])
    $listbox2_SelectedIndexChanged={
    [void][System.Windows.Forms.MessageBox]::Show($listbox2.SelectedItem,'You Selected Site')
    Here is the complete demo form:
    [void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    [void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $listbox2 = New-Object 'System.Windows.Forms.ListBox'
    $listbox1 = New-Object 'System.Windows.Forms.ListBox'
    $buttonOK = New-Object 'System.Windows.Forms.Button'
    $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    $FormEvent_Load={
    $global:serversToSites=@{
    Server1=@('S1_SITE1','S1_SITE2','S1_SITE3')
    Server2=@('S2_SITE1','S2_SITE2','S2_SITE3')
    Server3=@('S3_SITE1','S3_SITE2','S3_SITE3')
    $listbox1.Items.AddRange($serversToSites.Keys)
    $listbox1_SelectedIndexChanged={
    $listbox2.Items.Clear()
    $listbox2.Items.AddRange($global:serversToSites[$listbox1.SelectedItem])
    $listbox2_SelectedIndexChanged={
    [void][System.Windows.Forms.MessageBox]::Show($listbox2.SelectedItem,'You Selected Site')
    $Form_StateCorrection_Load=
    #Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState
    $form1.Controls.Add($listbox2)
    $form1.Controls.Add($listbox1)
    $form1.Controls.Add($buttonOK)
    $form1.AcceptButton = $buttonOK
    $form1.ClientSize = '439, 262'
    $form1.FormBorderStyle = 'FixedDialog'
    $form1.MaximizeBox = $False
    $form1.MinimizeBox = $False
    $form1.Name = "form1"
    $form1.StartPosition = 'CenterScreen'
    $form1.Text = "Form"
    $form1.add_Load($FormEvent_Load)
    # listbox2
    $listbox2.FormattingEnabled = $True
    $listbox2.Location = '237, 26'
    $listbox2.Name = "listbox2"
    $listbox2.Size = '120, 134'
    $listbox2.TabIndex = 2
    $listbox2.add_SelectedIndexChanged($listbox2_SelectedIndexChanged)
    # listbox1
    $listbox1.FormattingEnabled = $True
    $listbox1.Location = '13, 26'
    $listbox1.Name = "listbox1"
    $listbox1.Size = '120, 134'
    $listbox1.TabIndex = 1
    $listbox1.Sorted = $true
    $listbox1.add_SelectedIndexChanged($listbox1_SelectedIndexChanged)
    # buttonOK
    $buttonOK.Anchor = 'Bottom, Right'
    $buttonOK.DialogResult = 'OK'
    $buttonOK.Location = '352, 227'
    $buttonOK.Name = "buttonOK"
    $buttonOK.Size = '75, 23'
    $buttonOK.TabIndex = 0
    $buttonOK.Text = "OK"
    $buttonOK.UseVisualStyleBackColor = $True
    #Save the initial state of the form
    $InitialFormWindowState = $form1.WindowState
    #Init the OnLoad event to correct the initial state of the form
    $form1.add_Load($Form_StateCorrection_Load)
    #Clean up the control events
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    #Show the Form
    $form1.ShowDialog()
    You can easily substitute  CheckedListbox if you like checkboxes.
    ¯\_(ツ)_/¯

  • Place new objects right above the last active one?

    Hi there,
    I'm using Illustrator for years now, but I still haven't figured out how to create new objects right above the last selected one instead of the absolut top of the layer (or clipping path, when in draw-inside mode).
    I want to click on an object anywhere in my layers, then draw a new path or dreate a shape right on top of it, like it works in photoshop with new layers.
    I know you can cut-out the object and place it manually via ctrl-f, but thats really cumbersome and slow.
    Does anyone have tipps how I can solve this problem or a has workaround?

    Sorry Mike, but you must have missed the part in my post, where I already stated that I know about the ctrl+f functionality. It's not a good solution sadly :-(
    My usual workflow consists of creating the main shapes of an illustration first and then add the smaller parts. Now I have to create an object, ctrl+x it, select the shape I want to add details and press ctrl+f.
    Besides that, I find it very irritating, that theres an option "draw behind" but not "draw on top" which would be much more useful.
    Do the other vectorprogramms handle the process the same?
    Or does anyone know about a plugin or script that add the functionality?

  • How to get count from new enhanced for loop

    Is there a better way to determine the count when new enhanced for loop is used as follows:
    String[] test = new String[]{"1","2","3"};
    int count = 0;
    for(String i: test)
    count++;
    system.out.println("count: "+count);
    }

    There are cases where I need to use the count inside
    the for loop. I can keep track of the count by using
    the increment. But, then I would rather using the old
    for loop. Go ahead and use it. Are you under the assumption that the old form should be avoided?
    There is no saving in term of efficiency and readability.If there is any added efficiency in the "for each" form of the loop, it is on the micro level, and you would never notice it.
    As far as readability, look at some of the crazy solutions you've been given to avoid the general for loop, then reconsider which is more readable.

  • [ORA-22905] How to read a field of an object inside another object?

    Greetings,
    I'm a student and in a current exercise we have to work with the Object Oriented Programming functionality of Oracle.
    In the database we defined an object type, which is then considered inside another object type. The thing is, that I cannot read an attribute of the inner object. I've read tens of websites but none of them have helped so far. I've read the PL/SQL User Guide and Reference document also.
    The inner object is defined as follows:
    create type address_t as object (
            street varchar(50),
            city varchar(50),
            pcode number(5,0)
            );The outer object has an object of type address_t inside it:
    CREATE TYPE professor_t as OBJECT(
              code number(2),
              p_name varchar(50),
              address address_t,
              );Also, there is a table named PROFESSORS that stores objects of type professor_t
    First of all, with a simple testing SQL statement I can see the data inside the object professor, even the object address_t:
    SELECT * FROM PROFESSORS WHERE CODE = 13;returns the following:
    CODE    |         NAME      |       ADDRESS
    13      |         JOHN     |       MYSCHEMA.ADDRESS_T('FIFTH AVENUE','NEW YORK',12345)The thing is, I want to read the field street of the object address (of type address_t) inside professor (of type professor_t).
    I could see everywhere that the way to go is to use point notation, and I've seen examples about the command VALUE, but none of the following SQL statements work:
    SELECT VALUE(ADDRESS.STREET) FROM(
      SELECT CODE,P_NAME,ADDRESS FROM PROFESSORS WHERE CODE = 13);
    SELECT ADDRESS.STREET FROM PROFESSORS WHERE CODE = 13;
    SELECT PROFESSOR.ADDRESS.STREET FROM PROFESSORS WHERE CODE = 13;I'd really appreciate if someone could show me how to access the values of the field of the object inside an object.
    Thanks in advance,
    - David
    Edited by: 858176 on May 11, 2011 6:53 PM Formatting

    Great, this worked so far.
    It is curious that you wrote 'profesores' but that is the actual name for the variable. I translated everything to english in order to post it here.
    So, the statement is:
    select value(t).DIRECCION.CIUDAD from profesores t;And It returned:
    VALUE(T).DIRECCION.CIUDAD                         
    Valencia                                          
    New York
    TijuanaAnd, applying the VALUE command to the statement:
    select codigo,
    nombre,
    value(t).DIRECCION.CALLE,
    value(t).DIRECCION.CIUDAD,
    value(t).DIRECCION.CP
    from profesores T WHERE T.CODIGO = 13;Resulting in:
    CODIGO                 NOMBRE                                             VALUE(T).DIRECCION.CALLE                           VALUE(T).DIRECCION.CIUDAD                          VALUE(T).DIRECCION.CP 
    13                     Pepito Pérez                                       Calle de los Rosales 0                           Valencia                                           46023                  That is EXACTLY what I needed.
    Thanks Thomas, It was really helpful !
    Edited by: 858176 on May 11, 2011 7:46 PM

  • Adding new objects at runtime

    hi, i'm wondering if i could have everything all set up(canvas3d,simpleuniverse,etc.) and i wanted to add to add a transformgroup to the BranchGroup, would everything update to show the new transformgroup?
    adn is a simepleuniverse like a virtualuniverse?

    i see on Canvas3d there's an update() meathod, do i use that?No, please don`t.
    The scengraph will update if you set the capability
    BranchGroup.ALLOW_CHILDREN_EXTEND
    before you add a new object
    You should update a scengraph from a Behavior. Please see
    You should read the javadoc for Behavior
    When the Java 3D behavior scheduler invokes a Behavior object's processStimulus method, that method may perform any computation it wishes. Usually, it will change its internal state and specify its new wakeup conditions. Most probably, it will manipulate scene graph elements. However, the behavior code can only change those aspects of a scene graph element permitted by the capabilities associated with that scene graph element. A scene graph's capabilities restrict behavioral manipulation to those manipulations explicitly allowed.
    The application must provide the Behavior object with references to those scene graph elements that the Behavior object will manipulate. The application provides those references as arguments to the behavior's constructor when it creates the Behavior object. Alternatively, the Behavior object itself can obtain access to the relevant scene graph elements either when Java 3D invokes its initialize method or each time Java 3D invokes its processStimulus method.
    Behavior methods have a very rigid structure. Java 3D assumes that they always run to completion (if needed, they can spawn threads). Each method's basic structure consists of the following:
    * Code to decode and extract references from the WakeupCondition enumeration that caused the object's awakening.
    * Code to perform the manipulations associated with the WakeupCondition
    * Code to establish this behavior's new WakeupCondition
    * A path to Exit (so that execution returns to the Java 3D behavior scheduler)
    regards

  • New Object Creation vs. Field Setters

    I know this is massively context dependent, but is there some rule of thumb to follow when it comes to deciding between
    i) Making an class's fields final and creating a new object with new field values when needed, and
    ii) Leaving a class's fields mutable and using setter methods to alter the field.
    I tend toward option one, because not only do I tend to shy away from setters, but also because it helps prevent me from accidentally maintaining an old reference. However, purely from a performance standpoint, which option should you assume is better? How many object's of X size do I have to be making per unit of time before the performance benefits of "final" are lost?
    Thanks!

    I've been wishing for a while that Java would add a language level concept of immutability. Either an immutable keyword or an annotation. The compiler would bitch if you declared a class immutable and each of its fields was not final and either a primitive or a reference to an immutable class. Or perhaps it could simply check that there was no assignment to any field.
    It would be handy for me as a user of a class to know that it's immutable, for things like copying and thread-safety. It might or might not allow for runtime optimizations too.
    As for whether to make a given class immutable, like others say--it depends on the semantics of the class. If it's intended to represent something dynamic--e.g. a clock, or a piece on a board whose position changes with time, or the state of a network interface including packet sent and received--then it will make your code clunky and nonintuitive if you have to create a new object everytime the state of the thing you're modeling changes. But if it's something that changes less frequently, or that represents a fairly static entity or "value", then make it immutable.
    I do agree with duffymo: Better that an object comes out of construction in a valid and useful state. So even if the object is mutable, pass field values to the c'tor or set them to reasonable defaults inside the c'tor (e.g., "now", etc.)

  • Open a new scene inside another one

    Hi All
    I am newbie in javafx and I am developing an application based on ensemble example. I made a scene (indicators) with some objects and I need to connect to oracle to complete this scene. I have created a class with a scene (login) that connects to database (typing user and password). The login scene runs a connection method to oracle that returns connection object. After this connection is successful, I will use this object into indicators scene.
    How can I "call" the login scene from indicators class?
    Are there any special thing I have to do with use a connection object in indicators class?
    Sorry if it looks like too simple, but I did not find any tip about it.
    Thank you for any help
    Ricardo

    Declaration first your new class inside private void init (final Stage s) or inside class, after that you can call like this in action button.
    final Class_After_Login cal = new Class_After_Login();
    b1.setOnAction(new EventHandler<ActionEvent>()
                            @Override public void handle(ActionEvent e)
                                    if(e.getSource()== b1)
                                            try
                                                      cal.start(s); // This Syntax like this
                                                     Class.forName ("com.mysql.jdbc.Driver");
                                                     Connection c = DriverManager.getConnection("jdbc:mysql://localhost/mahasiswa","root","");  
                                                     Statement s = c.createStatement();
                                                     String sql =("select * from login where username='"+tf.getText()+"'and password='"+pf.getText().toString()+"'");
                                                     ResultSet rs= s.executeQuery(sql);
                                                     if(rs.next())
                                                            JOptionPane.showMessageDialog(null, "Login Berhasil");
                                                     else
                                                            JOptionPane.showMessageDialog(null, "Username atau Password SALAH");
                                            catch (Exception ex)
                                                    //Logger.getLogger(Menu_Utama.class.getName()).log(Level.SEVERE, null, ex);
                        });Edited by: Tom on Feb 12, 2012 6:22 PM

  • Naming new objects

    I'm a newb to Java (and programming in general) and I was wondering if anyone could help.
    What I need to make is a bank program that can have an unlimited amount of accounts added to it. Each account is supposed to be an object. The problem i'm having is how to do the unlimited part. I'm creating the objects using the following
    BankAccounts account1 = new BankAccount();
    But what I need is too be able to change "account1" to "account2" and so on for each new object created. any help?

    Instead of changing the name of each object you can add a parameter as account name in the class BankAccount() and every time you create a new object set the name attribute different for that object which can be the loop number...
    ArrayList arr = new ArrayList();
    for(int i=0;i<anyNumber;i++){
    BankAccount account = new BankAccount();
    account.name = "account"+i;
    arr.add(account);
    }In this way when later on you fetch out the objects from the list you can differentiate between each account on the basis of the name property..

Maybe you are looking for

  • Problems with Cluster Ready Service installation (RAC) in Oracle 10g R1

    Hello I have got problems with this installation. I am starting Oracle user At the end of the installation I get a mesage when all Configuration Assistants are failed I have got 2 computers with Windows 2000 PRO, two networks (private and public) As

  • Non included transactions in Payment Wizard

    After running the payment Wizard there are some payments in the Non included transactions report. Where can I find the explanation of the 'Error description' example : Payment amount is greater dan balance amount (rule 4)

  • Version management for DMS

    Dear all; I have attached one document say Drawing  with REV 0 in DIR ,Now I want to replace the Old drawing with latest revision say REV R1 at  same time I dont want to replace the old REV 0 .How to solve this problem with version management In DMS

  • Exchange Server 2003/2010 Coexistence Mail-flow Issues

    I've installed Exchange 2010 in a 2003 coexistence scenario. 2010 was deployed with CAS,HUB, and Mailbox roles.  The installation went through smoothly, and the default RGC was created. On the 2010 Server, when I create a new users with mailbox, that

  • Invalid header field

    When I try and manually add a manifest file to jar, a IOException is thrown with the message "invalid header filed". I have copied some manifests form some posts, I get that error, I extracted the default manifest from a jar, and tried to add it, I s