List of usage examples for java.util Arrays fill
public static void fill(Object[] a, Object val)
From source file:edu.harvard.i2b2.crc.dao.setfinder.PatientSetCollectionSpringDao.java
/** * function to add patient to patient set without out creating new db * session/*from ww w .ja v a 2 s.co m*/ * * @param patientId */ public void addPatient(long patientId) { setIndex++; QtPatientSetCollection collElement = new QtPatientSetCollection(); int patientSetCollId = 0; collElement.setPatientId(patientId); collElement.setQtQueryResultInstance(resultInstance); collElement.setSetIndex(setIndex); patientSetColl[batchDataIndex++] = collElement; if ((setIndex % 1000) == 0) { InsertStatementSetter batchSetter = new InsertStatementSetter(patientSetColl, batchDataIndex); jdbcTemplate.batchUpdate(insert_sql, batchSetter); Arrays.fill(patientSetColl, null); batchDataIndex = 0; } }
From source file:mitm.common.security.crypto.PBDecryptionInputStream.java
private void init(String algorithm, byte[] salt, int iterationCount) throws CryptoException { try {//from ww w . ja va 2s . c om SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); SecretKeyFactory keyFactory = securityFactory.createSecretKeyFactory(algorithm); PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount); /* * Clear out the password */ Arrays.fill(password, '#'); Key secretKey = keyFactory.generateSecret(keySpec); cipher = securityFactory.createCipher(algorithm); cipher.init(Cipher.DECRYPT_MODE, secretKey); } catch (NoSuchProviderException e) { throw new NoSuchProviderRuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } catch (InvalidKeySpecException e) { throw new CryptoException(e); } catch (NoSuchPaddingException e) { throw new CryptoException(e); } catch (InvalidKeyException e) { throw new CryptoException(e); } }
From source file:CircularQueue.java
public void clear() { Arrays.fill(q, null); size = 0; producerIndex = 0; consumerIndex = 0; }
From source file:com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation.SmileInterpolator.java
public List<T> getFittedModelParameters(final double forward, final double[] strikes, final double expiry, final double[] impliedVols) { ArgumentChecker.notNull(strikes, "strikes"); ArgumentChecker.notNull(impliedVols, "implied volatilities"); final int n = strikes.length; ArgumentChecker.isTrue(n > 2, "cannot fit less than three points; have {}", n); ArgumentChecker.isTrue(impliedVols.length == n, "#strikes != # vols; have {} and {}", impliedVols.length, n);/*from w ww. j a v a2 s . c o m*/ validateStrikes(strikes); final List<T> modelParameters = new ArrayList<>(n); final double[] errors = new double[n]; Arrays.fill(errors, FIT_ERROR); final SmileModelFitter<T> globalFitter = getFitter(forward, strikes, expiry, impliedVols, errors); final BitSet gFixed = getGlobalFixedValues(); LeastSquareResultsWithTransform gBest = null; double chiSqr = Double.POSITIVE_INFINITY; //TODO set these in sub classes int tries = 0; int count = 0; while (chiSqr > 100.0 * n && count < 5) { //10bps average error final DoubleMatrix1D gStart = getGlobalStart(forward, strikes, expiry, impliedVols); try { final LeastSquareResultsWithTransform glsRes = globalFitter.solve(gStart, gFixed); if (glsRes.getChiSq() < chiSqr) { gBest = glsRes; chiSqr = gBest.getChiSq(); } count++; } catch (final Exception e) { } tries++; if (tries > 20) { throw new MathException("Cannot fit data"); } } if (gBest == null) { throw new IllegalStateException("Global estimate was null; should never happen"); } if (n == 3) { if (gBest.getChiSq() / n > 1.0) { s_logger.debug("chi^2 on fit to ", +n + " points is " + gBest.getChiSq()); } modelParameters.add(toSmileModelData(gBest.getModelParameters())); } else { final BitSet lFixed = getLocalFixedValues(); DoubleMatrix1D lStart = gBest.getModelParameters(); for (int i = 0; i < n - 2; i++) { final double[][] temp = getStrikesVolsAndErrors(i, strikes, impliedVols, errors); final double[] tStrikes = temp[0]; final double[] tVols = temp[1]; final double[] tErrors = temp[2]; final SmileModelFitter<T> localFitter = getFitter(forward, tStrikes, expiry, tVols, tErrors); LeastSquareResultsWithTransform lRes = localFitter.solve(lStart, lFixed); LeastSquareResultsWithTransform best = lRes; count = 0; while (lRes.getChiSq() > 3.0 && count < 10) { lStart = getGlobalStart(forward, strikes, expiry, impliedVols); lRes = localFitter.solve(lStart, lFixed); if (lRes.getChiSq() < best.getChiSq()) { best = lRes; } count++; } if (best.getChiSq() > 3.0) { s_logger.debug("chi^2 on 3-point fit #" + i + " is " + best.getChiSq()); } modelParameters.add(toSmileModelData(best.getModelParameters())); } } return modelParameters; }
From source file:clus.statistic.ClassificationStat.java
public void initSingleTargetFrom(double[] distro) { m_ClassCounts[0] = distro;/*from w ww . j a v a2 s . co m*/ m_SumWeight = 0.0; for (int i = 0; i < distro.length; i++) { m_SumWeight += distro[i]; } Arrays.fill(m_SumWeights, m_SumWeight); }
From source file:edu.utah.further.core.api.collections.ArrayUtil.java
/** * /**//from w ww.j a v a 2 s . c o m * * @param size * @param fillValue * @return */ public static double[] newDoubleVector(final int size, final double fillValue) { final double[] a = new double[size]; Arrays.fill(a, fillValue); return a; }
From source file:net.fenyo.gnetwatch.actions.ActionFlood.java
/** * Floods the target./* www. j a va2 s.c o m*/ * @param none. * @return void. * @throws IOException IO exception. * @throws InterruptedException exception. */ public void invoke() throws IOException, InterruptedException { if (isDisposed() == true) return; try { super.invoke(); // il faudrait copier les queriers la cration de l'action final IPQuerier querier; DatagramSocket socket; final byte[] buf; final DatagramPacket packet; // on invoque un champ persistent depuis potentiellement un thread autre que celui qu gre une session qui rend cet objet persistent, on doit viter cet accs concurrent (les sessions ne sont pas thread safe) synchronized (getGUI().getSynchro()) { if (TargetIPv4.class.isInstance(getTarget())) { querier = ((TargetIPv4) getTarget()).getIPQuerier(); } else if (TargetIPv6.class.isInstance(getTarget())) { querier = ((TargetIPv6) getTarget()).getIPQuerier(); } else return; socket = new DatagramSocket(querier.getPortSrc()); socket.setTrafficClass(querier.getTos() << 2); socket.setBroadcast(true); buf = new byte[querier.getPDUMaxSize()]; Arrays.fill(buf, (byte) 0); packet = new DatagramPacket(buf, buf.length, new InetSocketAddress(querier.getAddress(), querier.getPortDst())); } long last_time = System.currentTimeMillis(); int bytes_sent = 0; while (true) { socket.send(packet); bytes_sent += buf.length; if (System.currentTimeMillis() - last_time > 1000) { synchronized (getGUI().getSynchro()) { synchronized (getGUI().sync_tree) { final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.update(this); getTarget().addEvent(new EventFlood(new Double( ((double) 8 * 1000 * bytes_sent) / (System.currentTimeMillis() - last_time)) .intValue())); setDescription( GenericTools.formatNumericString(getGUI().getConfig(), "" + new Double(((double) 8 * 1000 * bytes_sent) / (System.currentTimeMillis() - last_time)).intValue()) + " bit/s"); session.getTransaction().commit(); } catch (final Exception ex) { log.error("Exception", ex); session.getTransaction().rollback(); } } } synchronized (getGUI().getSynchro()) { getGUI().setStatus(getGUI().getConfig().getPattern("bytes_flooded", bytes_sent, querier.getAddress().toString().substring(1))); } last_time = System.currentTimeMillis(); bytes_sent = 0; } if (interrupted == true) { socket.close(); return; } } } catch (final InterruptedException ex) { } }
From source file:com.hadoop.compression.lzo.LzopInputStream.java
/** * Read and verify an lzo header, setting relevant block checksum options * and ignoring most everything else./* w ww. ja v a 2s. c o m*/ * @param in InputStream * @throws IOException if there is a error in lzo header */ protected void readHeader(InputStream in) throws IOException { readFully(in, buf, 0, 9); if (!Arrays.equals(buf, LzopCodec.LZO_MAGIC)) { throw new IOException("Invalid LZO header"); } Arrays.fill(buf, (byte) 0); Adler32 adler = new Adler32(); CRC32 crc32 = new CRC32(); int hitem = readHeaderItem(in, buf, 2, adler, crc32); // lzop version if (hitem > LzopCodec.LZOP_VERSION) { LOG.debug("Compressed with later version of lzop: " + Integer.toHexString(hitem) + " (expected 0x" + Integer.toHexString(LzopCodec.LZOP_VERSION) + ")"); } hitem = readHeaderItem(in, buf, 2, adler, crc32); // lzo library version if (hitem < LzoDecompressor.MINIMUM_LZO_VERSION) { throw new IOException("Compressed with incompatible lzo version: 0x" + Integer.toHexString(hitem) + " (expected at least 0x" + Integer.toHexString(LzoDecompressor.MINIMUM_LZO_VERSION) + ")"); } hitem = readHeaderItem(in, buf, 2, adler, crc32); // lzop extract version if (hitem > LzopCodec.LZOP_VERSION) { throw new IOException("Compressed with incompatible lzop version: 0x" + Integer.toHexString(hitem) + " (expected 0x" + Integer.toHexString(LzopCodec.LZOP_VERSION) + ")"); } hitem = readHeaderItem(in, buf, 1, adler, crc32); // method if (hitem < 1 || hitem > 3) { throw new IOException("Invalid strategy: " + Integer.toHexString(hitem)); } readHeaderItem(in, buf, 1, adler, crc32); // ignore level // flags hitem = readHeaderItem(in, buf, 4, adler, crc32); try { for (DChecksum f : dflags) { if (0 == (f.getHeaderMask() & hitem)) { dflags.remove(f); } else { dcheck.put(f, (int) f.getChecksumClass().newInstance().getValue()); } } for (CChecksum f : cflags) { if (0 == (f.getHeaderMask() & hitem)) { cflags.remove(f); } else { ccheck.put(f, (int) f.getChecksumClass().newInstance().getValue()); } } } catch (InstantiationException e) { throw new RuntimeException("Internal error", e); } catch (IllegalAccessException e) { throw new RuntimeException("Internal error", e); } ((LzopDecompressor) decompressor).initHeaderFlags(dflags, cflags); boolean useCRC32 = 0 != (hitem & 0x00001000); // F_H_CRC32 boolean extraField = 0 != (hitem & 0x00000040); // F_H_EXTRA_FIELD if (0 != (hitem & 0x400)) { // F_MULTIPART throw new IOException("Multipart lzop not supported"); } if (0 != (hitem & 0x800)) { // F_H_FILTER throw new IOException("lzop filter not supported"); } if (0 != (hitem & 0x000FC000)) { // F_RESERVED throw new IOException("Unknown flags in header"); } // known !F_H_FILTER, so no optional block readHeaderItem(in, buf, 4, adler, crc32); // ignore mode readHeaderItem(in, buf, 4, adler, crc32); // ignore mtime readHeaderItem(in, buf, 4, adler, crc32); // ignore gmtdiff hitem = readHeaderItem(in, buf, 1, adler, crc32); // fn len if (hitem > 0) { // skip filename int filenameLen = Math.max(4, hitem); // buffer must be at least 4 bytes for readHeaderItem to work. readHeaderItem(in, new byte[filenameLen], hitem, adler, crc32); } int checksum = (int) (useCRC32 ? crc32.getValue() : adler.getValue()); hitem = readHeaderItem(in, buf, 4, adler, crc32); // read checksum if (hitem != checksum) { throw new IOException("Invalid header checksum: " + Long.toHexString(checksum) + " (expected 0x" + Integer.toHexString(hitem) + ")"); } if (extraField) { // lzop 1.08 ultimately ignores this LOG.debug("Extra header field not processed"); adler.reset(); crc32.reset(); hitem = readHeaderItem(in, buf, 4, adler, crc32); readHeaderItem(in, new byte[hitem], hitem, adler, crc32); checksum = (int) (useCRC32 ? crc32.getValue() : adler.getValue()); if (checksum != readHeaderItem(in, buf, 4, adler, crc32)) { throw new IOException("Invalid checksum for extra header field"); } } }
From source file:com.spotify.sshagenttls.CertHttpsHandler.java
public void handle(final HttpsURLConnection conn) { final CertKey certKey; try {//from ww w . j a va 2 s. c om certKey = createCertKey(); } catch (IOException | GeneralSecurityException e) { if (failOnCertError) { throw new RuntimeException(e); } else { LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. " + "No cert will be sent with request.", getCertSource(), e.toString()); LOG.debug("full exception fromPaths setting up ClientCertificate follows", e); return; } } final Certificate cert = certKey.cert(); final PrivateKey key = certKey.key(); // Generate a keystore password. // Do all this locally to not make copies of the password in memory. final SecureRandom random = new SecureRandom(); final int numBytes = 60; final char[] keyStorePassword = new char[numBytes]; for (int i = 0; i < numBytes; i++) { // Only use ASCII characters for the password. The corresponding integer range is [32, 126]. keyStorePassword[i] = (char) (random.nextInt(95) + 32); } try { // We're creating a keystore in memory and putting the cert & key into it. // The keystore needs a password when we put the key into it, even though it's only going to // exist for the lifetime of the process. So we just have some random password that we use. final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", cert); keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert }); // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, keyStorePassword).build(); // Clear out arrays that had password Arrays.fill(keyStorePassword, '\0'); conn.setSSLSocketFactory(sslContext.getSocketFactory()); } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more. throw new RuntimeException(e); } }