Example usage for com.google.common.collect Table put

List of usage examples for com.google.common.collect Table put

Introduction

In this page you can find the example usage for com.google.common.collect Table put.

Prototype

@Nullable
V put(R rowKey, C columnKey, V value);

Source Link

Document

Associates the specified value with the specified keys.

Usage

From source file:au.com.permeance.liferay.portlet.controller.SamplePortletController.java

@RenderMapping
public String handleViewPage(final RenderRequest request, final ModelMap model,
        @RequestParam(defaultValue = "-1") final String recordSetIdParam,
        @RequestParam(required = false) final String columnName) throws Exception {
    log.info("In View");

    long recordSetId = Long.parseLong(recordSetIdParam);
    DDLRecordSet recordSet = lookupTable(request);
    if (recordSetId == -1) {
        if (recordSet != null) {
            recordSetId = recordSet.getRecordSetId();
        }//from   www  . j  a va2  s.co  m
    }

    if (recordSetId > 0) {

        List<DDLRecord> records = getRecords(request, recordSet, columnName);
        Table<Long, String, String> recordTable = HashBasedTable.create(records.size(), 7);

        long rowIdCounter = 0;
        for (DDLRecord record : records) {
            Fields fields = record.getFields();
            long rowId = rowIdCounter++;
            for (com.liferay.portlet.dynamicdatamapping.storage.Field field : fields) {
                String name = field.getName();
                String value = field.getValue(Locale.US).toString();

                recordTable.put(rowId, name, value);

            }
        }
        model.addAttribute("recordTable", recordTable);
    }

    model.addAttribute("recordSetId", recordSetId);

    // Limit the number of rows to display.
    model.addAttribute("displayRows", Arrays.asList(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L));

    return "view";
}

From source file:com.shazam.fork.reporter.FlakinessSorter.java

private List<UnsortedPoolHistory> reduceToUnsortedHistories(List<Execution> executionsList, List<Build> builds,
        Set<TestLabel> testLabels, Set<String> poolNames) {
    HashMap<String, Table<TestLabel, Build, TestInstance>> poolToFlakinessTableMap = new HashMap<>();
    for (Execution execution : executionsList) {
        String buildId = execution.getBuildId();
        String buildLink = buildLinkCreator.createLink(buildId);
        Build build = aBuild().withBuildId(buildId).withLink(buildLink).build();
        builds.add(build);/*  w  w  w .ja  v a2s.  c  om*/

        List<PoolSummary> poolSummaries = execution.getSummary().getPoolSummaries();
        for (PoolSummary poolSummary : poolSummaries) {
            String poolName = poolSummary.getPoolName();
            poolNames.add(poolName);
            Table<TestLabel, Build, TestInstance> table = getOrCreateTable(poolToFlakinessTableMap, poolName);
            for (TestResult testResult : poolSummary.getTestResults()) {
                TestLabel testLabel = testLabel().withClassName(testResult.getTestClass())
                        .withMethod(testResult.getTestMethod()).build();
                testLabels.add(testLabel);

                TestInstance testInstance = testInstance().withResultStatusFrom(testResult).withLink(
                        testLinkCreator.createLinkToTest(buildLink, poolSummary.getPoolName(), testLabel))
                        .build();
                table.put(testLabel, build, testInstance);
            }
        }
    }

    return poolToFlakinessTableMap.entrySet().stream()
            .map(entry -> new UnsortedPoolHistory(entry.getKey(), entry.getValue())).collect(toList());
}

From source file:org.age.util.fsm.StateMachineServiceBuilder.java

/**
 * Builds the transitions table./*from  w  ww  . jav  a2  s  .c  o  m*/
 *
 * @return an immutable transitions table.
 */
@NonNull
Table<S, E, TransitionDescriptor<S, E>> buildTransitionsTable() {
    final EnumSet<S> allStates = EnumSet.allOf(stateClass);
    final EnumSet<E> allEvents = EnumSet.allOf(eventClass);
    final Table<S, E, TransitionDescriptor<S, E>> table = ArrayTable.create(allStates, allEvents);

    for (final S state : allStates) {
        for (final E event : allEvents) {
            table.put(state, event, TransitionDescriptor.nullDescriptor());
        }
    }

    for (final S state : allStates) {
        noStateTransitions.forEach((event, targetStates) -> {
            final TransitionDescriptor<S, E> descriptor = new TransitionDescriptor<>(state, event, targetStates,
                    noStateActions.get(event));
            table.put(state, event, descriptor);
        });
        transitions.row(state).forEach((event, targetStates) -> {
            if (isNull(targetStates)) {
                return;
            }
            final TransitionDescriptor<S, E> descriptor = new TransitionDescriptor<>(state, event, targetStates,
                    actions.get(state, event));
            table.put(state, event, descriptor);
        });
    }

    if (log.isDebugEnabled()) {
        table.values().forEach(descriptor -> {
            if (nonNull(descriptor.initial())) {
                log.debug("New transition: {}.", descriptor);
            }
        });
    }

    return ImmutableTable.copyOf(table);
}

From source file:com.netease.flume.taildirSource.ReliableTaildirEventReader.java

/**
 * Create a ReliableTaildirEventReader to watch the given directory.
 *//*from ww w .  j a v a 2  s .c o  m*/
private ReliableTaildirEventReader(Map<String, String> filePaths, Map<String, String> targetFilenames,
        Table<String, String, String> headerTable, String positionFilePath, boolean skipToEnd,
        boolean addByteOffset) throws IOException {
    // Sanity checks
    Preconditions.checkNotNull(filePaths);
    Preconditions.checkNotNull(positionFilePath);

    if (logger.isDebugEnabled()) {
        logger.debug("Initializing {} with directory={}, metaDir={}",
                new Object[] { ReliableTaildirEventReader.class.getSimpleName(), filePaths });
    }

    Table<String, File, Pattern> tailFileTable = HashBasedTable.create();
    for (Entry<String, String> e : filePaths.entrySet()) {
        File f = new File(e.getValue());
        File parentDir = f.getParentFile();
        Preconditions.checkState(parentDir.exists(),
                "Directory does not exist: " + parentDir.getAbsolutePath());
        Pattern fileNamePattern = Pattern.compile(f.getName());
        tailFileTable.put(e.getKey(), parentDir, fileNamePattern);
    }
    logger.info("tailFileTable: " + tailFileTable.toString());
    logger.info("headerTable: " + headerTable.toString());

    this.targetFilenames = targetFilenames;
    this.tailFileTable = tailFileTable;
    this.headerTable = headerTable;
    this.addByteOffset = addByteOffset;
    updateTailFiles(skipToEnd);

    logger.info("Updating position from position file: " + positionFilePath);
    loadPositionFile(positionFilePath);
}

From source file:librec.undefined.FUSTauc.java

@Override
protected void initModel() throws Exception {
    P = new DenseMatrix(numUsers, numFactors);
    Y = new DenseMatrix(numUsers, numFactors);
    Q = new DenseMatrix(numUsers, numFactors);

    P.init(0.01);// www . j a  v  a 2  s  .  com
    Y.init(0.01);
    Q.init(0.01);

    itemBias = new DenseVector(numItems);
    itemBias.init(0.01);

    rho = cf.getInt("FISM.rho");
    alpha = cf.getFloat("FISM.alpha");

    regBeta = cf.getFloat("FISM.reg.beta");
    regGamma = cf.getFloat("FISM.reg.gamma");

    // new social matrix S with trust propagation, i.e., friends of friends
    Table<Integer, Integer, Double> data = socialMatrix.getDataTable();

    for (int u = 0; u < numUsers; u++) {
        SparseVector Tu = socialMatrix.row(u);

        for (VectorEntry ve : Tu) {
            int v = ve.index(); // v as a trusted neighbor
            SparseVector Tv = socialMatrix.row(v); // v's trusted neighbors
            for (VectorEntry ve2 : Tv) {
                int k = ve2.index();
                if (!Tu.contains(k))
                    data.put(u, k, 0.5); // add as a trusted neighbor of
                                         // user u
            }
        }
    }

    S = new SparseMatrix(numUsers, numUsers, data);
}

From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.SparqlLogicConceptMatcher.java

/**
 * Obtains all the matching resources that have a MatchType with the URIs of {@code origin} of the type provided (inclusive) or more.
 *
 * @param origins URIs to match/* w w  w  . j av a  2s .c om*/
 * @param minType the minimum MatchType we want to obtain
 * @return a {@link com.google.common.collect.Table} with the result of the matching indexed by origin URI and then destination URI.
 */
@Override
public Table<URI, URI, MatchResult> listMatchesAtLeastOfType(Set<URI> origins, MatchType minType) {
    Table<URI, URI, MatchResult> matchTable = HashBasedTable.create();
    Stopwatch w = new Stopwatch();
    for (URI origin : origins) {
        w.start();
        Map<URI, MatchResult> result = listMatchesAtLeastOfType(origin, minType);
        for (Map.Entry<URI, MatchResult> dest : result.entrySet()) {
            matchTable.put(origin, dest.getKey(), dest.getValue());
        }
        log.debug("Computed matched types for {} in {}. {} total matches.", origin, w.stop().toString(),
                result.size());
        w.reset();
    }
    return matchTable;

    //        return obtainMatchResults(origins, minType, this.getMatchTypesSupported().getHighest()); // TODO: Use the proper implementation for this
}

From source file:structure.matrix.SparseMatrix.java

public static SparseMatrix readMatrix(String filePath) throws IOException {
    // Table {row-id, col-id, rate}
    Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
    // Map {col-id, multiple row-id}: used to fast build a rating matrix
    Multimap<Integer, Integer> colMap = HashMultimap.create();

    BufferedReader br = FileIO.getReader(filePath);
    br.readLine();/*from w w w  .j  av  a2 s.  com*/
    String line = br.readLine();
    String[] terms = line.trim().split("[ \t,]+");
    int Nu = Integer.parseInt(terms[0]);
    int Nv = Integer.parseInt(terms[1]);
    while ((line = br.readLine()) != null) {
        String[] data = line.trim().split("[ \t,]+");
        int user = Integer.parseInt(data[0]) - 1;
        int item = Integer.parseInt(data[1]) - 1;
        Double rate = Double.parseDouble(data[2]);
        dataTable.put(user, item, rate);
        colMap.put(item, user);
    }
    br.close();
    // build rating matrix
    SparseMatrix mat = new SparseMatrix(Nu, Nv, dataTable, colMap);
    dataTable = null;
    return mat;
}

From source file:su.opencode.shuffler.MarkovBuildingVisitor.java

private void processName(String s, Table<String, String, Integer> chainTable) {
    if (StringUtils.isBlank(s))
        return;//ww  w .ja v  a  2s. c o  m
    String[] parts = StringUtils.splitByCharacterTypeCamelCase(s);

    String from = "";
    String to = "";

    for (int i = 0; i <= parts.length; i++) {
        to = (i == parts.length ? "" : parts[i].toLowerCase());
        if (NON_ALPHA_PATTERN.matcher(to).find()) {
            continue;
        }
        synchronized (chainTable) {
            Integer counter = chainTable.get(from, to);
            if (counter == null) {
                counter = 1;
            } else {
                counter++;
            }
            chainTable.put(from, to, counter);
        }
        from = to;
    }
}

From source file:net.librec.data.splitter.LOOCVDataSplitter.java

/**
 * Split ratings into two parts where the last user according to date is
 * preserved as the test set and the remaining data as the training set.
 *//*  www .j  a v  a 2s.  c o m*/
public void getLOOByUserDate() {
    trainMatrix = new SparseMatrix(preferenceMatrix);
    Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
    Multimap<Integer, Integer> colMap = HashMultimap.create();

    for (int u = 0, um = preferenceMatrix.numRows(); u < um; u++) {
        List<Integer> items = preferenceMatrix.getColumns(u);
        int i = -1;

        List<RatingContext> rcs = new ArrayList<>();
        for (int j : items) {
            rcs.add(new RatingContext(u, j, (long) datetimeMatrix.get(u, j)));
        }
        Collections.sort(rcs);
        i = rcs.get(rcs.size() - 1).getItem();
        trainMatrix.set(u, i, 0);
        dataTable.put(u, i, preferenceMatrix.get(u, i));
        colMap.put(i, u);
    }
    SparseMatrix.reshape(trainMatrix);
    testMatrix = new SparseMatrix(preferenceMatrix.numRows(), preferenceMatrix.numColumns(), dataTable, colMap);
}

From source file:net.librec.data.splitter.LOOCVDataSplitter.java

/**
 * Split ratings into two parts where the last item according to date is
 * preserved as the test set and the remaining data as the training set.
 *//*from   w  ww . j  av  a 2s .c  o m*/
public void getLooByItemsDate() {
    trainMatrix = new SparseMatrix(preferenceMatrix);

    Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
    Multimap<Integer, Integer> colMap = HashMultimap.create();

    for (int i = 0, im = preferenceMatrix.numColumns(); i < im; i++) {
        List<Integer> users = preferenceMatrix.getRows(i);
        int u = -1;

        List<RatingContext> rcs = new ArrayList<>();
        for (int v : users) {
            rcs.add(new RatingContext(v, i, (long) datetimeMatrix.get(v, i)));
        }
        Collections.sort(rcs);
        u = rcs.get(rcs.size() - 1).getUser();

        trainMatrix.set(u, i, 0);
        dataTable.put(u, i, preferenceMatrix.get(u, i));
        colMap.put(i, u);
    }

    SparseMatrix.reshape(trainMatrix);
    testMatrix = new SparseMatrix(preferenceMatrix.numRows(), preferenceMatrix.numColumns(), dataTable, colMap);
}