Example #1
0
  @Override
  public List<String[]> getColumnVector() {
    List<String[]> columnList = new ArrayList<String[]>();
    String[] columnVec =
        new String[] {
          Configuration.IDX_FIELD_API_NAME,
          Configuration.IDX_FIELD_CLASS_BASE_NAME,
          Configuration.IDX_FIELD_METHOD_NAME,
          Configuration.IDX_FIELD_DESCRIPTION
        };
    String[] columnVec1 =
        new String[] {
          Configuration.IDX_FIELD_API_NAME,
          Configuration.IDX_FIELD_CLASS_NAME_PKG_SPLIT,
          Configuration.IDX_FIELD_METHOD_NAME,
          Configuration.IDX_FIELD_DESCRIPTION
        };

    columnList.add(columnVec);
    columnList.add(Arrays.copyOf(columnVec, 4));
    columnList.add(Arrays.copyOf(columnVec, 4));
    columnList.add(Arrays.copyOf(columnVec, 4));
    columnList.add(columnVec1);
    return columnList;
  }
Example #2
0
  public void purge() {
    _lock.lock();
    try {
      int newIndex = 0;
      for (int oldIndex = 0; oldIndex < _elements.length; oldIndex++) {
        final Object obj = _elements[oldIndex];
        final long time = _access[oldIndex];

        _elements[oldIndex] = null;
        _access[oldIndex] = 0;

        if (obj == null || time + getMaxLifeTime() < System.currentTimeMillis()) continue;

        _elements[newIndex] = obj;
        _access[newIndex] = time;

        newIndex++;
      }

      _elements = Arrays.copyOf(_elements, newIndex);
      _access = Arrays.copyOf(_access, newIndex);
      _size = newIndex;
    } finally {
      _lock.unlock();
    }
  }
  /**
   * Returns the generated OLS based on Polynomial Finite Field.
   *
   * @param pm the order of the OLS and it should be a prime power
   * @param n the number of OLS and it should be at most {@code pm-1}
   * @return the generated OLS based on Polynomial Finite Field
   */
  private List<int[][]> generatePoly_OLS(int pm, int n) {

    ArrayList<int[][]> OLS_list = new ArrayList<int[][]>(n);

    if (n == 0) {
      return OLS_list;
    }

    // p & m
    int[] parts = MathUtil.partOfPrimePower(pm);
    int[][] firstPoly_LS = generatePoly_LS(parts[0], parts[1]);
    OLS_list.add(firstPoly_LS);

    int[][] nextPoly_LS = Arrays.copyOf(firstPoly_LS, firstPoly_LS.length);
    for (int i = 1; i < n; i++) {

      int[] secondRow = nextPoly_LS[1];

      // 3->2, 4->3, 5->4 ...
      for (int row = 1; row < nextPoly_LS.length - 1; row++) {
        nextPoly_LS[row] = nextPoly_LS[row + 1];
      }
      // second row -> last row
      nextPoly_LS[nextPoly_LS.length - 1] = secondRow;

      // add and copy a new LS with raw data to process
      OLS_list.add(nextPoly_LS);
      nextPoly_LS = Arrays.copyOf(nextPoly_LS, nextPoly_LS.length);
    }

    return OLS_list;
  }
  @Override
  public List<FSM> apply(List<FSM> parents) {
    int numberOfStates = parents.get(0).getNumberOfStates();
    int numberOfEvents = parents.get(0).getNumberOfEvents();
    List<String> events = parents.get(0).getEvents();

    int point = ThreadLocalRandom.current().nextInt(parents.get(0).getNumberOfStates());
    FSM.Transition[][] tr0 = new FSM.Transition[numberOfStates][numberOfEvents];
    FSM.Transition[][] tr1 = new FSM.Transition[numberOfStates][numberOfEvents];

    for (int state = 0; state < numberOfStates; state++) {
      if (state < point) {
        tr0[state] =
            Arrays.copyOf(
                parents.get(0).transitions[state], parents.get(0).transitions[state].length);
        tr1[state] =
            Arrays.copyOf(
                parents.get(1).transitions[state], parents.get(1).transitions[state].length);
      } else {
        tr0[state] =
            Arrays.copyOf(
                parents.get(1).transitions[state], parents.get(1).transitions[state].length);
        tr1[state] =
            Arrays.copyOf(
                parents.get(0).transitions[state], parents.get(0).transitions[state].length);
      }
    }

    List<FSM> offspring = new ArrayList<FSM>();
    offspring.add(new FSM(numberOfStates, tr0));
    offspring.add(new FSM(numberOfStates, tr1));
    return offspring;
  }
  // This is where you load the data that you saved in writeToNBT
  @Override
  public void readFromNBT(NBTTagCompound nbtTagCompound) {
    super.readFromNBT(
        nbtTagCompound); // The super call is required to save and load the tiles location
    final byte NBT_TYPE_COMPOUND = 10; // See NBTBase.createNewByType() for a listing
    NBTTagList dataForAllSlots = nbtTagCompound.getTagList("Items", NBT_TYPE_COMPOUND);

    Arrays.fill(itemStacks, null); // set all slots to empty
    for (int i = 0; i < dataForAllSlots.tagCount(); ++i) {
      NBTTagCompound dataForOneSlot = dataForAllSlots.getCompoundTagAt(i);
      byte slotNumber = dataForOneSlot.getByte("Slot");
      if (slotNumber >= 0 && slotNumber < this.itemStacks.length) {
        this.itemStacks[slotNumber] = ItemStack.loadItemStackFromNBT(dataForOneSlot);
      }
    }

    // Load everything else.  Trim the arrays (or pad with 0) to make sure they have the correct
    // number of elements
    cookTime = nbtTagCompound.getShort("CookTime");
    burnTimeRemaining =
        Arrays.copyOf(nbtTagCompound.getIntArray("burnTimeRemaining"), FUEL_SLOTS_COUNT);
    burnTimeInitialValue =
        Arrays.copyOf(nbtTagCompound.getIntArray("burnTimeInitial"), FUEL_SLOTS_COUNT);
    cachedNumberOfBurningSlots = -1;
  }
Example #6
0
  public static ClusterData makeCd(
      final int lane,
      final int tile,
      final int xCoord,
      final int yCoord,
      final boolean pf,
      final byte[] bases,
      final byte[] qualities,
      final String matchedBarcode) {
    final ReadData rd = new ReadData();
    rd.setBases(Arrays.copyOf(bases, bases.length));
    rd.setQualities(Arrays.copyOf(qualities, bases.length));
    rd.setReadType(
        ReadType.T); // This will be ignored, as the cluster will be chopped up by ReadStructure

    final ClusterData cd = new ClusterData(rd);
    cd.setLane(lane);
    cd.setTile(tile);
    cd.setX(xCoord);
    cd.setY(yCoord);
    cd.setPf(pf);
    cd.setMatchedBarcode(matchedBarcode);

    return cd;
  }
Example #7
0
 /**
  * Adds a record to the table and the ID index.
  *
  * @param i index in the table where the record should be inserted
  * @param pre pre value
  * @param fid first ID value
  * @param nid last ID value
  * @param inc increment value
  * @param oid original ID value
  */
 private void add(
     final int i, final int pre, final int fid, final int nid, final int inc, final int oid) {
   if (rows == pres.length) {
     final int s = Array.newSize(rows);
     pres = Arrays.copyOf(pres, s);
     fids = Arrays.copyOf(fids, s);
     nids = Arrays.copyOf(nids, s);
     incs = Arrays.copyOf(incs, s);
     oids = Arrays.copyOf(oids, s);
   }
   if (i < rows) {
     final int destPos = i + 1;
     final int length = rows - i;
     System.arraycopy(pres, i, pres, destPos, length);
     System.arraycopy(fids, i, fids, destPos, length);
     System.arraycopy(nids, i, nids, destPos, length);
     System.arraycopy(incs, i, incs, destPos, length);
     System.arraycopy(oids, i, oids, destPos, length);
   }
   pres[i] = pre;
   fids[i] = fid;
   nids[i] = nid;
   incs[i] = inc;
   oids[i] = oid;
   ++rows;
 }
Example #8
0
    /**
     * Creates a generator object that iterates over the range from start to end, inclusive.
     *
     * @param start The start address.
     * @param end The ending address.
     * @exception java.lang.IllegalArgumentException Thrown if the start address is greater than the
     *     ending address.
     */
    IPAddressRangeGenerator(byte[] start, byte[] end) {
      if (new ByteArrayComparator().compare(start, end) > 0)
        throw new IllegalArgumentException("start must be less than or equal to end");

      m_next = new BigInteger(1, Arrays.copyOf(start, start.length));
      m_end = new BigInteger(1, Arrays.copyOf(end, end.length));
    }
  @Override
  public Object clone() {
    try {
      SqoopOptions other = (SqoopOptions) super.clone();
      if (null != columns) {
        other.columns = Arrays.copyOf(columns, columns.length);
      }

      if (null != dbOutColumns) {
        other.dbOutColumns = Arrays.copyOf(dbOutColumns, dbOutColumns.length);
      }

      if (null != inputDelimiters) {
        other.inputDelimiters = (DelimiterSet) inputDelimiters.clone();
      }

      if (null != outputDelimiters) {
        other.outputDelimiters = (DelimiterSet) outputDelimiters.clone();
      }

      if (null != conf) {
        other.conf = new Configuration(conf);
      }

      if (null != extraArgs) {
        other.extraArgs = Arrays.copyOf(extraArgs, extraArgs.length);
      }

      return other;
    } catch (CloneNotSupportedException cnse) {
      // Shouldn't happen.
      return null;
    }
  }
Example #10
0
 /** Adds a named column. */
 public void add(String name, Vec vec) {
   // needs a compatibility-check????
   _names = Arrays.copyOf(_names, _names.length + 1);
   _vecs = Arrays.copyOf(_vecs, _vecs.length + 1);
   _names[_names.length - 1] = name;
   _vecs[_vecs.length - 1] = vec;
 }
  private static int[] parse1dArray(Reader in) throws IOException {
    int c;
    while (Character.isWhitespace(c = in.read())) {}
    if (c != '[') {
      throw new IOException();
    }
    int[] array = new int[4];
    int size = 0;

    StringBuilder item = new StringBuilder();
    while (true) {
      c = in.read();
      if (c == ',' || c == ']') {
        if (size == array.length) {
          array = Arrays.copyOf(array, array.length * 2);
        }
        array[size++] = Integer.parseInt(item.toString());
        if (c == ']') {
          return Arrays.copyOf(array, size);
        }
        item.setLength(0);
      } else if (!Character.isWhitespace(c)) {
        item.append((char) c);
      }
    }
  }
 public Player setItemSlotsMax(int n) {
   if (this.itemSlots.length != n) {
     this.itemSlots = Arrays.copyOf(this.itemSlots, n);
     this.itemSlotCounts = Arrays.copyOf(this.itemSlotCounts, n);
   }
   return this;
 }
Example #13
0
  /**
   * Trims the tree model set to a smaller size in case of over-fitting. Or if extra decision trees
   * in the model don't improve the performance, we may remove them to reduce the model size and
   * also improve the speed of prediction.
   *
   * @param T the new (smaller) size of tree model set.
   */
  public void trim(int T) {
    if (k == 2) {
      if (T > trees.length) {
        throw new IllegalArgumentException("The new model size is larger than the current size.");
      }

      if (T <= 0) {
        throw new IllegalArgumentException("Invalid new model size: " + T);
      }

      if (T < trees.length) {
        trees = Arrays.copyOf(trees, T);
      }
    } else {
      if (T > forest[0].length) {
        throw new IllegalArgumentException("The new model size is larger than the current one.");
      }

      if (T <= 0) {
        throw new IllegalArgumentException("Invalid new model size: " + T);
      }

      if (T < forest[0].length) {
        for (int i = 0; i < forest.length; i++) {
          forest[i] = Arrays.copyOf(forest[i], T);
        }
      }
    }
  }
Example #14
0
 /**
  * The update constructor. Copies the arrays and updates a single entry.
  *
  * @param locationArray the location array
  * @param index the updated index
  * @param location the updated location
  * @param rank the updated rank
  */
 public TmfLocationArray(
     TmfLocationArray locationArray, int index, ITmfLocation location, long rank) {
   fLocations = Arrays.copyOf(locationArray.fLocations, locationArray.fLocations.length);
   fLocations[index] = location;
   fRanks = Arrays.copyOf(locationArray.fRanks, locationArray.fRanks.length);
   fRanks[index] = rank;
 }
Example #15
0
  /**
   * AES CTR(Counter) Mode for Java ported from AES-CTR-Mode implementation in JavaScript by Chris
   * Veness
   *
   * @see <a href="http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf">"Recommendation
   *     for Block Cipher Modes of Operation - Methods and Techniques"</a>
   */
  private String AESCounterModeDecrypt(String cipherText, String key, int nBits) throws Exception {
    if (!(nBits == 128 || nBits == 192 || nBits == 256)) {
      return "Error: Must be a key mode of either 128, 192, 256 bits";
    }
    if (cipherText == null || key == null) {
      return "Error: cipher and/or key equals null";
    }
    String res = null;
    nBits = nBits / 8;
    byte[] data = Base64.decode(cipherText.toCharArray());
    /*
     * CHECK: we should always use getBytes("UTF-8") or with wanted charset, never system charset!
     */
    byte[] k = Arrays.copyOf(key.getBytes(), nBits);

    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
    SecretKey secretKey = generateSecretKey(k, nBits);
    byte[] nonceBytes = Arrays.copyOf(Arrays.copyOf(data, 8), nBits / 2);
    IvParameterSpec nonce = new IvParameterSpec(nonceBytes);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, nonce);
    /*
     * CHECK: we should always use new String (bytes,charset) to avoid issues with system charset and utf-8
     */
    res = new String(cipher.doFinal(data, 8, data.length - 8));
    return res;
  }
 @Override
 protected TypeComparator<T> getNewComparator(ExecutionConfig executionConfig) {
   @SuppressWarnings("rawtypes")
   final TypeComparator[] finalFieldComparators =
       Arrays.copyOf(fieldComparators, comparatorHelperIndex);
   final int[] finalLogicalKeyFields = Arrays.copyOf(logicalKeyFields, comparatorHelperIndex);
   // final TypeSerializer[] finalFieldSerializers = Arrays.copyOf(fieldSerializers,
   // comparatorHelperIndex);
   // create the serializers for the prefix up to highest key position
   int maxKey = 0;
   for (int key : finalLogicalKeyFields) {
     maxKey = Math.max(maxKey, key);
   }
   TypeSerializer<?>[] fieldSerializers = new TypeSerializer<?>[maxKey + 1];
   for (int i = 0; i <= maxKey; i++) {
     fieldSerializers[i] = types[i].createSerializer(executionConfig);
   }
   if (finalFieldComparators.length == 0
       || finalLogicalKeyFields.length == 0
       || fieldSerializers.length == 0
       || finalFieldComparators.length != finalLogicalKeyFields.length) {
     throw new IllegalArgumentException("Tuple comparator creation has a bug");
   }
   return new TupleComparator<T>(finalLogicalKeyFields, finalFieldComparators, fieldSerializers);
 }
Example #17
0
  public void setReturnType(
      ClassObjectType objectType, String[] params, String[] args, Declaration[] declarations)
      throws NoSuchMethodException, IllegalArgumentException {
    this.returnType = objectType;
    this.params = params;
    if (args != null) {
      this.abducibleArgs = Arrays.copyOf(args, args.length);
      this.arg2param = new int[abducibleArgs.length];
      for (int j = 0; j < this.abducibleArgs.length; j++) {
        boolean matched = false;
        for (int k = 0; k < params.length; k++) {
          if (abducibleArgs[j].equals(params[k])) {
            this.arg2param[j] = k;
            matched = true;
            break;
          }
          if (matched) {
            break;
          }
        }
        if (!matched) {
          throw new IllegalArgumentException(
              "Constructor argument " + abducibleArgs[j] + " cannot be resolved ");
        }
      }
    } else {
      this.abducibleArgs = Arrays.copyOf(params, params.length - 1);
      this.arg2param = new int[abducibleArgs.length];
      for (int j = 0; j < this.abducibleArgs.length; j++) {
        this.arg2param[j] = j;
      }
    }

    findConstructor(declarations);
  }
Example #18
0
 private final CheckOut[] resizeCheckOut(Boolean action, CheckOut[] resizing) {
   if (action) {
     return (Arrays.copyOf(resizing, resizing.length + 1));
   } else {
     return (Arrays.copyOf(resizing, resizing.length - 1));
   }
 }
Example #19
0
  /**
   * Sets the output text.
   *
   * @param t output text
   * @param s text size
   */
  public final void setText(final byte[] t, final int s) {
    // remove invalid characters and compare old with new string
    int ns = 0;
    final int ts = text.size();
    final byte[] tt = text.text();
    boolean eq = true;
    for (int r = 0; r < s; ++r) {
      final byte b = t[r];
      // support characters, highlighting codes, tabs and newlines
      if (b >= ' ' || b <= TokenBuilder.MARK || b == 0x09 || b == 0x0A) {
        t[ns++] = t[r];
      }
      eq &= ns < ts && ns < s && t[ns] == tt[ns];
    }
    eq &= ns == ts;

    // new text is different...
    if (!eq) {
      text = new BaseXTextTokens(Arrays.copyOf(t, ns));
      rend.setText(text);
      scroll.pos(0);
    }
    if (undo != null) undo.store(t.length != ns ? Arrays.copyOf(t, ns) : t, 0);
    SwingUtilities.invokeLater(calc);
  }
  @Test
  public void testAddNode() throws Exception {
    waitForFullMesh(2000);
    IStoreClient<String, String> client0 =
        syncManagers[0].getStoreClient("global", String.class, String.class);
    IStoreClient<String, String> client1 =
        syncManagers[1].getStoreClient("global", String.class, String.class);
    client0.put("key", "value");
    waitForValue(client1, "key", "value", 2000, "client1");

    nodes.add(new ClusterNode("localhost", 40105, (short) 5, (short) 5));
    SyncManager[] sms = Arrays.copyOf(syncManagers, syncManagers.length + 1);
    FloodlightModuleContext[] fmcs = Arrays.copyOf(moduleContexts, moduleContexts.length + 1);
    sms[syncManagers.length] = new SyncManager();
    fmcs[moduleContexts.length] = new FloodlightModuleContext();
    nodeString = mapper.writeValueAsString(nodes);

    setupSyncManager(
        fmcs[moduleContexts.length], sms[syncManagers.length], nodes.get(syncManagers.length));
    syncManagers = sms;
    moduleContexts = fmcs;

    for (int i = 0; i < 4; i++) {
      moduleContexts[i].addConfigParam(syncManagers[i], "nodes", nodeString);
      syncManagers[i].doUpdateConfiguration();
    }
    waitForFullMesh(2000);

    IStoreClient<String, String> client4 =
        syncManagers[4].getStoreClient("global", String.class, String.class);
    client4.put("newkey", "newvalue");
    waitForValue(client4, "key", "value", 2000, "client4");
    waitForValue(client0, "newkey", "newvalue", 2000, "client0");
  }
  private boolean cleanupRequestor(long now) {
    boolean empty = true;
    int x = 0;
    for (int i = 0; i < requestorNodes.length; i++) {
      WeakReference<? extends PeerNodeUnlocked> ref = requestorNodes[i];
      if (ref == null) continue;
      PeerNodeUnlocked pn = ref.get();
      if (pn == null) continue;
      long bootID = pn.getBootID();
      if (bootID != requestorBootIDs[i]) continue;
      if (!pn.isConnected()) continue;
      if (now - requestorTimes[i] > MAX_TIME_BETWEEN_REQUEST_AND_OFFER) continue;
      empty = false;
      requestorNodes[x] = requestorNodes[i];
      requestorTimes[x] = requestorTimes[i];
      requestorBootIDs[x] = requestorBootIDs[i];
      requestorHTLs[x] = requestorHTLs[i];
      x++;
    }
    if (x < requestorNodes.length) {
      requestorNodes = Arrays.copyOf(requestorNodes, x);
      ;
      requestorTimes = Arrays.copyOf(requestorTimes, x);
      ;
      requestorBootIDs = Arrays.copyOf(requestorBootIDs, x);
      ;
      requestorHTLs = Arrays.copyOf(requestorHTLs, x);
      ;
    }

    return empty;
  }
Example #22
0
  protected long[] physAllocate(int size, boolean ensureAvail, boolean recursive) {
    assert (disableLocks || structuralLock.isHeldByCurrentThread());
    if (size == 0L) return new long[] {0L};
    // append to end of file
    if (size < MAX_REC_SIZE) {
      long indexVal = freePhysTake(size, ensureAvail, recursive);
      indexVal |= ((long) size) << 48;
      return new long[] {indexVal};
    } else {
      long[] ret = new long[2];
      int retPos = 0;
      int c = 8;

      while (size > 0) {
        if (retPos == ret.length) ret = Arrays.copyOf(ret, ret.length * 2);
        int allocSize = Math.min(size, MAX_REC_SIZE);
        size -= allocSize - c;

        // append to end of file
        long indexVal = freePhysTake(allocSize, ensureAvail, recursive);
        indexVal |= (((long) allocSize) << 48);
        if (c != 0) indexVal |= MASK_LINKED;
        ret[retPos++] = indexVal;

        c = size <= MAX_REC_SIZE ? 0 : 8;
      }
      if (size != 0) throw new AssertionError();

      return Arrays.copyOf(ret, retPos);
    }
  }
  /**
   * This method returns a general regression formula for a given function (i.e. the function in
   * myGeneralFunction). We use the method of steepest descent (gradient descent) in order to find
   * the minimum value of the error. Implementing this algorithm involves calculating the error and
   * progressing down the gradient incline accordingly. We first define values for the step and
   * lambda (learning factor) as well as the number of coefficients, a counter for the while loop,
   * and three arrays that are initially the same as the coefficients but that change in the while
   * loop to further satisfy our conditions. After much experimentation, I decided that a step of
   * 0.001 and lambda of .1 are the best bets, as they provide values quite close to the actual one.
   * In the while loop, we iterate a million times (we could do more, but due to big-O constraints
   * we must settle), stepping down each element of the 'left' array and stepping up each element of
   * the 'right' array. We then find the derivative using three points: the corresponding points in
   * each array (right, initGuesses, and left). The nextGuess element is then decreased by lambda
   * times the derivative. This procedure is rep- eated for each element in the array during each
   * pass of the while loop. We calculate the error of the nextGuess array as well as the
   * currentGuess array and find their difference; if it is nonzero, i.e. nextError > currentError,
   * then we shift in the opposite direction (negative gradient). If the two are machine-precision
   * equal, we call it quits. Otherwise, the loop repeats -- and the new initialGuesses array is now
   * the nextGuess array, with the updated values of coefficients. The loop trudges on. Finally, we
   * return initialGuesses.
   *
   * @param data is the set of points that we wish to fit to a given curve
   * @return an array of points that map to the coefficients of the curve equation
   */
  public static double[] genReg(Point[] data, double[] initialGuesses) {
    // define factors for descent
    double step = 0.0001;
    double lambda = .1;

    // define arrays to hold updated and nearby values
    double[] nextGuess = initialGuesses;
    double[] left = initialGuesses;
    double[] right = initialGuesses;

    // simplifies coding
    int numOfCoeffs = initialGuesses.length;

    // loop invariants
    boolean terminate = false;
    int counter = 0;

    while (counter < 1000000 && terminate == false) {
      // updates array
      initialGuesses = Arrays.copyOf(nextGuess, numOfCoeffs);

      // calculates 3-point derivative, shifts the coefficient in the nextGuess array
      for (int i = 0; i < numOfCoeffs; i++) {
        left = Arrays.copyOf(initialGuesses, numOfCoeffs);
        left[i] -= step;

        right = Arrays.copyOf(initialGuesses, numOfCoeffs);
        right[i] += step;

        Point leftPt = new Point(left[i], calcErrFunct(data, left));
        Point currentPt = new Point(initialGuesses[i], calcErrFunct(data, initialGuesses));
        Point rightPt = new Point(right[i], calcErrFunct(data, right));

        nextGuess[i] -=
            lambda
                * DerivativesUpdated.parabolicDerivNew(
                    leftPt, currentPt, rightPt, currentPt.getX());
      } // close for loop

      // calculates error
      double currentError = calcErrFunct(data, initialGuesses);
      double nextError = calcErrFunct(data, nextGuess);

      // if new error is greater, we dial down lambda
      if (currentError < nextError) {
        nextGuess = Arrays.copyOf(initialGuesses, numOfCoeffs);
        lambda /= 2;
      } // close if

      // if the errors are approximately the same, we're done
      if (currentError == nextError) {
        terminate = true;
      } // close if

      counter++;
    } // close while

    return initialGuesses;
  } // close genReg()
 private List<Object[]> buildStepExecutionParameters(StepExecution stepExecution) {
   Assert.isNull(
       stepExecution.getId(),
       "to-be-saved (not updated) StepExecution can't already have an id assigned");
   Assert.isNull(
       stepExecution.getVersion(),
       "to-be-saved (not updated) StepExecution can't already have a version assigned");
   validateStepExecution(stepExecution);
   stepExecution.setId(stepExecutionIncrementer.nextLongValue());
   stepExecution.incrementVersion(); // Should be 0
   List<Object[]> parameters = new ArrayList<Object[]>();
   String exitDescription =
       truncateExitDescription(stepExecution.getExitStatus().getExitDescription());
   Object[] parameterValues =
       new Object[] {
         stepExecution.getId(),
         stepExecution.getVersion(),
         stepExecution.getStepName(),
         stepExecution.getJobExecutionId(),
         stepExecution.getStartTime(),
         stepExecution.getEndTime(),
         stepExecution.getStatus().toString(),
         stepExecution.getCommitCount(),
         stepExecution.getReadCount(),
         stepExecution.getFilterCount(),
         stepExecution.getWriteCount(),
         stepExecution.getExitStatus().getExitCode(),
         exitDescription,
         stepExecution.getReadSkipCount(),
         stepExecution.getWriteSkipCount(),
         stepExecution.getProcessSkipCount(),
         stepExecution.getRollbackCount(),
         stepExecution.getLastUpdated()
       };
   Integer[] parameterTypes =
       new Integer[] {
         Types.BIGINT,
         Types.INTEGER,
         Types.VARCHAR,
         Types.BIGINT,
         Types.TIMESTAMP,
         Types.TIMESTAMP,
         Types.VARCHAR,
         Types.INTEGER,
         Types.INTEGER,
         Types.INTEGER,
         Types.INTEGER,
         Types.VARCHAR,
         Types.VARCHAR,
         Types.INTEGER,
         Types.INTEGER,
         Types.INTEGER,
         Types.INTEGER,
         Types.TIMESTAMP
       };
   parameters.add(0, Arrays.copyOf(parameterValues, parameterValues.length));
   parameters.add(1, Arrays.copyOf(parameterTypes, parameterTypes.length));
   return parameters;
 }
  @Override
  protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
      throws IllegalBlockSizeException, BadPaddingException {
    if (input != null) {
      engineUpdate(input, inputOffset, inputLen);
    }

    if (inputTooLarge) {
      throw new IllegalBlockSizeException("input must be under " + buffer.length + " bytes");
    }

    final byte[] tmpBuf;
    if (bufferOffset != buffer.length) {
      if (padding == NativeCrypto.RSA_NO_PADDING) {
        tmpBuf = new byte[buffer.length];
        System.arraycopy(buffer, 0, tmpBuf, buffer.length - bufferOffset, bufferOffset);
      } else {
        tmpBuf = Arrays.copyOf(buffer, bufferOffset);
      }
    } else {
      tmpBuf = buffer;
    }

    byte[] output = new byte[buffer.length];
    int resultSize;
    if (encrypting) {
      if (usingPrivateKey) {
        resultSize =
            NativeCrypto.RSA_private_encrypt(
                tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
      } else {
        resultSize =
            NativeCrypto.RSA_public_encrypt(
                tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
      }
    } else {
      try {
        if (usingPrivateKey) {
          resultSize =
              NativeCrypto.RSA_private_decrypt(
                  tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
        } else {
          resultSize =
              NativeCrypto.RSA_public_decrypt(
                  tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
        }
      } catch (SignatureException e) {
        IllegalBlockSizeException newE = new IllegalBlockSizeException();
        newE.initCause(e);
        throw newE;
      }
    }
    if (!encrypting && resultSize != output.length) {
      output = Arrays.copyOf(output, resultSize);
    }

    bufferOffset = 0;
    return output;
  }
 /**
  * Constructs a new BufferFormat instance with the given parameters.
  *
  * @param chroma a VLC buffer type, must be exactly 4 characters and cannot contain non-ASCII
  *     characters
  * @param width the width, must be &gt; 0
  * @param height the height, must be &gt; 0
  * @param pitches the pitch of each plane that this buffer consists of (usually a multiple of
  *     width)
  * @param lines the number of lines of each plane that this buffer consists of (usually same as
  *     height)
  * @throws IllegalArgumentException if any parameter is invalid
  */
 public BufferFormat(String chroma, int width, int height, int[] pitches, int[] lines) {
   validate(chroma, width, height, pitches, lines);
   this.chroma = chroma;
   this.width = width;
   this.height = height;
   this.pitches = Arrays.copyOf(pitches, pitches.length);
   this.lines = Arrays.copyOf(lines, lines.length);
 }
 /**
  * Constructs a ComponentValueProperty with the specified vaadin event types.
  *
  * @param changeEvents array of vaadin event types of the events that signify a property change.
  * @param staleEvents array of vaadin event types of the events that signify a property became
  *     stale.
  */
 public AbstractVaadinSetProperty(
     Class<? extends Component.Event>[] changeEvents,
     Class<? extends Component.Event>[] staleEvents) {
   this.changeEvents =
       changeEvents != null ? Arrays.copyOf(changeEvents, changeEvents.length) : changeEvents;
   this.staleEvents =
       staleEvents != null ? Arrays.copyOf(staleEvents, staleEvents.length) : staleEvents;
 }
Example #28
0
 protected void ensureCapacity(int cap) {
   while (lumps.length <= cap) {
     lumps = Arrays.copyOf(lumps, Math.max(lumps.length * 2, DEFAULT_CAPACITY));
   }
   while (patches.length <= cap) {
     patches = Arrays.copyOf(patches, Math.max(patches.length * 2, DEFAULT_CAPACITY));
   }
 }
 public void resize(int capacity) {
   // System.out.println("Growing queue to " + capacity);
   if (capacity < size)
     throw new IllegalStateException("BinHeap contains too many elements to fit in new capacity.");
   this.capacity = capacity;
   prio = Arrays.copyOf(prio, capacity + 1);
   elem = Arrays.copyOf(elem, capacity + 1);
 }
Example #30
0
 /**
  * The average number of columns per input, taking into account the topology of the inputs and
  * columns. This value is used to calculate the inhibition radius. This function supports an
  * arbitrary number of dimensions. If the number of column dimensions does not match the number of
  * input dimensions, we treat the missing, or phantom dimensions as 'ones'.
  *
  * @param c the {@link Connections} (spatial pooler memory)
  * @return
  */
 public double avgColumnsPerInput(Connections c) {
   int[] colDim = Arrays.copyOf(c.getColumnDimensions(), c.getColumnDimensions().length);
   int[] inputDim = Arrays.copyOf(c.getInputDimensions(), c.getInputDimensions().length);
   double[] columnsPerInput =
       ArrayUtils.divide(
           ArrayUtils.toDoubleArray(colDim), ArrayUtils.toDoubleArray(inputDim), 0, 0);
   return ArrayUtils.average(columnsPerInput);
 }