Esempio n. 1
0
 /** Replaces a figure in the drawing without removing it from the drawing. */
 public synchronized void replace(Figure figure, Figure replacement) {
   int index = fFigures.indexOf(figure);
   if (index != -1) {
     replacement.addToContainer(this); // will invalidate figure
     figure.changed();
     fFigures.setElementAt(replacement, index);
   }
 }
Esempio n. 2
0
  /**
   * This method returns an array of all the tables referenced in the datastore.
   *
   * @param updateable True if the table list should only include updateable tables and false if it
   *     should include all.
   */
  public String[] getTableList(boolean updateable) {

    DSColumnDescriptor col = null;

    Vector tables = new Vector();
    Vector pkey = new Vector();

    for (int i = 0; i < _desc.getColumnCount(); i++) {
      col = _desc.getColumn(i);
      String tableName = col.getTable();
      if (tableName == null) tableName = _desc.getDefaultTable();

      if ((!updateable) || col.isUpdateable()) {
        boolean found = false;
        for (int j = 0; j < tables.size(); j++) {
          if ((tables.elementAt(j)).equals(tableName)) {
            if (col.isPrimaryKey()) pkey.setElementAt(new Boolean(true), j);
            found = true;
            break;
          }
        }
        if (!found && tableName != null) {
          tables.addElement(tableName);
          pkey.addElement(new Boolean(col.isPrimaryKey()));
        }
      }
    }

    if (updateable) {
      for (int i = pkey.size() - 1; i > -1; i--) {
        if (!((Boolean) pkey.elementAt(i)).booleanValue()) tables.removeElementAt(i);
      }
    } else {
      for (int i = 0; i < getAliasCount(); i++) {
        try {
          String table = getTable(i);
          boolean found = false;
          for (int j = 0; j < tables.size(); j++) {
            if ((tables.elementAt(j)).equals(table)) found = true;
          }
          if (!found && table != null) tables.addElement(table);
        } catch (Exception e) {
        }
      }
    }

    String retVal[] = new String[tables.size()];
    tables.copyInto(retVal);

    return retVal;
  }
 /**
  * A nice ol' bubble sort. This is used because it has a passable performance when the list starts
  * off sorted.
  */
 public void sort() {
   synchronized (this) {
     boolean swap;
     do {
       swap = false;
       for (int i = 1; i < tracks.size(); i++) {
         Track lastTrack = (Track) tracks.elementAt(i - 1);
         Track track = (Track) tracks.elementAt(i);
         if (compare(lastTrack, track) > 0) {
           tracks.setElementAt(track, i - 1);
           tracks.setElementAt(lastTrack, i);
           swap = true;
         }
       }
     } while (swap);
   }
 }
  /**
   * INTERNAL This method iterates through a collection and gets the values from the objects to
   * conform in an in-memory query. Creation date: (1/19/01 1:18:27 PM)
   */
  public Object valuesFromCollection(
      Object object, AbstractSession session, int valueHolderPolicy, boolean isObjectUnregistered) {
    // in case the mapping is null - this can happen if a query key is being used
    // In this case, check for the query key and find it's mapping.
    boolean readMappingFromQueryKey = false;
    if (getMapping() == null) {
      getMappingFromQueryKey();
      readMappingFromQueryKey = true;
    }

    // For bug 2780817 get the mapping directly from the object.  In EJB 2.0
    // inheritance, each child must override mappings defined in an abstract
    // class with its own.
    DatabaseMapping mapping = this.mapping;
    ClassDescriptor descriptor = mapping.getDescriptor();
    if (descriptor.hasInheritance() && (descriptor.getJavaClass() != object.getClass())) {
      mapping =
          session
              .getDescriptor(object.getClass())
              .getObjectBuilder()
              .getMappingForAttributeName(getName());
      descriptor = mapping.getDescriptor();
    }

    // fetch group support
    if (descriptor.hasFetchGroupManager()) {
      FetchGroupManager fetchGroupManager = descriptor.getFetchGroupManager();
      if (fetchGroupManager.isPartialObject(object)
          && (!fetchGroupManager.isAttributeFetched(object, mapping.getAttributeName()))) {
        // the conforming attribute is not fetched, simply throw exception
        throw QueryException.cannotConformUnfetchedAttribute(mapping.getAttributeName());
      }
    }

    if (mapping.isDirectToFieldMapping()) {
      return ((AbstractDirectMapping) mapping).valueFromObject(object, mapping.getField(), session);
    } else if (mapping.isForeignReferenceMapping()) {
      // CR 3677 integration of a ValueHolderPolicy
      Object valueFromMapping = mapping.getAttributeValueFromObject(object);
      if (!((ForeignReferenceMapping) mapping)
          .getIndirectionPolicy()
          .objectIsInstantiated(valueFromMapping)) {
        if (valueHolderPolicy != InMemoryQueryIndirectionPolicy.SHOULD_TRIGGER_INDIRECTION) {
          // If the client wishes us to trigger the indirection then we should do so,
          // Other wise throw the exception
          throw QueryException
              .mustInstantiateValueholders(); // you should instantiate the valueholder for this to
                                              // work
        }

        // maybe we should throw this exception from the start, to save time
      }
      Object valueToIterate = mapping.getRealAttributeValueFromObject(object, session);
      UnitOfWorkImpl uow = isObjectUnregistered ? (UnitOfWorkImpl) session : null;

      // First check that object in fact is unregistered.
      // toDo: ?? Why is this commented out? Why are we supporting the unregistered thing at all?
      // Does not seem to be any public API for this, nor every used internally?
      // if (isObjectUnregistered) {
      //	isObjectUnregistered = !uow.getCloneMapping().containsKey(object);
      // }
      if (mapping.isCollectionMapping() && (valueToIterate != null)) {
        // For bug 2766379 must use the correct version of vectorFor to
        // unwrap the result same time.
        valueToIterate = mapping.getContainerPolicy().vectorFor(valueToIterate, session);

        // toDo: If the value is empty, need to support correct inner/outer join filtering
        // symantics.
        // For CR 2612601, try to partially replace the result with already
        // registered objects.
        if (isObjectUnregistered && (uow.getCloneMapping().get(object) == null)) {
          Vector objectValues = (Vector) valueToIterate;
          for (int i = 0; i < objectValues.size(); i++) {
            Object original = objectValues.elementAt(i);
            Object clone =
                uow.getIdentityMapAccessorInstance()
                    .getIdentityMapManager()
                    .getFromIdentityMap(original);
            if (clone != null) {
              objectValues.setElementAt(clone, i);
            }
          }
        }

        // For CR 2612601, conforming without registering, a query could be
        // bob.get("address").get("city").equal("Ottawa"); where the address
        // has been registered and modified in the UOW, but bob has not.  Thus
        // even though bob does not point to the modified address now, it will
        // as soon as it is registered, so should point to it here.
      } else if (isObjectUnregistered && (uow.getCloneMapping().get(object) == null)) {
        Object clone =
            uow.getIdentityMapAccessorInstance()
                .getIdentityMapManager()
                .getFromIdentityMap(valueToIterate);
        if (clone != null) {
          valueToIterate = clone;
        }
      }
      return valueToIterate;
    } else if (mapping.isAggregateMapping()) {
      Object aggregateValue = mapping.getAttributeValueFromObject(object);
      // Bug 3995468 - if this query key is to a mapping in an aggregate object, get the object from
      // actual mapping rather than the aggregate mapping
      while (readMappingFromQueryKey
          && mapping.isAggregateObjectMapping()
          && !((AggregateObjectMapping) mapping)
              .getReferenceClass()
              .equals(queryKey.getDescriptor().getJavaClass())) {
        mapping =
            mapping
                .getReferenceDescriptor()
                .getObjectBuilder()
                .getMappingForField(((DirectQueryKey) queryKey).getField());
        aggregateValue = mapping.getRealAttributeValueFromObject(aggregateValue, session);
      }
      return aggregateValue;
    } else {
      throw QueryException.cannotConformExpression();
    }
  }
Esempio n. 5
0
  public static Vector<Double> trainNode(
      String filename,
      int outputRepresentation,
      String inputRepresentation,
      int filter,
      double learningRate,
      int epochs) {
    Vector<Double> node = null; // initialize node to null
    double error = 1; // initialize error
    double output = 0; // initialize output
    Vector<Double> trainError = new Vector<Double>();
    double meansq = 0;
    String binTarget = "";
    String binaryRep = "";
    int target;
    openFile(filename); // open our file for training
    firstRead = true;
    int targetCounter = 0;
    while ((target = readFileIntoInputVector(inputRepresentation))
        != -2) { // while we have not reached out end of file error
      if (outputRepresentation == 4) {
        binTarget = Integer.toBinaryString(target); // convert target to binary
        int[] targetArray = new int[4]; // array to hold binary ints
        for (int h = 0; h < targetArray.length; h++) { // add binary elements to int array
          try {
            targetArray[targetArray.length - h - 1] =
                Character.digit(binTarget.charAt(binTarget.length() - h - 1), 10);
          } catch (IndexOutOfBoundsException e) { // if there is empty spaces, fill with zeros
            targetArray[targetArray.length - h - 1] = 0;
          }
        }
        target = targetArray[filter];
        binTarget = "";
        for (int i = 0; i < targetArray.length; i++) {
          binTarget = binTarget + targetArray[i];
        }
      }

      if ((filter == target && outputRepresentation == 10) || outputRepresentation != 10) {
        if (node == null) {
          node = new Vector<Double>();
          for (int i = 0; i < inputs.size(); i++) { // for each input
            double randWeight = 1; // initialize random weight
            while (randWeight > 0.15) // while out random isn't less than 0.15
            randWeight = random.nextDouble(); // get a new random double
            if (random.nextBoolean()) randWeight = randWeight * -1; // randomly set to negative
            node.addElement(new Double(randWeight)); // store random weight
          }
        }
        targetCounter++;
        // train for number of epochs
        for (int i = 0; i < epochs; i++) { // for each epoch
          double weightedSum = 0; // set/reset the weighted sum to 0
          for (int j = 0; j < inputs.size(); j++) {
            weightedSum += (inputs.elementAt(j) * node.elementAt(j)); // calculate weighted sum
          }
          output = activation(weightedSum); // retrieve output
          if (outputRepresentation == 1 || outputRepresentation == 10) output = output * 10;
          else if (outputRepresentation == 4) { // each node must have a whole number
            if (output > 0.5) output = 1;
            else output = 0;
          }

          error = target - output; // calculate error

          if (i == epochs - 1) {
            if (outputRepresentation == 4) {
              if (filter == 0) {
                allOutputs.ensureCapacity(targetCounter);
                allOutputs.add(Integer.toString((int) output));
              } else {
                allOutputs.set(
                    targetCounter - 1, allOutputs.get(targetCounter - 1) + ((int) output));
              }
            }
            trainError.add(error);
            if (Math.round(error) == 0 && outputRepresentation != 4) {
              trainCountCorrect++;
            } else if (outputRepresentation == 4 && filter == 3) {
              if (allOutputs.get(targetCounter - 1).equals(binTarget)) {
                trainCountCorrect++;
              }
            }
          }

          for (int k = 0; k < inputs.size(); k++) { // for each input
            double derivative =
                (1.64872 * Math.exp(weightedSum))
                    / (Math.pow(1.64872 + Math.exp(weightedSum), 2)); // calculate new weights
            double newWeight =
                node.elementAt(k)
                    + (learningRate * inputs.elementAt(k) * error * derivative); // cont.
            node.setElementAt(newWeight, k); // update weights
          }
        }
      }
      inputs.clear();
    }
    errorVect.addElement((Vector<Double>) trainError.clone());
    trainError.clear();
    if (outputRepresentation == 4 && filter == 3)
      System.out.println(
          "Training Percent: " + (100 * (double) trainCountCorrect / (double) targetCounter));
    if (outputRepresentation == 10 && filter == 9)
      System.out.println(
          "Training Percent: " + (10 * (double) trainCountCorrect / (double) targetCounter));
    if (outputRepresentation == 1)
      System.out.println(
          "Training Percent: " + (100 * (double) trainCountCorrect / (double) targetCounter));
    closeFile();
    return node; // node is now trained for an epoch
  }
Esempio n. 6
0
 public void setVCardData(int index, String data) {
   vCardData.setElementAt(data, index);
 }