Example usage for java.util.function Consumer accept

List of usage examples for java.util.function Consumer accept

Introduction

In this page you can find the example usage for java.util.function Consumer accept.

Prototype

void accept(T t);

Source Link

Document

Performs this operation on the given argument.

Usage

From source file:com.spotify.heroic.metric.bigtable.BigtableBackend.java

private AsyncFuture<FetchData.Result> fetchBatch(final FetchQuotaWatcher watcher, final MetricType type,
        final List<PreparedQuery> prepared, final BigtableConnection c,
        final Consumer<MetricCollection> metricsConsumer) {
    final BigtableDataClient client = c.dataClient();

    final List<AsyncFuture<FetchData.Result>> fetches = new ArrayList<>(prepared.size());

    for (final PreparedQuery p : prepared) {
        QueryTrace.NamedWatch fs = QueryTrace.watch(FETCH_SEGMENT);

        final AsyncFuture<List<FlatRow>> readRows = client.readRows(table,
                ReadRowsRequest.builder().rowKey(p.request.getRowKey())
                        .filter(RowFilter.chain(Arrays.asList(
                                RowFilter.newColumnRangeBuilder(p.request.getColumnFamily())
                                        .startQualifierOpen(p.request.getStartQualifierOpen())
                                        .endQualifierClosed(p.request.getEndQualifierClosed()).build(),
                                RowFilter.onlyLatestCell())))
                        .build());/*from w  w w .j a va  2s.com*/

        final Function<FlatRow.Cell, Metric> transform = cell -> p.deserialize(cell.getQualifier(),
                cell.getValue());

        fetches.add(readRows.directTransform(result -> {
            for (final FlatRow row : result) {
                watcher.readData(row.getCells().size());
                final List<Metric> metrics = Lists.transform(row.getCells(), transform);
                metricsConsumer.accept(MetricCollection.build(type, metrics));
            }
            return FetchData.result(fs.end());
        }));
    }
    return async.collect(fetches, FetchData.collectResult(FETCH)).directTransform(result -> {
        watcher.accessedRows(prepared.size());
        return result;
    });
}

From source file:net.dv8tion.jda.handle.EntityBuilder.java

public void createGuildSecondPass(String guildId, List<JSONArray> memberChunks) {
    HashMap<String, JSONObject> cachedGuildJsons = cachedJdaGuildJsons.get(api);
    HashMap<String, Consumer<Guild>> cachedGuildCallbacks = cachedJdaGuildCallbacks.get(api);

    JSONObject guildJson = cachedGuildJsons.remove(guildId);
    Consumer<Guild> secondPassCallback = cachedGuildCallbacks.remove(guildId);
    GuildImpl guildObj = (GuildImpl) api.getGuildMap().get(guildId);

    if (guildObj == null)
        throw new IllegalStateException(
                "Attempted to preform a second pass on an unknown Guild. Guild not in JDA "
                        + "mapping. GuildId: " + guildId);
    if (guildJson == null)
        throw new IllegalStateException(
                "Attempted to preform a second pass on an unknown Guild. No cached Guild "
                        + "for second pass. GuildId: " + guildId);
    if (secondPassCallback == null)
        throw new IllegalArgumentException("No callback provided for the second pass on the Guild!");

    for (JSONArray chunk : memberChunks) {
        createGuildMemberPass(guildObj, chunk);
    }//from w  ww . ja v a  2  s .c o  m

    User owner = api.getUserById(guildJson.getString("owner_id"));
    if (owner != null)
        guildObj.setOwner(owner);

    if (guildObj.getOwner() == null)
        JDAImpl.LOG.fatal("Never set the Owner of the Guild: " + guildObj.getId()
                + " because we don't have the owner User object! How?!");

    JSONArray channels = guildJson.getJSONArray("channels");
    createGuildChannelPass(guildObj, channels);

    secondPassCallback.accept(guildObj);
    GuildLock.get(api).unlock(guildId);
}

From source file:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java

protected void read(SelectionKey selectionKey, Consumer<List<String>> callback,
        Consumer<Exception> exceptionHandler) {
    try {/* w  w w. j  ava2  s . co  m*/
        if (!selectionKey.isValid() || !selectionKey.isReadable())
            return;
        byteBuffer.clear();
        int bytesRead = ((ReadableByteChannel) selectionKey.channel()).read(byteBuffer);
        if (bytesRead < 0) {
            LOG.warn(
                    "End of stream reached.  Deregistering interest in reads on the selection key invoking exception handler.");
            invokeExceptionHandler(selectionKey, exceptionHandler, new EOFException("End of stream"));
            return;
        }
        byteBuffer.flip();
        if (byteBuffer.remaining() + messageBuffer.size() > maxMessageSize) {
            LOG.error("Max message size of " + maxMessageSize
                    + " bytes exceeded.  Deregistering interest in reads on the selection key invoking exception handler.");
            invokeExceptionHandler(selectionKey, exceptionHandler,
                    new IllegalStateException("Max message size of " + maxMessageSize + " bytes exceeded"));
            return;
        }
        while (byteBuffer.hasRemaining())
            messageBuffer.write(byteBuffer.get());
        String messagesString = messageBuffer.toString(charset);
        messageBuffer.reset();
        List<String> messages = new ArrayList<>();
        for (String message : splitter.split(messagesString))
            messages.add(message);
        messageBuffer.write(messages.remove(messages.size() - 1).getBytes(charset));
        if (!messages.isEmpty()) {
            selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ);
            callback.accept(messages);
        }
    } catch (Exception e) {
        LOG.error("ReadDelimitedMessage task failed", e);
        invokeExceptionHandler(selectionKey, exceptionHandler, e);
    }
}

From source file:net.dv8tion.jda.core.entities.EntityBuilder.java

public void createGuildFirstPass(JSONObject guild, Consumer<Guild> secondPassCallback) {
    final long id = guild.getLong("id");
    GuildImpl guildObj = ((GuildImpl) api.getGuildMap().get(id));
    if (guildObj == null) {
        guildObj = new GuildImpl(api, id);
        api.getGuildMap().put(id, guildObj);
    }/*from  ww w  .  j  a  v  a2s  .  co m*/
    if (guild.has("unavailable") && guild.getBoolean("unavailable")) {
        guildObj.setAvailable(false);
        //This is used for when GuildCreateHandler receives a guild that is currently unavailable. During normal READY
        // loading for bots (which unavailable is always true) the secondPassCallback parameter will always
        // be null.
        if (secondPassCallback != null)
            secondPassCallback.accept(guildObj);
        api.getGuildLock().lock(id);
        return;
    }

    //If we make it to here, the Guild is available. This means 1 of 2 things:
    //Either:
    // 1) This is Guild provided during READY for a Client account
    // 2) This is a Guild received from GuildCreateHandler from a GUILD_CREATE event.
    //      This could be triggered by joining a guild or due to discord finally
    //      providing us with Guild information about a previously unavailable guild.
    //      Whether it was unavailable due to Bot READY unavailability or due to an
    //      outage within discord matters now.
    //
    // Either way, we now have enough information to fill in the general information about the Guild.
    // This does NOT necessarily mean that we have all information to complete the guild.
    // For Client accounts, we will also need to use op 12 (GUILD_SYNC) to get all presences of online users because
    // discord only provides Online users that we have an open PM channel with or are friends with for Client accounts.
    // On larger guilds we will still need to request all users using op 8 (GUILD_MEMBERS_CHUNK).
    //
    // The code below takes the information we -do- have and starts to fill in the Guild. It won't create anything
    // that might rely on Users that we don't have due to needing the GUILD_MEMBERS_CHUNK
    // This includes making VoiceStatus and PermissionOverrides

    guildObj.setAvailable(true).setIconId(guild.isNull("icon") ? null : guild.getString("icon"))
            .setSplashId(guild.isNull("splash") ? null : guild.getString("splash"))
            .setRegion(Region.fromKey(guild.getString("region"))).setName(guild.getString("name"))
            .setAfkTimeout(Guild.Timeout.fromKey(guild.getInt("afk_timeout")))
            .setVerificationLevel(Guild.VerificationLevel.fromKey(guild.getInt("verification_level")))
            .setDefaultNotificationLevel(
                    Guild.NotificationLevel.fromKey(guild.getInt("default_message_notifications")))
            .setRequiredMFALevel(Guild.MFALevel.fromKey(guild.getInt("mfa_level"))).setExplicitContentLevel(
                    Guild.ExplicitContentLevel.fromKey(guild.getInt("explicit_content_filter")));

    JSONArray roles = guild.getJSONArray("roles");
    for (int i = 0; i < roles.length(); i++) {
        Role role = createRole(roles.getJSONObject(i), guildObj.getIdLong());
        guildObj.getRolesMap().put(role.getIdLong(), role);
        if (role.getIdLong() == guildObj.getIdLong())
            guildObj.setPublicRole(role);
    }

    if (!guild.isNull("emojis")) {
        JSONArray array = guild.getJSONArray("emojis");
        TLongObjectMap<Emote> emoteMap = guildObj.getEmoteMap();
        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            JSONArray emoteRoles = object.getJSONArray("roles");
            final long emoteId = object.getLong("id");

            EmoteImpl emoteObj = new EmoteImpl(emoteId, guildObj);
            Set<Role> roleSet = emoteObj.getRoleSet();

            for (int j = 0; j < emoteRoles.length(); j++)
                roleSet.add(guildObj.getRoleById(emoteRoles.getString(j)));
            emoteMap.put(emoteId,
                    emoteObj.setName(object.getString("name")).setManaged(object.getBoolean("managed")));
        }
    }

    if (guild.has("members")) {
        JSONArray members = guild.getJSONArray("members");
        createGuildMemberPass(guildObj, members);
    }

    //This could be null for Client accounts. Will be fixed by GUILD_SYNC
    Member owner = guildObj.getMemberById(guild.getLong("owner_id"));
    if (owner != null)
        guildObj.setOwner(owner);

    if (guild.has("presences")) {
        JSONArray presences = guild.getJSONArray("presences");
        for (int i = 0; i < presences.length(); i++) {
            JSONObject presence = presences.getJSONObject(i);
            final long userId = presence.getJSONObject("user").getLong("id");
            MemberImpl member = (MemberImpl) guildObj.getMembersMap().get(userId);

            if (member == null)
                WebSocketClient.LOG.debug("Received a ghost presence in GuildFirstPass! Guild: " + guildObj
                        + " UserId: " + userId);
            else
                createPresence(member, presence);
        }
    }

    if (guild.has("channels")) {
        JSONArray channels = guild.getJSONArray("channels");

        for (int i = 0; i < channels.length(); i++) {
            JSONObject channel = channels.getJSONObject(i);
            ChannelType type = ChannelType.fromId(channel.getInt("type"));
            if (type == ChannelType.TEXT) {
                TextChannel newChannel = createTextChannel(channel, guildObj.getIdLong(), false);
                if (newChannel.getIdLong() == guildObj.getIdLong())
                    guildObj.setPublicChannel(newChannel);
            } else if (type == ChannelType.VOICE) {
                VoiceChannel newChannel = createVoiceChannel(channel, guildObj.getIdLong(), false);
                if (!guild.isNull("afk_channel_id")
                        && newChannel.getId().equals(guild.getString("afk_channel_id")))
                    guildObj.setAfkChannel(newChannel);
            } else
                WebSocketClient.LOG.fatal(
                        "Received a channel for a guild that isn't a text or voice channel. JSON: " + channel);
        }
    }

    //If the members that we were provided with (and loaded above) were not all of the
    //  the members in this guild, then we need to request more users from Discord using
    //  op 9 (GUILD_MEMBERS_CHUNK). To do so, we will cache the guild's JSON so we can properly
    //  load stuff that relies on Users like Channels, PermissionOverrides and VoiceStatuses
    //  after we have the rest of the users. We will request the GUILD_MEMBERS_CHUNK information
    //  which will be sent from discord over the main Websocket and will be handled by
    //  GuildMemberChunkHandler. After the handler has received all users as determined by the
    //  value set using `setExpectedGuildMembers`, it will do one of the following:
    //    1) If this is a Bot account, immediately call EntityBuilder#createGuildSecondPass, thus finishing
    //        the Guild object creation process.
    //    2) If this is a Client account, it will request op 12 (GUILD_SYNC) to make sure we have all information
    //        about online users as GUILD_MEMBERS_CHUNK does not include presence information, and when loading the
    //        members from GUILD_MEMBERS_CHUNK, we assume they are offline. GUILD_SYNC makes sure that we mark them
    //        properly. After GUILD_SYNC is received by GuildSyncHandler, it will call EntityBuilder#createGuildSecondPass
    //
    //If we actually -did- get all of the users needed, then we don't need to Chunk. Furthermore,
    // we don't need to use GUILD_SYNC because we always get presences with users thus we have all information
    // needed to guild the Guild. We will skip
    if (guild.getJSONArray("members").length() != guild.getInt("member_count")) {
        cachedGuildJsons.put(id, guild);
        cachedGuildCallbacks.put(id, secondPassCallback);

        GuildMembersChunkHandler handler = api.getClient().getHandler("GUILD_MEMBERS_CHUNK");
        handler.setExpectedGuildMembers(id, guild.getInt("member_count"));

        //If we are already past READY / RESUME, then chunk at runtime. Otherwise, pass back to the ReadyHandler
        // and let it send a burst chunk request.
        if (api.getClient().isReady()) {
            if (api.getAccountType() == AccountType.CLIENT) {
                JSONObject obj = new JSONObject().put("op", WebSocketCode.GUILD_SYNC).put("guild_id",
                        guildObj.getId());
                api.getClient().chunkOrSyncRequest(obj);
            }
            JSONObject obj = new JSONObject().put("op", WebSocketCode.MEMBER_CHUNK_REQUEST).put("d",
                    new JSONObject().put("guild_id", id).put("query", "").put("limit", 0));
            api.getClient().chunkOrSyncRequest(obj);
        } else {
            ReadyHandler readyHandler = api.getClient().getHandler("READY");
            readyHandler.acknowledgeGuild(guildObj, true, true, api.getAccountType() == AccountType.CLIENT);
        }

        api.getGuildLock().lock(id);
        return;
    }

    //As detailed in the comment above, if we've made it this far then we have all member information needed to
    // create the Guild. Thus, we fill in the remaining information, unlock the guild, and provide the guild
    // to the callback
    //This should only occur on small user count guilds.

    JSONArray channels = guild.getJSONArray("channels");
    createGuildChannelPass(guildObj, channels); //Actually creates PermissionOverrides

    JSONArray voiceStates = guild.getJSONArray("voice_states");
    createGuildVoiceStatePass(guildObj, voiceStates);

    api.getGuildLock().unlock(guildObj.getIdLong());
    if (secondPassCallback != null)
        secondPassCallback.accept(guildObj);
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private <E> void handleErrors(Iterator<E> iterator, Consumer<E> consumerMethod) {
    while (iterator.hasNext()) {
        E e = iterator.next();/* w ww .  j a  v a 2s  .c om*/
        iterator.remove();
        consumerMethod.accept(e);
    }
}

From source file:com.vmware.admiral.compute.container.HostContainerListDataCollection.java

private void createDiscoveredContainer(Consumer<Throwable> callback, AtomicInteger counter,
        ContainerState containerState) {
    logFine("Creating ContainerState for discovered container: %s", containerState.id);
    URI containerFactoryUri = UriUtils.buildUri(getHost(), ContainerFactoryService.class);
    sendRequest(OperationUtil.createForcedPost(containerFactoryUri).setBody(containerState)
            .setCompletion((o, ex) -> {
                if (ex != null) {
                    if (ex instanceof ServiceAlreadyStartedException) {
                        logWarning("Container state already exists for container (id=%s)", containerState.id);
                    } else {
                        logSevere("Failed to create ContainerState for discovered container (id=%s): %s",
                                containerState.id, ex.getMessage());
                        callback.accept(ex);
                        return;
                    }//from  w w  w  .j  a v  a  2  s .co  m
                } else {
                    logInfo("Created ContainerState for discovered container: %s", containerState.id);

                    // as soon as the ContainerService
                    // is started, its
                    // maintenance
                    // handler will be invoked to fetch
                    // up-to-date attributes
                }

                // Shouldn't create ContainerDescription
                // for system containers.
                String systemContainerName = matchSystemContainerName(
                        SystemContainerDescriptions.getSystemContainerNames(), containerState.names);

                if (systemContainerName == null) {
                    ContainerState body = o.getBody(ContainerState.class);
                    createDiscoveredContainerDescription(body);
                }

                if (counter.decrementAndGet() == 0) {
                    callback.accept(null);
                }
            }));
}

From source file:gedi.riboseq.inference.orf.OrfFinder.java

public MemoryIntervalTreeStorage<Orf> computeChunk(int index, ReferenceSequence ref, int start, int end,
        Consumer<ImmutableReferenceGenomicRegion<IntervalTreeSet<Codon>>> codonOutProc) { //DiskGenomicNumericBuilder codon, DiskGenomicNumericBuilder[] perCondCodon

    MutableMonad<ToDoubleFunction<Collection<Codon>>> gofComp = new MutableMonad<ToDoubleFunction<Collection<Codon>>>();
    ImmutableReferenceGenomicRegion<IntervalTreeSet<Codon>> codons = inference.inferCodons(reads, ref, start,
            end, maxAminoDist * 3, gofComp);

    if (codonOutProc != null)
        codonOutProc.accept(codons);

    //      if (codon!=null) {
    //         synchronized (codon) {
    //            float[] data = new float[3];
    //            for (Codon c : codons.getData()) {
    //               if (c.getTotalActivity()==0) continue;
    //               
    //               setRmq(codon, ref, 
    //                     codons.map(c.map(ref.getStrand().equals(Strand.Minus)?2:0)),0,
    //                     c.getTotalActivity(), data);
    //               setRmq(codon, ref, 
    //                     codons.map(c.map(1)),1,
    //                     c.getTotalActivity(), data);
    //               setRmq(codon, ref, 
    //                     codons.map(c.map(ref.getStrand().equals(Strand.Minus)?0:2)),2,
    //                     c.getTotalActivity(), data);
    //               
    ////               int genomic = codons.map(ref.getStrand().equals(Strand.Minus)?c.getStop():c.getStart());
    ////               data[genomic%3] = (float) c.getTotalActivity();
    ////               codon.addValueEx(ref, genomic, data); // FIX: spliced codons!
    ////               codon.addValueEx(ref, genomic+1, data);
    ////               codon.addValueEx(ref, genomic+2, data);
    ////               data[genomic%3] = 0;
    //            }            
    //         }//w w w .  j  a v  a 2s  .  c  o  m
    //      }
    //      
    //      if (perCondCodon!=null) {
    //         synchronized (perCondCodon) {
    //            float[] data = new float[3];
    //            for (int i=0; i<perCondCodon.length; i++) {
    //               for (Codon c : codons.getData()) {
    //                  if (c.getActivity()[i]==0) continue;
    //                  
    //                  setRmq(perCondCodon[i], ref, 
    //                        codons.map(c.map(ref.getStrand().equals(Strand.Minus)?2:0)),0,
    //                        c.getActivity()[i], data);
    //                  setRmq(perCondCodon[i], ref, 
    //                        codons.map(c.map(1)),1,
    //                        c.getActivity()[i], data);
    //                  setRmq(perCondCodon[i], ref, 
    //                        codons.map(c.map(ref.getStrand().equals(Strand.Minus)?0:2)),2,
    //                        c.getActivity()[i], data);
    //                  
    ////                  int genomic = codons.map(ref.getStrand().equals(Strand.Minus)?c.getStop():c.getStart());
    ////                  data[genomic%3] = (float) c.getActivity()[i];
    ////                  perCondCodon[i].addValueEx(ref, genomic, data);
    ////                  perCondCodon[i].addValueEx(ref, genomic+1, data);
    ////                  perCondCodon[i].addValueEx(ref, genomic+2, data);
    ////                  data[genomic%3] = 0;
    //               }
    //            }
    //         }
    //      }

    SpliceGraph sg = new SpliceGraph(0, end - start);

    CharSequence sequence = inference.getGenome().getSequence(codons);

    if (useReadSplits)
        reads.iterateIntersectingMutableReferenceGenomicRegions(ref, start, end)
                .forEachRemaining(read -> sg.addIntrons(codons.induce(read.getRegion())));
    annotation.iterateIntersectingMutableReferenceGenomicRegions(ref, start, end).forEachRemaining(tr -> {
        sg.addIntrons(codons.induce(tr.getRegion()));
    });

    if (!useReadSplits) {
        Iterator<Codon> it = codons.getData().iterator();
        while (it.hasNext()) {
            Codon c = it.next();
            for (int i = 1; i < c.getNumParts(); i++) {
                if (!sg.contains(c.getEnd(i - 1), c.getStart(i))) {
                    it.remove();
                    break;
                }
            }
        }
    }

    //      // codons region spans 1 - l-1
    //      double[] codTotal = new double[codons.getRegion().getTotalLength()+2];
    //      for (Codon c : codons.getData())
    //         codTotal[c.getStart()+1]+=c.getTotalActivity();

    RiboModel scoring = inference.getModels()[0];

    MemoryIntervalTreeStorage<Orf> re = new MemoryIntervalTreeStorage<Orf>(Orf.class);
    ArrayList<OrfWithCodons> orfs = findOrfs(index, sequence.toString(), sg, codons);

    // stitch orfs if all of them have a coverage of minStitchCoverage and are minStichDistance away from each other (and there is no stop codon...)
    tryToStitch(orfs, sg, sequence.toString());

    double totalClu = EI.wrap(codons.getData()).mapToDouble(m -> m.getTotalActivity()).sum();

    for (OrfWithCodons orf : orfs) {

        //         if (codons.map(orf.getRegion()).getStart()==143233)
        //            System.out.println(codons.map(orf.getRegion()));
        Orf oorf = orf.toOrf();
        oorf.clusterFraction = oorf.getActivityUnique() / totalClu;

        oorf.sequence = SequenceUtils.extractSequence(orf.getRegion(), sequence);

        oorf.hasStop = orf.hasStopCodon();

        oorf.startScores = new double[orf.getRegion().getTotalLength() / 3];
        oorf.changePointScores = new double[orf.getRegion().getTotalLength() / 3];
        double[][] accc = oorf.uniquePval < 0.01 ? oorf.estCodonsEach : oorf.estCodonsUnique;
        double[] ccc = null;
        for (int c = 0; c < accc.length; c++)
            ccc = ArrayUtils.add(ccc, accc[c]);
        double[] cccc = ccc.clone();
        ArrayUtils.cumSumInPlace(cccc, 1);

        for (int p = 0; p < accc[0].length; p++) {
            //            oorf.startScores[p] = scoring.computeStartScore(accc,p,accc[0].length-1, useSingleStartScores);
            if (!scoring.hasLfc())
                oorf.startScores[p] = scoring.computeSvmStartProbability(accc, p, accc[0].length - 1);
            oorf.changePointScores[p] = scoring.computeChangePointScore(ccc, p, ccc.length - 1);
        }

        if (scoring.hasLfc())
            oorf.startScores = scoring.computeSvmLfcProbabilities(accc);

        GenomicRegion eorf = orf.getRegion().extendFront(1).extendBack(1);
        double[] codTotal = new double[eorf.getTotalLength()];
        for (Codon c : codons.getData())
            if (eorf.containsUnspliced(c))
                codTotal[eorf.induce(c.getStart())] += c.getTotalActivity();

        BitVector disallowed = new BitVector(accc[0].length);
        oorf.inferredStartPosition = -1;
        boolean thisistheend = false;
        while (oorf.inferredStartPosition < 0 && !thisistheend) {

            int startCand = inferStart(oorf, ccc, cccc, disallowed, scoring.hasLfc());

            if (startCand == -1) {
                // try first and exit
                disallowed.clear();
                startCand = inferStart(oorf, ccc, cccc, disallowed, scoring.hasLfc());
                thisistheend = true;
            }

            if (startCand >= 0) {

                oorf.tmCov = NumericArrayFunction.trimmedMean(scoring.getTrim())
                        .applyAsDouble(NumericArray.wrap(ccc, startCand, ccc.length));//,ngaps,ccc.length));

                double[] sccc = ArrayUtils.slice(ccc, startCand, ccc.length);

                DoubleArrayList x = new DoubleArrayList(sccc.length);
                DoubleArrayList y = new DoubleArrayList(sccc.length);
                for (int i = 0; i < sccc.length; i++)
                    if (sccc[i] > scoring.getThreshold())
                        x.add(i);
                    else
                        y.add(i);
                double uniformity = x.isEmpty() || y.isEmpty() ? 1
                        : new MannWhitneyUTest().mannWhitneyUTest(x.toDoubleArray(), y.toDoubleArray());

                boolean stopPresent = sccc[sccc.length - 1] > scoring.getThreshold();
                Arrays.sort(sccc);
                int ngaps = 0;
                for (; ngaps < sccc.length && sccc[ngaps] <= scoring.getThreshold(); ngaps++)
                    ;

                //               double tmCov = NumericArrayFunction.trimmedMean(model.getTrim()).applyAsDouble(NumericArray.wrap(ccc,ngaps,ccc.length));
                double meanCov = ArrayUtils.sum(sccc) / sccc.length;

                int present = sccc.length - 1 - ngaps + (stopPresent ? 1 : 0);

                oorf.internalPval = scoring.computeErrorOrf(codTotal, startCand * 3 + 1, codTotal.length - 3);
                oorf.uniformityPval = uniformity;
                oorf.gapPval = (ngaps - 1.0) / (oorf.startScores.length - 1 - startCand) > scoring
                        .getGapThreshold(meanCov) ? 0 : 1;//getGapPvalue(oorf.startScores.length-1-startCand, meanCov, ngaps-1);
                oorf.presentPval = scoring.getPresentPvalue(sccc.length - 1, present);
                oorf.stopScore = scoring.computeStopScore(accc, startCand, accc[0].length - 1);

                double total = ArrayUtils.sum(sccc);
                boolean allok = //orf.getRegion().getTotalLength()/3-1-startCand>=minAaLength &&
                        total > minOrfTotalActivity && oorf.hasStop
                                && oorf.activityFraction > minIsoformFraction && oorf.tmCov > minTmCov
                                && (!filterByInternal || oorf.internalPval < 0.01);

                if (thisistheend && startCand >= 0 && total <= minOrfTotalActivity)
                    startCand = -1;

                if (allok || thisistheend)
                    oorf.inferredStartPosition = startCand;
                else
                    disallowed.putQuick(startCand, true);
            } else {
                oorf.tmCov = 0;
                oorf.internalPval = 1;
                oorf.presentPval = 1;
                oorf.gapPval = 1;
                oorf.stopScore = 0;
            }

        }

        if (oorf.inferredStartPosition > -1) {
            // recompute actitivies!
            oorf.activityUnique = ArrayUtils.sum(ccc, oorf.inferredStartPosition, ccc.length);
            for (int c = 0; c < oorf.estCodonsEach.length; c++)
                oorf.activities[c] = ArrayUtils.sum(oorf.estCodonsEach[c], oorf.inferredStartPosition,
                        oorf.estCodonsEach[c].length);
        }
        oorf.ri = 0;
        for (int c = 0; c < oorf.estCodonsEach.length; c++)
            if (oorf.activities[c] >= minOrfExperimentActivity)
                oorf.ri++;

        int bigger1 = 0;
        int missedgof = 0;
        double total = 0;
        ArrayList<Codon> orfCodons = new ArrayList<Codon>();
        for (Codon c : orf.getEstCodons())
            if (orf.getRegion().induce(c.getStart()) / 3 >= oorf.inferredStartPosition) {
                orfCodons.add(new Codon(codons.map(c), c));
                total += c.getTotalActivity();
                if (c.getTotalActivity() >= 1) {
                    bigger1++;
                    if (c.getGoodness() > scoring.getCodonGofThreshold(c.getTotalActivity()))
                        missedgof++;
                }
            }

        double gof = gofComp.Item.applyAsDouble(orfCodons);
        oorf.gof = Binomial.cumulative(missedgof, bigger1, 0.01, false, false);
        oorf.gof = gof > scoring.getOrfGofThreshold(total) ? 0 : 1;

        //         System.out.println(codons.map(orf.getRegion()));
        // odds scores are not filtered!
        oorf.passesAllFilters = orf.getRegion().getTotalLength() / 3 - 1
                - oorf.inferredStartPosition >= minAaLength && oorf.inferredStartPosition >= 0 && oorf.hasStop
                && oorf.activityFraction > minIsoformFraction && oorf.tmCov > minTmCov
                && (!filterByInternal || oorf.internalPval < 0.01) && (!filterByGap || oorf.gapPval > 0.01)
                && oorf.presentPval < 0.01 &&
                //               oorf.clusterFraction>minClusterFraction &&
                oorf.ri >= minRi
                && (!scoring.hasLfc() || oorf.startScores[oorf.inferredStartPosition] > inference.getModels()[0]
                        .getSvmLfcCutoff());

        double offframe = 0;
        double inframe = 0;

        ArrayGenomicRegion cds = orf.getRegion()
                .map(new ArrayGenomicRegion(oorf.inferredStartPosition * 3, orf.getRegion().getTotalLength()));
        for (Codon c : codons.getData().getIntervalsIntersecting(cds.getStart(), cds.getStop(),
                new ArrayList<Codon>())) {
            if (cds.containsUnspliced(c)) {
                int frame = cds.induce(c).getStart() % 3;
                if (frame == 0)
                    inframe += c.getTotalActivity();
                else
                    offframe += c.getTotalActivity();
            }
        }
        oorf.inframefraction = inframe / (inframe + offframe);

        ImmutableReferenceGenomicRegion<Orf> r = new ImmutableReferenceGenomicRegion<Orf>(ref,
                codons.map(orf.getRegion()), oorf);

        annotate(r);
        re.add(r);

        //         if (codOut!=null && r.getData().getOrfType()==OrfType.CDS) {
        //            double[] d = ArrayUtils.slice(codTotal, r.getData().getInferredStartPosition()*3+1, codTotal.length-1);
        //            try {
        //               codOut.writef("%s\t%s\t%.1f\t%s\n", r.getData().getReference().getData().getTranscriptId(),r.toLocationString(), r.getData().getActivityUnique(), StringUtils.concat(",", d));
        //            } catch (IOException e) {
        //               throw new RuntimeException("Could not write codons!",e);
        //            }
        //         }
    }

    return re;
}

From source file:org.geoserver.opensearch.rest.AbstractOpenSearchController.java

protected SimpleFeatureType mapFeatureTypeToSimple(FeatureType schema,
        Consumer<SimpleFeatureTypeBuilder> extraAttributeBuilder) {
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    for (PropertyDescriptor pd : schema.getDescriptors()) {
        // skip multivalue, metadata and quicklook
        final Name propertyName = pd.getName();
        if (pd.getMaxOccurs() > 1 || OpenSearchAccess.METADATA_PROPERTY_NAME.equals(propertyName)
                || OpenSearchAccess.QUICKLOOK_PROPERTY_NAME.equals(propertyName)
                || "htmlDescription".equalsIgnoreCase(propertyName.getLocalPart())
                || "id".equals(propertyName.getLocalPart())) {
            continue;
        }//from   w  w  w . ja v  a  2  s  .c  o  m
        Name name = propertyName;
        String uri = name.getNamespaceURI();
        String prefix = null;
        if (OpenSearchAccess.EO_NAMESPACE.equals(uri)) {
            prefix = "eo";
        } else {
            for (ProductClass pc : ProductClass.values()) {
                if (pc.getNamespace().equals(uri)) {
                    prefix = pc.getPrefix();
                    break;
                }
            }
        }
        String mappedName;
        if (prefix != null) {
            mappedName = prefix + ":" + name.getLocalPart();
        } else {
            mappedName = name.getLocalPart();
        }
        tb.userData(SOURCE_NAME, name);
        tb.add(mappedName, pd.getType().getBinding());
    }
    tb.setName(schema.getName());
    extraAttributeBuilder.accept(tb);
    SimpleFeatureType targetSchema = tb.buildFeatureType();
    return targetSchema;
}

From source file:org.jboss.pnc.environment.openshift.OpenshiftStartedEnvironment.java

private Runnable onEnvironmentInitComplete(Consumer<RunningEnvironment> onComplete, Selector selector) {
    return () -> {
        synchronized (this) {
            initialized.add(selector);/*from   w  ww. j  a  v a  2s . c o  m*/
            if (createRoute) {
                if (!initialized.containsAll(Arrays.asList(Selector.POD, Selector.SERVICE, Selector.ROUTE))) {
                    return;
                }
            } else {
                if (!initialized.containsAll(Arrays.asList(Selector.POD, Selector.SERVICE))) {
                    return;
                }
            }
        }

        logger.info("Environment successfully initialized. Pod [{}]; Service [{}].", pod.getName(),
                service.getName());
        if (createRoute) {
            logger.info("Route initialized [{}].", route.getName());
        }

        RunningEnvironment runningEnvironment = RunningEnvironment.createInstance(pod.getName(),
                Integer.parseInt(environmentConfiguration.getContainerPort()), route.getHost(),
                getPublicEndpointUrl(), getInternalEndpointUrl(), repositorySession,
                Paths.get(environmentConfiguration.getWorkingDirectory()), this::destroyEnvironment, debugData);

        gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_SUCCESS_KEY));
        onComplete.accept(runningEnvironment);
    };
}

From source file:com.evolveum.midpoint.model.common.stringpolicy.ValuePolicyProcessor.java

private <O extends ObjectType, R extends ObjectType> boolean checkProhibitedValues(String newPassword,
        ProhibitedValuesType prohibitedValuesType, AbstractValuePolicyOriginResolver<O> originResolver,
        Consumer<ProhibitedValueItemType> failAction, String shortDesc, Task task, OperationResult result)
        throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException,
        ConfigurationException, SecurityViolationException {

    if (prohibitedValuesType == null || originResolver == null) {
        return true;
    }/*from   w  ww.j a v  a  2  s.c o m*/

    MutableBoolean isAcceptable = new MutableBoolean(true);
    for (ProhibitedValueItemType prohibitedItemType : prohibitedValuesType.getItem()) {

        ItemPathType itemPathType = prohibitedItemType.getPath();
        if (itemPathType == null) {
            throw new SchemaException("No item path defined in prohibited item in " + shortDesc);
        }
        ItemPath itemPath = itemPathType.getItemPath();

        ResultHandler<R> handler = (object, objectResult) -> {

            PrismProperty<Object> objectProperty = object.findProperty(itemPath);
            if (objectProperty == null) {
                return true;
            }

            if (isMatching(newPassword, objectProperty)) {
                if (failAction != null) {
                    failAction.accept(prohibitedItemType);
                }
                isAcceptable.setValue(false);
                return false;
            }

            return true;
        };
        originResolver.resolve(handler, prohibitedItemType, shortDesc, task, result);
    }

    return isAcceptable.booleanValue();
}