Java 类org.apache.commons.lang3.tuple.Triple 实例源码

项目:nest-spider    文件:CommonSpiderService.java   
public ResultBundle<Map<String, Triple<SpiderInfo, JobKey, Trigger>>> listAllJobs() {
    Map<String, Triple<SpiderInfo, JobKey, Trigger>> result = new HashMap<>();
    for(JobKey key:manager.listAll(QUARTZ_JOB_GROUP_NAME)) {
        Pair<JobDetail, Trigger> pair = manager.findInfo(key);
        SpiderInfo info = (SpiderInfo)pair.getLeft().getJobDataMap().get("spiderInfo");
        result.put(info.getId(), Triple.of(info, key, pair.getRight()));
    }
    return builder.bundle(null, () -> result);
}
项目:smaph    文件:SmaphDebugger.java   
private JSONArray getAnnotatedSnippetS3(String query, WikipediaInterface wikiApi) throws JSONException, IOException {
    JSONArray res = new JSONArray();
    if (this.annotatedSnippetsAndBoldsS3.containsKey(query))
        for (Triple<String, HashSet<Annotation>, HashSet<Mention>> p : this.annotatedSnippetsAndBoldsS3.get(query)) {
            JSONObject pairJs = new JSONObject();
            res.put(pairJs);
            pairJs.put("snippet", p.getLeft());
            JSONArray annotationsJs = new JSONArray();
            pairJs.put("parts", annotationsJs);
            int lastIdx = 0;
            for (Annotation a : SmaphUtils.sorted(p.getMiddle())) {
                annotationsJs.put(getTextPartJson(p.getLeft(), lastIdx, a.getPosition(), p.getRight()));

                JSONObject annotationJs = getTextPartJson(p.getLeft(), a.getPosition(), a.getPosition() + a.getLength(),
                        p.getRight());
                annotationsJs.put(annotationJs);
                annotationJs.put("title", wikiApi.getTitlebyId(a.getConcept()));
                annotationJs.put("wid", a.getConcept());
                annotationJs.put("url", widToUrl(a.getConcept(), wikiApi));
                lastIdx = a.getPosition() + a.getLength();
            }
            annotationsJs.put(getTextPartJson(p.getLeft(), lastIdx, p.getLeft().length(), p.getRight()));
        }
    return res;
}
项目:smaph    文件:SmaphDebugger.java   
private JSONArray getEntityFeaturesJson(
        HashMap<String, List<Triple<Integer, HashMap<String, Double>, Boolean>>> source,
        String query, WikipediaInterface wikiApi) throws JSONException,
        IOException {
    JSONArray res = new JSONArray();
    if (source.containsKey(query))
        for (Triple<Integer, HashMap<String, Double>, Boolean> p : source
                .get(query)) {
            JSONObject pairJs = new JSONObject();
            res.put(pairJs);
            pairJs.put("wid", p.getLeft());
            pairJs.put("title", wikiApi.getTitlebyId(p.getLeft()));
            pairJs.put("url", widToUrl(p.getLeft(), wikiApi));
            JSONObject features = new JSONObject();
            pairJs.put("features", features);
            for (String ftrName : SmaphUtils.sorted(p.getMiddle().keySet()))
                features.put(ftrName, p.getMiddle().get(ftrName));
            pairJs.put("accepted", p.getRight());
        }
    return res;
}
项目:smaph    文件:SmaphDebugger.java   
private JSONArray getSourceSearchResultJson(
        HashMap<String, List<Triple<Integer, String, Integer>>> source,
        String query, WikipediaInterface wikiApi) throws JSONException, IOException {
    JSONArray res = new JSONArray();
    if (source.containsKey(query))
        for (Triple<Integer, String, Integer> t : source.get(query)) {
            JSONObject triple = new JSONObject();
            res.put(triple);
            triple.put("rank", t.getLeft());
            triple.put("wid", t.getRight());
            triple.put("title",
                    t.getRight() >= 0 ? wikiApi.getTitlebyId(t.getRight())
                            : "---not a wikipedia page---");
            triple.put("url", t.getMiddle());
        }
    return res;
}
项目:smaph    文件:SmaphUtils.java   
public static Triple<Double, Double, Double> getMinMaxAvg(List<Double> values) {
    if (values.isEmpty())
        return new ImmutableTriple<Double, Double, Double>(0.0, 0.0, 0.0);

    double minVal = Double.POSITIVE_INFINITY;
    double maxVal = Double.NEGATIVE_INFINITY;
    double avgVal = 0.0;
    for (double v : values) {
        minVal = Math.min(v, minVal);
        maxVal = Math.max(v, maxVal);
        avgVal += v / values.size();
    }

    return new ImmutableTriple<Double, Double, Double>(minVal, maxVal,
            avgVal);
}
项目:smaph    文件:EntityFeaturePack.java   
private static Triple<Double, Double, Double> getBoldsEDCapitalizedWordcount(String query, int rank, List<Pair<String, Integer>> websearchBolds){
    double minEdDist = 1.0;
    double capitalized = 0;
    double avgNumWords = 0;
    int boldsCount = 0;
    for (Pair<String, Integer> p : websearchBolds)
        if (p.second == rank) {
            boldsCount++;
            minEdDist = Math.min(minEdDist,
                    SmaphUtils.getMinEditDist(query, p.first));
            if (Character.isUpperCase(p.first.charAt(0)))
                capitalized++;
            avgNumWords += p.first.split("\\W+").length;
        }
    if (boldsCount != 0)
        avgNumWords /= boldsCount;
    return new ImmutableTriple<>(minEdDist, capitalized, avgNumWords);
}
项目:smaph    文件:SmaphAnnotator.java   
private List<Triple<Annotation, AnnotationFeaturePack, Boolean>> getAdvancedARToFtrsAndPresence(
        String query, QueryInformation qi,
        HashSet<Annotation> goldStandardAnn,
        MatchRelation<Annotation> annotationMatch) {

    List<Triple<Annotation, AnnotationFeaturePack, Boolean>> annAndFtrsAndPresence = new Vector<>();
    for (Annotation a : IndividualLinkback.getAnnotations(query,
            qi.allCandidates(), anchorMaxED, e2a, wikiApi)) {
        boolean inGold = false;
        for (Annotation goldAnn : goldStandardAnn)
            if (annotationMatch.match(goldAnn, a)) {
                inGold = true;
                break;
            }
        //if (e2a.containsId(a.getConcept())) {
            AnnotationFeaturePack features = new AnnotationFeaturePack(a, query, qi, wikiApi, wikiToFreeb, e2a);
            annAndFtrsAndPresence.add(new ImmutableTriple<Annotation, AnnotationFeaturePack, Boolean>(a, features, inGold));
        //} else
        //  LOG.warn("No anchors found for id={}", a.getConcept());
    }

    return annAndFtrsAndPresence;
}
项目:smaph    文件:SmaphAnnotator.java   
private List<Triple<HashSet<Annotation>, BindingFeaturePack, Double>> getLBBindingToFtrsAndF1(String query,
        QueryInformation qi, HashSet<Annotation> goldStandardAnn, MatchRelation<Annotation> match,
        Set<Tag> acceptedEntities, SmaphDebugger debugger) {

    Collection<Pair<HashSet<Annotation>, BindingFeaturePack>> bindingAndFeaturePacks = CollectiveLinkBack
            .getBindingFeaturePacks(query, acceptedEntities, qi, bg, wikiApi, wikiToFreeb, e2a, debugger);

    List<Triple<HashSet<Annotation>, BindingFeaturePack, Double>> res = new Vector<>();
    for (Pair<HashSet<Annotation>, BindingFeaturePack> bindingAndFeaturePack : bindingAndFeaturePacks) {
        HashSet<Annotation> binding = bindingAndFeaturePack.first;
        BindingFeaturePack bindingFeatures = bindingAndFeaturePack.second;

        Metrics<Annotation> m = new Metrics<>();
        float f1 = m.getSingleF1(goldStandardAnn, binding, match);

        res.add(new ImmutableTriple<HashSet<Annotation>, BindingFeaturePack, Double>(
                binding, bindingFeatures, (double) f1));
    }
    return res;
}
项目:smaph    文件:SmaphAnnotator.java   
public Pair<HashSet<ScoredAnnotation>, Integer> getLBUpperBound2(String query,
        HashSet<Annotation> goldStandardAnn, BindingGenerator bg, SmaphDebugger debugger)
                throws Exception {
    QueryInformation qi = getQueryInformation(query, debugger);
    List<Triple<HashSet<Annotation>, BindingFeaturePack, Double>> bindingToFtrsAndF1 = getLBBindingToFtrsAndF1(
            query, qi, goldStandardAnn, new StrongAnnotationMatch(
                    wikiApi), qi.allCandidates(), debugger);
    HashSet<Annotation> bestBinding = null;
    double bestF1 = Double.NEGATIVE_INFINITY;
    for (Triple<HashSet<Annotation>, BindingFeaturePack, Double> bindingAndFtrsAndF1 : bindingToFtrsAndF1) {
        double f1 = bindingAndFtrsAndF1.getRight();
        if (f1 > bestF1) {
            bestBinding = bindingAndFtrsAndF1.getLeft();
            bestF1 = f1;
        }
    }

    HashSet<ScoredAnnotation> bestBindingScored = new HashSet<>();
    for (Annotation a: bestBinding)
        bestBindingScored.add(new ScoredAnnotation(a.getPosition(), a.getLength(), a.getConcept(), 1.0f));
    return new Pair<HashSet<ScoredAnnotation>, Integer>(bestBindingScored,
            bindingToFtrsAndF1.size());
}
项目:smaph    文件:SmaphAnnotator.java   
public HashSet<ScoredAnnotation> getUpperBoundMentions(String query,
        HashSet<Annotation> goldStandardAnn, BindingGenerator bg, SmaphDebugger debugger)
                throws Exception {
    QueryInformation qi = getQueryInformation(query, debugger);
    List<Triple<HashSet<Annotation>, BindingFeaturePack, Double>> bindingToFtrsAndF1 = getLBBindingToFtrsAndF1(
            query, qi, goldStandardAnn,
            new StrongMentionAnnotationMatch(), qi.allCandidates(), debugger);
    HashSet<Annotation> bestBinding = null;
    double bestF1 = Double.NEGATIVE_INFINITY;
    for (Triple<HashSet<Annotation>, BindingFeaturePack, Double> bindingAndFtrsAndF1 : bindingToFtrsAndF1) {
        double f1 = bindingAndFtrsAndF1.getRight();
        if (f1 > bestF1) {
            bestBinding = bindingAndFtrsAndF1.getLeft();
            bestF1 = f1;
        }
    }

    if (bestBinding == null) return null;

    HashSet<ScoredAnnotation> bestBindingScored= new HashSet<>();
    for (Annotation a : bestBinding)
        bestBindingScored.add(new ScoredAnnotation(a.getPosition(), a.getLength(), a.getConcept(), 1.0f));
    return bestBindingScored;
}
项目:talchain    文件:PendingTxMonitor.java   
private void onPendingTransactionUpdate(TransactionReceipt txReceipt, EthereumListener.PendingTransactionState state, Block block) {
    byte[] txHash = txReceipt.getTransaction().getHash();
    Pair<Long, TransactionResultDTO> removed = remoteTxs.remove(txHash);
    if (state == EthereumListener.PendingTransactionState.DROPPED) {
        if (localTxs.remove(txHash) != null) {
            System.out.println("Dropped due to timeout (matchned: " + (removed != null) + "): " + Hex.toHexString(txHash));
        } else {
            if (remoteTxs.containsKey(txHash)) {
                System.err.println("Dropped but matching: "  + Hex.toHexString(txHash) + ": \n" + txReceipt);
            }
        }
    } else if (state == EthereumListener.PendingTransactionState.NEW_PENDING) {
        System.out.println("Local: " + Hex.toHexString(txHash));
        if (removed == null) {
            localTxs.put(txHash, Triple.of(System.currentTimeMillis(), txReceipt, state));
        } else {
            System.out.println("Tx matched: " + Hex.toHexString(txHash));
        }
    }
    checkUnmatched();
}
项目:talchain    文件:PendingStateTest.java   
@Test
public void testBlockOnlyIncluded() throws InterruptedException {
    StandaloneBlockchain bc = new StandaloneBlockchain();
    PendingListener l = new PendingListener();
    bc.addEthereumListener(l);
    Triple<TransactionReceipt, EthereumListener.PendingTransactionState, Block> txUpd = null;
    PendingStateImpl pendingState = (PendingStateImpl) bc.getBlockchain().getPendingState();

    ECKey alice = new ECKey();
    ECKey bob = new ECKey();

    bc.sendEther(bob.getAddress(), convert(100, ETHER));

    Block b1 = bc.createBlock();

    Transaction tx1 = bc.createTransaction(bob, 0, alice.getAddress(), BigInteger.valueOf(1000000), new byte[0]);
    bc.submitTransaction(tx1);
    Block b2 = bc.createBlock();

    Block b2_ = bc.createForkBlock(b1);
    Assert.assertTrue(l.getQueueFor(tx1).isEmpty());
    Block b3_ = bc.createForkBlock(b2_);
    txUpd = l.pollTxUpdate(tx1);
    Assert.assertEquals(txUpd.getMiddle(), EthereumListener.PendingTransactionState.PENDING);
}
项目:tokenapp-backend    文件:Etherscan.java   
public List<Triple<Date,Long,Long>> getTxEth(String address) throws IOException {
    String s = "https://"+url+"/api" +
            "?module=account" +
            "&action=txlist" +
            "&address=" + address +
            "&tag=latest" +
            "&apikey="+apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", options.getUserAgent());

    ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    TxReturnValue retVal = objectMapper.readValue(res.getBody(), TxReturnValue.class);

    List<Triple<Date,Long,Long>> ret = new ArrayList<>();
    for(TxReturnValue.Result result:retVal.result) {
        long time = Long.parseLong(result.timeStamp) * 1000;
        long value = Long.parseLong(result.value);
        long blocknr = Long.parseLong(result.blockNumber);
        ret.add(Triple.of(new Date(time), value, blocknr));
    }
    return ret;
}
项目:tokenapp-backend    文件:Blockr.java   
public List<Triple<Date, Long, Long>> getTxBtc(String address) throws ParseException, IOException {
    String s = "https://" + url + "/api/v1/address/txs/" + address + "?amount_format=string";

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", options.getUserAgent());

    ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    TxReturnValue retVal = objectMapper.readValue(res.getBody(), TxReturnValue.class);


    List<Triple<Date, Long, Long>> ret = new ArrayList<>();
    if (retVal.data.nbTxs != retVal.data.nbTxsDisplayed) {
        LOG.error("someone payed with over 200 tx, handle manually {}", address);
    }
    DateFormat m_ISO8601Local = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    for (TxReturnValue.Data.Tx result : retVal.data.txs) {
        Date time = m_ISO8601Local.parse(result.timeUtc);
        BigDecimal amount = new BigDecimal(result.amount).multiply(new BigDecimal(100_000_000));
        ret.add(Triple.of(time, amount.longValue(), getBlockNr(result.tx)));
    }
    return ret;
}
项目:saluki    文件:ConsulRegistryService.java   
private void processApplication(Map<String, Application> appCache,
                                Map.Entry<String, Pair<Set<GrpcHost>, Set<GrpcHost>>> entry) {
    Triple<String, String, String> appNameServiceVersion = getAppNameServiceVersion(entry.getKey());
    Pair<Set<GrpcHost>, Set<GrpcHost>> providerConsumer = entry.getValue();
    String appName = appNameServiceVersion.getLeft();
    String serviceName = appNameServiceVersion.getMiddle();
    String version = appNameServiceVersion.getRight();
    Application application = new Application(appName);
    GrpcService service = new GrpcService(appName, version, serviceName);
    if (providerConsumer.getLeft() != null) {
        service.addProviderHosts(providerConsumer.getLeft());
    }
    if (providerConsumer.getRight() != null) {
        service.addConsumerHosts(providerConsumer.getRight());
    }
    application.addService(service);
    if (appCache.get(application.getAppName()) == null) {
        appCache.put(application.getAppName(), application);
    } else {
        appCache.get(application.getAppName()).addServices(application.getServices());
    }
}
项目:saluki    文件:LimitAccessFilter.java   
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    String auth = request.getHeader("Authorization");
    String accessToken = auth.split(" ")[1];
    ctx.set("LimitAccess", Boolean.TRUE);
    try {
        Triple<Long, String, Long> clientTriple = databaseUserDetailService.loadClientByToken(accessToken);
        String user = clientTriple.getMiddle();
        Long intervalInMills = clientTriple.getLeft();
        Long limits = clientTriple.getRight();
        if (intervalInMills != null && intervalInMills != 0l && limits != null && limits != 0l) {
            if (!access(user, intervalInMills, limits)) {
                ctx.set("LimitAccess", Boolean.FALSE);
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(HttpServletResponse.SC_BAD_REQUEST);
                ctx.setResponseBody("The times of usage is limited");
            }
        }
    } catch (Throwable e) {
    }
    return null;
}
项目:Solar    文件:TileMechanicalTranslocator.java   
private void setRelativeState(Triple<IBlockState, EnumFacing, NBTTagCompound> data) {
    BlockPos pos = getPos().offset(getFacingLazy());
    IBlockState state = data.getLeft();
    EnumFacing from = data.getMiddle();
    EnumFacing to = getFacingLazy();
    if(state.getBlock().canPlaceBlockAt(world, pos)) {
        world.setBlockState(pos, getRotationState(state, from, to));
        getTile(TileEntity.class, world, pos).ifPresent(tile -> {
            NBTTagCompound tag = data.getRight();
            tag.setInteger("x", pos.getX());
            tag.setInteger("y", pos.getY());
            tag.setInteger("z", pos.getZ());
            tile.readFromNBT(tag);
        });
    }
}
项目:AppCoins-ethereumj    文件:PendingTxMonitor.java   
private void onPendingTransactionUpdate(TransactionReceipt txReceipt, EthereumListener.PendingTransactionState state, Block block) {
    byte[] txHash = txReceipt.getTransaction().getHash();
    Pair<Long, TransactionResultDTO> removed = remoteTxs.remove(txHash);
    if (state == EthereumListener.PendingTransactionState.DROPPED) {
        if (localTxs.remove(txHash) != null) {
            System.out.println("Dropped due to timeout (matchned: " + (removed != null) + "): " + Hex.toHexString(txHash));
        } else {
            if (remoteTxs.containsKey(txHash)) {
                System.err.println("Dropped but matching: "  + Hex.toHexString(txHash) + ": \n" + txReceipt);
            }
        }
    } else if (state == EthereumListener.PendingTransactionState.NEW_PENDING) {
        System.out.println("Local: " + Hex.toHexString(txHash));
        if (removed == null) {
            localTxs.put(txHash, Triple.of(System.currentTimeMillis(), txReceipt, state));
        } else {
            System.out.println("Tx matched: " + Hex.toHexString(txHash));
        }
    }
    checkUnmatched();
}
项目:AppCoins-ethereumj    文件:PendingStateTest.java   
@Test
public void testBlockOnlyIncluded() throws InterruptedException {
    StandaloneBlockchain bc = new StandaloneBlockchain();
    PendingListener l = new PendingListener();
    bc.addEthereumListener(l);
    Triple<TransactionReceipt, EthereumListener.PendingTransactionState, Block> txUpd = null;
    PendingStateImpl pendingState = (PendingStateImpl) bc.getBlockchain().getPendingState();

    ECKey alice = new ECKey();
    ECKey bob = new ECKey();

    bc.sendEther(bob.getAddress(), convert(100, ETHER));

    Block b1 = bc.createBlock();

    Transaction tx1 = bc.createTransaction(bob, 0, alice.getAddress(), BigInteger.valueOf(1000000), new byte[0]);
    bc.submitTransaction(tx1);
    Block b2 = bc.createBlock();

    Block b2_ = bc.createForkBlock(b1);
    Assert.assertTrue(l.getQueueFor(tx1).isEmpty());
    Block b3_ = bc.createForkBlock(b2_);
    txUpd = l.pollTxUpdate(tx1);
    Assert.assertEquals(txUpd.getMiddle(), PENDING);
}
项目:hiervis    文件:MeasureComputeThread.java   
/**
 * Posts a new task for the thread to process.
 * 
 * @param holder
 *            the result holder in which the measure result will be saved
 * @param hierarchy
 *            the hierarchy for which the measure is to be computed
 * @param task
 *            the task to post
 */
public void postTask( MeasureResultHolder holder, Hierarchy hierarchy, MeasureTask task )
{
    if ( holder == null ) {
        throw new IllegalArgumentException( "Holder must not be null!" );
    }
    if ( hierarchy == null ) {
        throw new IllegalArgumentException( "Hierarchy must not be null!" );
    }
    if ( task == null ) {
        throw new IllegalArgumentException( "Task must not be null!" );
    }

    Triple<MeasureResultHolder, Hierarchy, MeasureTask> arg = Triple.of( holder, hierarchy, task );

    lock.lock();
    try {
        tasks.add( arg );
    }
    finally {
        lock.unlock();
    }

    taskPosted.broadcast( Pair.of( hierarchy, task ) );
}
项目:ml_demo    文件:WDBCAutoencoder.java   
private void evaluate() {
    scoredTest = new ArrayList<>();

    // run through all example chunks
    for(int i = 0; i < featuresTest.size(); i++) {
        INDArray testData = featuresTest.get(i);
        INDArray labels = labelsTest.get(i);
        int nRows = testData.rows();

        // go through each example individually
        for(int j = 0; j < nRows; j++) {
            INDArray example = testData.getRow(j);
            int digit = (int)labels.getDouble(j);
            double score = net.score(new DataSet(example,example));
            scoredTest.add(new ImmutableTriple<Double, Integer, INDArray>(new Double(score), new Integer(digit), example));
        }
    }

    // sort for increasing score
    Collections.sort(scoredTest, new Comparator<Triple<Double, Integer, INDArray>>() {
        @Override
        public int compare(Triple<Double, Integer, INDArray> o1, Triple<Double, Integer, INDArray> o2) {
            return(o1.getLeft().compareTo(o2.getLeft()));
        }
    });
}
项目:Robocode    文件:SecurityConfig.java   
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
        throws AuthenticationException, InvalidTokenException {
    OAuth2Authentication authentication = super.loadAuthentication(accessToken);
    OAuth2Request request = authentication.getOAuth2Request();
    UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.class.cast(authentication.getUserAuthentication());
    Map<String, Object> map = Map.class.cast(token.getDetails());

    String id = map.getOrDefault("id", "").toString();
    Triple<OAuthSource, String, Integer> principal = Triple.of(source, id, null);
    Object credentials = token.getCredentials();
    List<GrantedAuthority> authorities = Lists.newArrayList(token.getAuthorities());

    OAuthUser user = this.repository.findBySourceAndId(source, id);
    if (user != null) {
        Assert.state(user.getUser() != null);
        principal = Triple.of(source, id, user.getUser().getId());
        authorities.add(new SimpleGrantedAuthority("ROLE_SU"));
    }

    token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
    token.setDetails(map);
    return new OAuth2Authentication(request, token);
}
项目:Robocode    文件:ConnectHandler.java   
public void onApplicationEvent(SessionConnectEvent event) {
    MessageHeaders headers = event.getMessage().getHeaders();
    String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
    Principal principal = SimpMessageHeaderAccessor.getUser(headers);
    if (principal == null) {
        return;
    }

    Assert.state(OAuth2Authentication.class.isInstance(principal));
    OAuth2Authentication authentication = OAuth2Authentication.class.cast(principal);
    Authentication token = authentication.getUserAuthentication();
    boolean isSu = this.hasRole(token.getAuthorities(), "ROLE_SU");
    if (!isSu) {
        return;
    }

    Triple<OAuthSource, String, Integer> sourceAndId = Triple.class.cast(token.getPrincipal());
    Assert.state(sourceAndId.getRight() != null);

    ActiveWebSocketUser activeUser = new ActiveWebSocketUser();
    activeUser.setSessionId(sessionId);
    activeUser.setConnectTime(LocalDateTime.now());
    activeUser.setUser(this.userRepository.findOne(sourceAndId.getRight()));
    this.activeWebSocketUserRepository.save(activeUser);
    this.messagingTemplate.convertAndSend("/su/connected", Lists.newArrayList(activeUser));
}
项目:CodeChickenLib    文件:SimpleBlockRenderer.java   
@Override
public List<BakedQuad> bakeQuads(EnumFacing face, IExtendedBlockState state) {
    BakingVertexBuffer buffer = BakingVertexBuffer.create();
    Triple<Integer, Integer, UVTransformation> worldData = getWorldTransforms(state);
    CCRenderState ccrs = CCRenderState.instance();
    ccrs.reset();
    ccrs.startDrawing(0x7, DefaultVertexFormats.ITEM, buffer);
    models[worldData.getLeft()][worldData.getMiddle()].render(ccrs, worldData.getRight());
    buffer.finishDrawing();
    List<BakedQuad> quads = buffer.bake();
    if (face == null && !shouldCull()) {
        return quads;
    } else if (face != null) {
        return VertexDataUtils.sortFaceData(quads).get(face);
    }
    return ImmutableList.of();
}
项目:CodeChickenLib    文件:SimpleBlockRenderer.java   
@Override
public List<BakedQuad> bakeItemQuads(EnumFacing face, ItemStack stack) {
    BakingVertexBuffer buffer = BakingVertexBuffer.create();
    Triple<Integer, Integer, UVTransformation> worldData = getItemTransforms(stack);
    CCRenderState ccrs = CCRenderState.instance();
    ccrs.reset();
    ccrs.startDrawing(0x7, DefaultVertexFormats.ITEM, buffer);
    models[worldData.getLeft()][worldData.getMiddle()].render(ccrs, worldData.getRight());
    buffer.finishDrawing();
    List<BakedQuad> quads = buffer.bake();

    if (face == null && !shouldCull()) {
        return quads;
    } else if (face != null) {
        return VertexDataUtils.sortFaceData(quads).get(face);
    }
    return ImmutableList.of();
}
项目:Rapture    文件:PluginSandboxItem.java   
public static Pair<RaptureURI, String> calculateURI(String leafTail) {
    String variant = (leafTail.startsWith(CONTENTDIR)) ? null : extractVariant(leafTail);
    Triple<String, String, Scheme> trip = extractScheme(leafTail.substring(variantLength(variant)));
    checkArgument(trip != null, "extraneuous file");
    RaptureURI uri = null;
    switch (trip.getRight()) {
    case USER:
    case ENTITLEMENTGROUP:
        if (trip.getLeft().indexOf("/") == -1) {
            uri = new RaptureURI(trip.getLeft(), trip.getRight());
        }
        break;
    default:
        break;
    }
    if (uri == null) {
        uri = RaptureURI.createFromFullPathWithAttribute(trip.getLeft(), trip.getMiddle(), trip.getRight());
    }
    return new ImmutablePair<RaptureURI, String>(uri, variant);
}
项目:MrGerkins    文件:GithubUtils.java   
/**
 * Get list of Pull requests that we merged after last tag
 *
 * @param repoFullName
 * @throws HttpException
 * @throws IOException
 */
public List<Triple<String, String, String>> getListOfMergedPRs(String repoFullName, String headTag)
        throws HttpException, IOException {
    GithubRelease releaseResponse = githubClientWrapper.getLatestRelease(repoFullName);
    GithubCompareTag compareTagResponse = githubClientWrapper.compareCommitTags(repoFullName, releaseResponse.getTagName(),
            headTag);

    Pattern pattern = Pattern.compile(MERGE_PULL_REQUEST_MSG_REGEX);

    List<GithubCommitRecord> commitRecords = compareTagResponse.getCommits();

    //Triple <PR#>
    List<Triple<String, String, String>> prList = new ArrayList<>();

    for (GithubCommitRecord commitRecord : commitRecords) {
        String message = commitRecord.getCommit().getMessage();
        Matcher matcher = pattern.matcher(message);
        if (matcher.matches() && matcher.groupCount() == 3) {
            prList.add(Triple.of(matcher.group(1), matcher.group(2), matcher.group(3)));
        }
    }
    return prList;
}
项目:MrGerkins    文件:GithubUtils.java   
/**
 * repofullname -> ex: Payments-R/paymentapiplatformserv
 */
public void generateReleaseNotes(String repoFullName, String branch, String releaseVersion) throws HttpException,
        IOException {

    /**
     * get all the commits after last release tag
     */
    List<Triple<String, String, String>> mergedPRs = getListOfMergedPRs(repoFullName, branch);
    StringBuilder notes = new StringBuilder("## ").append(repoFullName).append(" &nbsp;&nbsp;&nbsp;&nbsp; v")
            .append(releaseVersion).append("\n### Changes \n");

    // Each line of release notes will be of form : <a href = "PR link"> #PR-number </a> Title of PR
    mergedPRs.forEach(
            pr -> notes.append("\n* [#").append(pr.getLeft()).append("](").append(githubConfig.getHomepageUrl())
                    .append(repoFullName).append("/pull/").append(pr.getLeft()).append(")&nbsp;&nbsp;&nbsp;&nbsp;")
                    .append(pr.getRight()));

    updateFileInRepo(repoFullName, RELEASE_NOTES_FILE_PATH, notes.toString(), branch);
}
项目:KaellyBot    文件:JobUser.java   
/**
 * Ajoute à la base de donnée l'objet si celui-ci n'y est pas déjà.
 */
public synchronized void addToDatabase(){

    if (! getJobs().containsKey(Triple.of(idUser, server, job)) && level > 0) {
        getJobs().put(Triple.of(idUser, server, job), this);
        Connexion connexion = Connexion.getInstance();
        Connection connection = connexion.getConnection();

        try {
            PreparedStatement preparedStatement = connection.prepareStatement(
                    "INSERT INTO Job_User(name_job, id_user, server_dofus, level) VALUES(?, ?, ?, ?);");
            preparedStatement.setString(1, job.getName());
            preparedStatement.setString(2, String.valueOf(idUser));
            preparedStatement.setString(3, server.getName());
            preparedStatement.setInt(4, level);

            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            ClientConfig.setSentryContext(ClientConfig.DISCORD().getGuildByID(idUser),
                    ClientConfig.DISCORD().getUserByID(idUser), null,null);
            LOG.error(e.getMessage());
        }
    }
}
项目:KaellyBot    文件:JobUser.java   
private static synchronized Map<Triple<Long, ServerDofus, Job>, JobUser> getJobs(){
    if(jobs == null){
        jobs = new ConcurrentHashMap<>();
        Connexion connexion = Connexion.getInstance();
        Connection connection = connexion.getConnection();

        try {
            PreparedStatement query = connection.prepareStatement(
                    "SELECT id_user, server_dofus, name_job, level FROM Job_User;");
            ResultSet resultSet = query.executeQuery();

            while (resultSet.next()) {
                Long idUser = resultSet.getLong("id_user");
                ServerDofus server = ServerDofus.getServersMap().get(resultSet.getString("server_dofus"));
                Job job = Job.getJob(resultSet.getString("name_job"));
                int level = resultSet.getInt("level");
                jobs.put(Triple.of(idUser, server, job), new JobUser(idUser, server, job, level));
            }
        } catch (SQLException e) {
            ClientConfig.setSentryContext(null, null, null,null);
            LOG.error(e.getMessage());
        }
    }

    return jobs;
}
项目:fili    文件:RoleDimensionApiFilterRequestMapper.java   
/**
 * For a set of ApiFilters collect by dimension, field and operation, and union their value sets.
 *
 * @param filterStream  Stream of ApiFilters whose values are to be unioned
 *
 * @return A set of filters with the same operations but values unioned
 */
protected static Set<ApiFilter> unionMergeFilterValues(Stream<ApiFilter> filterStream) {

    Function<ApiFilter, Triple<Dimension, DimensionField, FilterOperation>> filterGroupingIdentity = filter ->
        new ImmutableTriple<>(filter.getDimension(), filter.getDimensionField(), filter.getOperation());

    Map<Triple<Dimension, DimensionField, FilterOperation>, Set<String>> filterMap =
            filterStream.collect(Collectors.groupingBy(
                    filterGroupingIdentity::apply,
                    Collectors.mapping(
                            ApiFilter::getValues,
                            Collectors.reducing(Collections.emptySet(), StreamUtils::setMerge)
                    )
            ));

    return filterMap.entrySet().stream()
            .map(it -> new ApiFilter(
                    it.getKey().getLeft(),
                    it.getKey().getMiddle(),
                    it.getKey().getRight(),
                    it.getValue()
            ))
            .collect(Collectors.toSet());
}
项目:app-framework    文件:PluginManagerServiceImpl.java   
/**
 * Parse the whole list of plugins and check if some are auto-register.<br/>
 * If yes creates the corresponding {@link PluginConfiguration} instance
 */
private void createAutoRegisterPluginConfigurations() {
    log.info("Checking auto-register plugins");
    Map<String, Triple<Boolean, IExtension, IPluginDescriptor>> extensionPlugins = getExtensionPlugins();
    for (String identifier : extensionPlugins.keySet()) {
        IPluginDescriptor descriptor = extensionPlugins.get(identifier).getRight();
        if (log.isDebugEnabled()) {
            log.debug("Plugin " + identifier + " auto-register : " + descriptor.autoRegister());
        }
        if (descriptor.autoRegister()) {
            PluginConfiguration pluginConfiguration = PluginConfiguration.find.where().eq("pluginDefinition.identifier", identifier).findUnique();
            if (log.isDebugEnabled()) {
                log.debug("Plugin " + identifier + " auto-register with "
                        + (pluginConfiguration == null ? "no plugin configuration (need to create one)" : "an existing plugin configuration"));
            }
            if (pluginConfiguration == null) {
                pluginConfiguration = new PluginConfiguration();
                pluginConfiguration.isAutostart = true;
                pluginConfiguration.name = descriptor.getName();
                pluginConfiguration.pluginDefinition = PluginDefinition.getPluginDefinitionFromIdentifier(identifier);
                pluginConfiguration.save();
                log.info("Plugin configuration created for auto-register plugin " + identifier);
            }
        }
    }
}
项目:lambda4j    文件:TriBooleanToDoubleFunction.java   
/**
 * Returns a memoized (caching) version of this {@link TriBooleanToDoubleFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code TriBooleanToDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default TriBooleanToDoubleFunction memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Boolean, Boolean, Boolean>, Double> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (TriBooleanToDoubleFunction & Memoized) (value1, value2, value3) -> {
            final double returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3),
                                                    key -> applyAsDouble(key.getLeft(), key.getMiddle(),
                                                                         key.getRight()));
            }
            return returnValue;
        };
    }
}
项目:lambda4j    文件:ThrowableCharTernaryOperator.java   
/**
 * Returns a memoized (caching) version of this {@link ThrowableCharTernaryOperator}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>
 * Unless the operator and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableCharTernaryOperator}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized operator, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized operator can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableCharTernaryOperator<X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Character, Character, Character>, Character> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableCharTernaryOperator<X> & Memoized) (value1, value2, value3) -> {
            final char returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3), ThrowableFunction.of(
                        key -> applyAsCharThrows(key.getLeft(), key.getMiddle(), key.getRight())));
            }
            return returnValue;
        };
    }
}
项目:lambda4j    文件:ThrowableBiObjIntToCharFunction.java   
/**
 * Returns a memoized (caching) version of this {@link ThrowableBiObjIntToCharFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableBiObjIntToCharFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableBiObjIntToCharFunction<T, U, X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Integer>, Character> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableBiObjIntToCharFunction<T, U, X> & Memoized) (t, u, value) -> {
            final char returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value), ThrowableFunction.of(
                        key -> applyAsCharThrows(key.getLeft(), key.getMiddle(), key.getRight())));
            }
            return returnValue;
        };
    }
}
项目:lambda4j    文件:ThrowableTriByteToShortFunction.java   
/**
 * Returns a memoized (caching) version of this {@link ThrowableTriByteToShortFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableTriByteToShortFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableTriByteToShortFunction<X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Byte, Byte, Byte>, Short> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableTriByteToShortFunction<X> & Memoized) (value1, value2, value3) -> {
            final short returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3), ThrowableFunction.of(
                        key -> applyAsShortThrows(key.getLeft(), key.getMiddle(), key.getRight())));
            }
            return returnValue;
        };
    }
}
项目:lambda4j    文件:ThrowableObjBiByteToShortFunction.java   
/**
 * Returns a memoized (caching) version of this {@link ThrowableObjBiByteToShortFunction}. Whenever it is called,
 * the mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableObjBiByteToShortFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableObjBiByteToShortFunction<T, X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, Byte, Byte>, Short> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableObjBiByteToShortFunction<T, X> & Memoized) (t, value1, value2) -> {
            final short returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, value1, value2), ThrowableFunction.of(
                        key -> applyAsShortThrows(key.getLeft(), key.getMiddle(), key.getRight())));
            }
            return returnValue;
        };
    }
}
项目:lambda4j    文件:ThrowableBiObjByteToDoubleFunction.java   
/**
 * Returns a memoized (caching) version of this {@link ThrowableBiObjByteToDoubleFunction}. Whenever it is called,
 * the mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableBiObjByteToDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableBiObjByteToDoubleFunction<T, U, X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<T, U, Byte>, Double> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableBiObjByteToDoubleFunction<T, U, X> & Memoized) (t, u, value) -> {
            final double returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(t, u, value), ThrowableFunction.of(
                        key -> applyAsDoubleThrows(key.getLeft(), key.getMiddle(), key.getRight())));
            }
            return returnValue;
        };
    }
}
项目:lambda4j    文件:ShortTernaryOperator.java   
/**
 * Returns a memoized (caching) version of this {@link ShortTernaryOperator}. Whenever it is called, the mapping
 * between the input parameters and the return value is preserved in a cache, making subsequent calls returning the
 * memoized value instead of computing the return value again.
 * <p>
 * Unless the operator and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ShortTernaryOperator}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized operator, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized operator can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ShortTernaryOperator memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Short, Short, Short>, Short> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ShortTernaryOperator & Memoized) (value1, value2, value3) -> {
            final short returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3),
                                                    key -> applyAsShort(key.getLeft(), key.getMiddle(),
                                                                        key.getRight()));
            }
            return returnValue;
        };
    }
}
项目:lambda4j    文件:ThrowableTriIntToShortFunction.java   
/**
 * Returns a memoized (caching) version of this {@link ThrowableTriIntToShortFunction}. Whenever it is called, the
 * mapping between the input parameters and the return value is preserved in a cache, making subsequent calls
 * returning the memoized value instead of computing the return value again.
 * <p>
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code ThrowableTriIntToShortFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default ThrowableTriIntToShortFunction<X> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Integer, Integer, Integer>, Short> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (ThrowableTriIntToShortFunction<X> & Memoized) (value1, value2, value3) -> {
            final short returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3), ThrowableFunction.of(
                        key -> applyAsShortThrows(key.getLeft(), key.getMiddle(), key.getRight())));
            }
            return returnValue;
        };
    }
}