List of usage examples for java.util Arrays stream
public static DoubleStream stream(double[] array)
From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java
@Test public void testGenericTarballDownload() throws Exception { // Generate some test content String path = contentGenerator.newArtifactPath("tar.gz"); Map<String, byte[]> entries = new HashMap<>(); entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400)); entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400)); final File tgz = makeTarball(entries); System.out.println("tar content array has length: " + tgz.length()); // We only need one repo server. ExpectationServer server = new ExpectationServer(); server.start();/* w ww . ja v a 2 s . co m*/ String url = server.formatUrl(path); // Register the generated content by writing it to the path within the repo server's dir structure. // This way when the path is requested it can be downloaded instead of returning a 404. server.expect("GET", url, (req, resp) -> { // Content-Length: 47175 // Content-Type: application/x-gzip resp.setHeader("Content-Encoding", "x-gzip"); resp.setHeader("Content-Type", "application/x-gzip"); byte[] raw = FileUtils.readFileToByteArray(tgz); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GzipCompressorOutputStream gzout = new GzipCompressorOutputStream(baos); gzout.write(raw); gzout.finish(); byte[] content = baos.toByteArray(); resp.setHeader("Content-Length", Long.toString(content.length)); OutputStream respStream = resp.getOutputStream(); respStream.write(content); respStream.flush(); System.out.println("Wrote content with length: " + content.length); }); final PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(); ccm.setMaxTotal(1); final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(ccm); CloseableHttpClient client = builder.build(); HttpGet get = new HttpGet(url); // get.setHeader( "Accept-Encoding", "gzip,deflate" ); Boolean result = client.execute(get, (response) -> { Arrays.stream(response.getAllHeaders()).forEach((h) -> System.out.println("Header:: " + h)); Header contentEncoding = response.getEntity().getContentEncoding(); if (contentEncoding == null) { contentEncoding = response.getFirstHeader("Content-Encoding"); } System.out.printf("Got content encoding: %s\n", contentEncoding == null ? "None" : contentEncoding.getValue()); byte[] content = IOUtils.toByteArray(response.getEntity().getContent()); try (TarArchiveInputStream tarIn = new TarArchiveInputStream( new GzipCompressorInputStream(new ByteArrayInputStream(content)))) { TarArchiveEntry entry = null; while ((entry = tarIn.getNextTarEntry()) != null) { System.out.printf("Got tar entry: %s\n", entry.getName()); byte[] entryData = new byte[(int) entry.getSize()]; int read = tarIn.read(entryData, 0, entryData.length); } } return false; }); }
From source file:com.spankingrpgs.model.GameState.java
private GameState(GameCharacter playerCharacter) { this.playerCharacter = playerCharacter; characters = new LinkedHashMap<>(); keywords = new HashSet<>(); items = new HashMap<>(); events = new HashMap<>(); party = new HashMap<>(CombatRange.values().length); Arrays.stream(CombatRange.values()).forEach(range -> this.party.put(range, new ArrayList<>(6))); attritionRate = AttritionRate.MODERATE; artificialIntelligenceLevel = ArtificialIntelligenceLevel.AVERAGE; playerSpankable = true;//from ww w. ja v a 2s. c om numTimesLost = 0; skills = new HashMap<>(); equipment = new HashMap<>(); episodeNumber = 1; dayNumber = 1; activityLength = 4; gameTime = Calendar.getInstance(); this.previousVillains = new HashMap<>(); try { gameTime.setTime(DATE_FORMAT.parse("09/01 at 11:00")); } catch (ParseException e) { String msg = String.format("Encountered an error formatting the date when creating the state: %s", e); LOG.log(Level.SEVERE, msg); throw new RuntimeException(msg, e); } if (playerCharacter != null) { characters.put(PC_NAME, playerCharacter); } }
From source file:com.simiacryptus.mindseye.lang.Tensor.java
/** * Instantiates a new Tensor./* w ww . j a va 2 s. c om*/ * * @param data the data * @param dims the dims */ public Tensor(@Nullable final float[] data, @Nonnull final int... dims) { if (Tensor.length(dims) >= Integer.MAX_VALUE) throw new IllegalArgumentException(); dimensions = Arrays.copyOf(dims, dims.length); strides = Tensor.getSkips(dims); if (null != data) { this.data = RecycleBin.DOUBLES.obtain(data.length);// Arrays.copyOf(data, data.length); Arrays.parallelSetAll(this.data, i -> { final double v = data[i]; return Double.isFinite(v) ? v : 0; }); assert Arrays.stream(this.data).allMatch(v -> Double.isFinite(v)); } assert isValid(); //assert (null == data || Tensor.length(dims) == data.length); }
From source file:eu.amidst.core.exponentialfamily.EF_Normal_NormalParents.java
/** * {@inheritDoc}//from w ww. j ava 2 s. c o m */ @Override public NaturalParameters getNaturalParameters() { CompoundVector naturalParametersCompound = this.createEmtpyCompoundVector(); /* 1) theta_0 */ double theta_0 = beta0 / variance; naturalParametersCompound.setThetaBeta0_NatParam(theta_0); /* 2) theta_0Theta */ double variance2Inv = 1.0 / (2 * variance); //IntStream.range(0,coeffParents.length).forEach(i-> coeffParents[i]*=(beta_0*variance2Inv)); double[] theta0_beta = Arrays.stream(betas).map(w -> -w * beta0 / variance).toArray(); naturalParametersCompound.setThetaBeta0Beta_NatParam(theta0_beta); /* 3) theta_Minus1 */ double theta_Minus1 = -variance2Inv; /* 4) theta_beta & 5) theta_betaBeta */ naturalParametersCompound.setThetaCov_NatParam(theta_Minus1, betas, variance2Inv); this.naturalParameters = naturalParametersCompound; return this.naturalParameters; }
From source file:com.esri.geoportal.harvester.agpsrc.AgpInputBroker.java
@Override public void initialize(InitContext context) throws DataProcessorException { definition.override(context.getParams()); td = context.getTask().getTaskDefinition(); CloseableHttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build(); if (context.getTask().getTaskDefinition().isIgnoreRobotsTxt()) { client = new AgpClient(httpclient, definition.getHostUrl(), definition.getCredentials(), definition.getMaxRedirects()); } else {/*from ww w . j av a 2s . c om*/ Bots bots = BotsUtils.readBots(definition.getBotsConfig(), httpclient, definition.getHostUrl()); client = new AgpClient(new BotsHttpClient(httpclient, bots), definition.getHostUrl(), definition.getCredentials(), definition.getMaxRedirects()); } try { String folderId = StringUtils.trimToNull(definition.getFolderId()); if (folderId != null) { FolderEntry[] folders = this.client.listFolders(definition.getCredentials().getUserName(), generateToken(1)); FolderEntry selectedFodler = Arrays.stream(folders) .filter(folder -> folder.id != null && folder.id.equals(folderId)).findFirst() .orElse(Arrays.stream(folders) .filter(folder -> folder.title != null && folder.title.equals(folderId)).findFirst() .orElse(null)); if (selectedFodler != null) { definition.setFolderId(selectedFodler.id); } else { definition.setFolderId(null); } } else { definition.setFolderId(null); } } catch (IOException | URISyntaxException ex) { throw new DataProcessorException( String.format("Error listing folders for user: %s", definition.getCredentials().getUserName()), ex); } }
From source file:com.netflix.spinnaker.halyard.deploy.services.v1.GenerateService.java
private static List<String> aggregateProfilesInPath(String basePath, String relativePath) { String filePrefix;//www .java 2s.c om if (!relativePath.isEmpty()) { filePrefix = relativePath + File.separator; } else { filePrefix = relativePath; } File currentPath = new File(basePath, relativePath); return Arrays.stream(currentPath.listFiles()) .map(f -> f.isFile() ? Collections.singletonList(filePrefix + f.getName()) : aggregateProfilesInPath(basePath, filePrefix + f.getName())) .reduce(new ArrayList<>(), (a, b) -> { a.addAll(b); return a; }); }
From source file:edu.washington.gs.skyline.model.quantification.DesignMatrix.java
@Override public String toString() { if (columnNames.length == 0) { return ""; }/*from w w w . j a va 2 s . com*/ List<String> lines = new ArrayList<>(); lines.add(String.join("\t", columnNames)); for (int row = 0; row < matrixColumns[0].length; row++) { final int rowNumber = row; lines.add(String.join("\t", Arrays.stream(matrixColumns).map(col -> Double.toString(col[rowNumber])) .collect(Collectors.toList()))); } return String.join("\n", lines); }
From source file:at.tfr.securefs.client.SecurefsFileServiceClient.java
public void parse(String[] args) throws ParseException { CommandLineParser clp = new DefaultParser(); CommandLine cmd = clp.parse(options, args); // validate:/*from www . j a v a 2s . c om*/ if (!cmd.hasOption("f")) { throw new ParseException("file name is mandatory"); } fileServiceUrl = cmd.getOptionValue("u", fileServiceUrl); if (cmd.hasOption("f")) { Arrays.stream(cmd.getOptionValue("f").split(",")).forEach(f -> files.add(Paths.get(f))); } asyncTest = Boolean.parseBoolean(cmd.getOptionValue("a", "false")); threads = Integer.parseInt(cmd.getOptionValue("t", "1")); if (cmd.hasOption("r") || cmd.hasOption("w") || cmd.hasOption("d")) { read = write = delete = false; read = cmd.hasOption("r"); write = cmd.hasOption("w"); delete = cmd.hasOption("d"); } }
From source file:Imputers.KnniLDProb.java
/** * Performs imputation using an already calculated similarity matrix. Used * for optimizing parameters as the similarity matrix only has to be calculated * once.//from ww w . j a v a 2s.c om * * The author is aware this description is a bit light on detail. Please * contact the author if further details are needed. * @param original Genotypes called based purely on read counts * @param callprobs Called genotype probabilities * @param list List of masked genotypes and their masked genotype * @param sim Similarity matrix * @return List of imputed probabilities */ protected List<SingleGenotypeProbability> impute(byte[][] original, List<SingleGenotypeProbability> callprobs, List<SingleGenotypeMasked> list, int[][] sim) { if (!SingleGenotypePosition.samePositions(callprobs, list)) { //Needs a proper error throw new ProgrammerException(); } Progress progress = ProgressFactory.get(list.size()); return IntStream.range(0, list.size()).mapToObj(i -> { SingleGenotypeMasked sgr = list.get(i); SingleGenotypeProbability sgc = callprobs.get(i); SingleGenotypeProbability sgp; if (Arrays.stream(sgr.getMasked()).sum() < knownDepth) { sgp = new SingleGenotypeProbability(sgr.getSample(), sgr.getSNP(), imputeSingle(original, sgr.getSample(), sgr.getSNP(), true, sim)); } else { sgp = new SingleGenotypeProbability(sgr.getSample(), sgr.getSNP(), sgc.getProb()); } progress.done(); return sgp; }).collect(Collectors.toCollection(ArrayList::new)); }
From source file:io.adeptj.runtime.common.Servlets.java
private static void handleInitParams(WebServlet webServlet, Dictionary<String, Object> properties) { Arrays.stream(webServlet.initParams()).forEach(initParam -> properties .put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX + initParam.name(), initParam.value())); }