private XYZDataset createDataSet(HashBasedTable<String, String, Double> data) {

    MatrixSeries series =
        new MatrixSeries(
            "DataTable", roomToCodeMapping.keySet().size(), roomToCodeMapping.keySet().size());

    for (String source : roomToCodeMapping.keySet()) {
      Integer sourceId = roomToCodeMapping.get(source);

      for (String destination : roomToCodeMapping.keySet()) {

        Integer destinationId = roomToCodeMapping.get(destination);
        if (!data.contains(source, destination)) {
          series.update(sourceId, destinationId, -1.0);
        } else {
          double value;
          if (type == MarkovDataDialog.HeatMapType.COMPARISON)
            value = (data.get(source, destination) + 1.0) / 2; // Scale to 0 to 1 for comparison
          else value = data.get(source, destination);
          if (value < 0 || value > 1) {
            System.out.println(
                "***********Problem in value=" + value + "(" + source + "," + destination + ")");
          }
          series.update(sourceId, destinationId, value);
        }
      }
    }

    System.out.println("Room size = " + roomToCodeMapping.keySet().size());
    return new MatrixSeriesCollection(series);
  }
예제 #2
0
  private static ArrayList<String> printData(HashBasedTable<String, String, Double> tbl1) {

    // lstOut = output data
    // sbl1 = current line
    // rgs1 = list of row ids
    // rgs2 = list of headers

    ArrayList<String> lstOut;
    StringBuilder sbl1;
    String rgs1[];
    String rgs2[];

    lstOut = new ArrayList<String>();
    rgs1 = tbl1.rowKeySet().toArray(new String[tbl1.rowKeySet().size()]);
    rgs2 = new String[rgs1.length];
    for (int i = 0; i < rgs1.length; i++) {
      rgs2[i] = (new File(rgs1[i])).getName();
    }
    lstOut.add("SampleID" + "," + Joiner.on(",").join(rgs2));
    for (String s : tbl1.columnKeySet()) {
      sbl1 = new StringBuilder();
      sbl1.append(s);
      for (int i = 0; i < rgs1.length; i++) {
        sbl1.append("," + tbl1.get(rgs1[i], s));
      }
      lstOut.add(sbl1.toString());
    }
    return lstOut;
  }
 @Test
 public void calculateWeight_WeightsCalculated_WeightsCorrect() {
   for (Integer i : tblWeight.rowKeySet()) {
     for (Integer j : tblWeight.columnKeySet()) {
       assertEquals(tblWeight.get(i, j), spw1.getWeight(spw1.getEdge(i, j)), 0.0000001);
     }
   }
 }
예제 #4
0
  /**
   * Copy Constructor
   *
   * @param other an another intersection
   */
  public Intersection(Intersection other) {

    super(other);
    this.nb_ways = HashBasedTable.create(other.nb_ways);
    this.ways_size = HashBasedTable.create(other.ways_size);
    this.conflict_zone_size = new HashMap<>(other.conflict_zone_size);
    this.indonesian_cross = other.indonesian_cross;

    // Initialize conflict zone, trajectories and sizes
    update();
  }
예제 #5
0
  @Test
  public void testHashBasedTable() {
    HashBasedTable<Integer, Integer, String> table = HashBasedTable.create();

    for (int row = 0; row < 5; row++) {
      for (int column = 0; column < 10; column++) {
        table.put(row, column, row + "_" + column);
      }
    }

    System.out.println(table.rowMap().toString());
  }
  private void handleIncomingConfirmableCoapRequest(ChannelHandlerContext ctx, MessageEvent me) {
    InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress();
    CoapMessage coapMessage = (CoapMessage) me.getMessage();

    IncomingReliableMessageExchange newMessageExchange =
        new IncomingReliableMessageExchange(remoteEndpoint, coapMessage.getMessageID());

    IncomingMessageExchange oldMessageExchange =
        ongoingMessageExchanges.get(remoteEndpoint, coapMessage.getMessageID());

    // Check if there is an ongoing
    if (oldMessageExchange != null) {

      if (oldMessageExchange instanceof IncomingReliableMessageExchange) {

        // if the old message exchange is reliable and the empty ACK was already sent send another
        // empty ACK
        if (((IncomingReliableMessageExchange) oldMessageExchange).isAcknowledgementSent())
          writeEmptyAcknowledgement(remoteEndpoint, coapMessage.getMessageID());

      }

      // if the old message was unreliable and the duplicate message is confirmable send empty ACK
      else writeEmptyAcknowledgement(remoteEndpoint, coapMessage.getMessageID());

      // As the message is already being processed there is nothing more to do
      return;
    }

    // try to add new reliable message exchange
    boolean added = false;
    synchronized (monitor) {
      Long time = System.currentTimeMillis() + MIN_EMPTY_ACK_DELAY_MILLIS;

      // Add message exchange to set of ongoing exchanges to detect duplicates
      if (!ongoingMessageExchanges.contains(remoteEndpoint, coapMessage.getMessageID())) {
        ongoingMessageExchanges.put(remoteEndpoint, coapMessage.getMessageID(), newMessageExchange);
        added = true;
      }

      // If the scheduling of the empty ACK does not work then it was already scheduled
      if (!emptyAcknowledgementSchedule.put(time, newMessageExchange)) {
        log.error("Could not schedule empty ACK for message: {}", coapMessage);
        ongoingMessageExchanges.remove(remoteEndpoint, coapMessage.getMessageID());
        added = false;
      }
    }

    // everything is fine, so further process message
    if (added) ctx.sendUpstream(me);
  }
  private Table<String, MetricDto, MeasureDto> searchMeasuresByComponentUuidAndMetric(
      DbSession dbSession,
      ComponentDto baseComponent,
      List<ComponentDto> components,
      List<MetricDto> metrics,
      List<WsMeasures.Period> periods,
      @Nullable Long developerId) {
    List<String> componentUuids = new ArrayList<>();
    componentUuids.add(baseComponent.uuid());
    components.stream().forEach(c -> componentUuids.add(c.uuid()));

    Map<Integer, MetricDto> metricsById = Maps.uniqueIndex(metrics, MetricDtoFunctions.toId());
    MeasureQuery measureQuery =
        MeasureQuery.builder()
            .setPersonId(developerId)
            .setComponentUuids(componentUuids)
            .setMetricIds(metricsById.keySet())
            .build();
    List<MeasureDto> measureDtos = dbClient.measureDao().selectByQuery(dbSession, measureQuery);

    Table<String, MetricDto, MeasureDto> measuresByComponentUuidAndMetric =
        HashBasedTable.create(components.size(), metrics.size());
    for (MeasureDto measureDto : measureDtos) {
      measuresByComponentUuidAndMetric.put(
          measureDto.getComponentUuid(), metricsById.get(measureDto.getMetricId()), measureDto);
    }

    addBestValuesToMeasures(measuresByComponentUuidAndMetric, components, metrics, periods);

    return measuresByComponentUuidAndMetric;
  }
예제 #8
0
파일: MergeOp.java 프로젝트: web1992/gerrit
  private BatchMetaDataUpdate saveToBatch(
      ChangeControl ctl,
      ChangeUpdate callerUpdate,
      LabelNormalizer.Result normalized,
      Timestamp timestamp)
      throws IOException {
    Table<Account.Id, String, Optional<Short>> byUser = HashBasedTable.create();
    for (PatchSetApproval psa : normalized.updated()) {
      byUser.put(psa.getAccountId(), psa.getLabel(), Optional.of(psa.getValue()));
    }
    for (PatchSetApproval psa : normalized.deleted()) {
      byUser.put(psa.getAccountId(), psa.getLabel(), Optional.<Short>absent());
    }

    BatchMetaDataUpdate batch = callerUpdate.openUpdate();
    for (Account.Id accountId : byUser.rowKeySet()) {
      if (!accountId.equals(callerUpdate.getUser().getAccountId())) {
        ChangeUpdate update =
            updateFactory.create(ctl.forUser(identifiedUserFactory.create(accountId)), timestamp);
        update.setSubject("Finalize approvals at submit");
        putApprovals(update, byUser.row(accountId));

        CommitBuilder commit = new CommitBuilder();
        commit.setCommitter(new PersonIdent(serverIdent, timestamp));
        batch.write(update, commit);
      }
    }

    putApprovals(callerUpdate, byUser.row(callerUpdate.getUser().getAccountId()));
    return batch;
  }
예제 #9
0
    public Matrix(final String one, final String two) {
      this.one = one;
      this.two = two;
      this.width = one.length();
      this.height = two.length();
      this.matrix = HashBasedTable.create(this.width, this.height);

      for (int i = 0; i <= this.width; i++) {
        put(i, 0, i);
      }
      for (int j = 0; j <= this.height; j++) {
        put(0, j, j);
      }

      final int lenOne = this.width;
      final int lenTwo = this.height;
      for (int i = 1; i <= lenOne; i++) {
        final int firstIndex = i - 1;
        for (int j = 1; j <= lenTwo; j++) {
          final int secondIndex = j - 1;
          final char alpha = two.charAt(secondIndex);
          final char beta = one.charAt(firstIndex);

          final int cost = alpha == beta ? 0 : 1;
          final int firstDistance = get(firstIndex, j) + 1;
          final int secondDistance = get(i, secondIndex) + 1;
          final int d1 = Math.min(firstDistance, secondDistance);
          final int diagonalCost = get(firstIndex, secondIndex);
          final int d2 = diagonalCost + cost;
          put(i, j, Math.min(d1, d2));
        }
      }
    }
예제 #10
0
  @Test
  public void thatImportedDartsContainNoClones() {
    when(dartsService.getDartsTable()).thenReturn(HashBasedTable.<String, String, Dart>create());
    when(dartsExtractor.extract(inputStream)).thenReturn(createExpectedDartsWithClones());
    defaultDartsImporter.importDarts(inputStream);

    verify(dartsService).saveAll(createExpectedDarts());
  }
예제 #11
0
 private void readObject(java.io.ObjectInputStream stream)
     throws IOException, ClassNotFoundException {
   doReadObject(stream);
   copied = new HashMap<>();
   pointersToContexts = HashBasedTable.create();
   ref = new WeakReference<DataBuffer>(this, Nd4j.bufferRefQueue());
   freed = new AtomicBoolean(false);
 }
 private void handleApplicationShutdown(ChannelHandlerContext ctx, MessageEvent me) {
   synchronized (monitor) {
     this.shutdown = true;
     emptyAcknowledgementSchedule.clear();
     ongoingMessageExchanges.clear();
   }
   ctx.sendDownstream(me);
 }
예제 #13
0
/** PolicySet that ind */
public class AsuBasePolicySet extends PolicySet<HmpUserDetails, DocumentAction, Object> {

  private Table<DocumentAction, DocumentStatus, PolicySet> policySetsByActionAndStatus =
      HashBasedTable.create();

  public AsuBasePolicySet() {
    super(Targets.anyTarget(), PolicyCombiningAlgorithms.onlyOneApplicable());

    for (DocumentAction action : DocumentAction.values()) {
      for (DocumentStatus status : DocumentStatus.values()) {
        policySetsByActionAndStatus.put(
            action,
            status,
            new PolicySet(
                targetForActionAndStatus(action, status), AsuPolicyCombiningAlgorithm.instance()));
      }
    }
  }

  public void addPolicy(AsuPolicy policy) {
    getPolicySet(policy.getAction(), policy.getStatus()).addPolicy(policy);
    super.addPolicy(policy);
  }

  public void addPolicySet(AsuPolicySet policySet) {
    getPolicySet(policySet.getAction(), policySet.getStatus()).addPolicySet(policySet);
    super.addPolicySet(policySet);
  }

  public PolicySet getPolicySet(DocumentAction action, String status) {
    return getPolicySet(action, DocumentStatus.forName(status));
  }

  public PolicySet getPolicySet(DocumentAction action, DocumentStatus status) {
    return policySetsByActionAndStatus.get(action, status);
  }

  @Override
  public AuthorizationDecision evaluate(
      DecisionRequest<HmpUserDetails, DocumentAction, Object> request) {
    try {
      String status = Document.getStatusName(request.getResource());
      PolicySet policySet = getPolicySet(request.getAction(), status);
      AuthorizationDecision decision = policySet.evaluate(request);
      return decision;
    } catch (MissingAttributeException e) {
      return AuthorizationDecision.valueOf(this, e);
    }
  }

  public static ITarget<HmpUserDetails, DocumentAction, Document> targetForActionAndStatus(
      DocumentAction action, DocumentStatus status) {
    return Targets.with(
        Targets.anySubjects(HmpUserDetails.class),
        Targets.equalTo(action),
        new AsuTarget.DocumentStatusMatcher(status));
  }
}
예제 #14
0
  private UIStyleFamily buildFamily(String family, UISkin skin) {
    UIStyleFamily baseFamily = skin.getFamily(family);
    UIStyle baseStyle = new UIStyle(skin.getDefaultStyleFor(family));
    if (!family.isEmpty()) {
      UIStyleFragment fragment = baseStyles.get(family);
      fragment.applyTo(baseStyle);
    }

    Set<StyleKey> inheritedStyleKey = Sets.newLinkedHashSet();
    for (Class<? extends UIWidget> widget : baseFamily.getWidgets()) {
      inheritedStyleKey.add(new StyleKey(widget, "", ""));
      for (String part : baseFamily.getPartsFor(widget)) {
        inheritedStyleKey.add(new StyleKey(widget, part, ""));
        for (String mode : baseFamily.getModesFor(widget, part)) {
          inheritedStyleKey.add(new StyleKey(widget, part, mode));
        }
      }
    }

    Map<Class<? extends UIWidget>, Table<String, String, UIStyle>> familyStyles = Maps.newHashMap();
    Map<StyleKey, UIStyleFragment> styleLookup = elementStyles.row(family);
    Map<StyleKey, UIStyleFragment> baseStyleLookup =
        (family.isEmpty()) ? Maps.<StyleKey, UIStyleFragment>newHashMap() : elementStyles.row("");
    for (StyleKey styleKey :
        Sets.union(Sets.union(styleLookup.keySet(), baseStyleKeys), inheritedStyleKey)) {
      UIStyle elementStyle =
          new UIStyle(baseSkin.getStyleFor(family, styleKey.element, styleKey.part, styleKey.mode));
      baseStyles.get("").applyTo(elementStyle);
      baseStyles.get(family).applyTo(elementStyle);
      List<Class<? extends UIWidget>> inheritanceTree =
          ReflectionUtil.getInheritanceTree(styleKey.element, UIWidget.class);
      applyStylesForInheritanceTree(
          inheritanceTree, "", "", elementStyle, styleLookup, baseStyleLookup);

      if (!styleKey.part.isEmpty()) {
        applyStylesForInheritanceTree(
            inheritanceTree, styleKey.part, "", elementStyle, styleLookup, baseStyleLookup);
      }

      if (!styleKey.mode.isEmpty()) {
        applyStylesForInheritanceTree(
            inheritanceTree,
            styleKey.part,
            styleKey.mode,
            elementStyle,
            styleLookup,
            baseStyleLookup);
      }

      Table<String, String, UIStyle> elementTable = familyStyles.get(styleKey.element);
      if (elementTable == null) {
        elementTable = HashBasedTable.create();
        familyStyles.put(styleKey.element, elementTable);
      }
      elementTable.put(styleKey.part, styleKey.mode, elementStyle);
    }
    return new UIStyleFamily(baseStyle, familyStyles);
  }
예제 #15
0
  /** @return the data table of this matrix as (row, column, value) cells */
  public Table<Integer, Integer, Double> getDataTable() {
    Table<Integer, Integer, Double> res = HashBasedTable.create();

    for (MatrixEntry me : this) {
      if (me.get() != 0) res.put(me.row(), me.column(), me.get());
    }

    return res;
  }
 public SupervisorEmpGroup(SupervisorEmpGroup supEmpGroup) {
   if (supEmpGroup != null) {
     this.supervisorId = supEmpGroup.supervisorId;
     this.startDate = supEmpGroup.getStartDate();
     this.endDate = supEmpGroup.getEndDate();
     this.primaryEmployees = new HashMap<>(supEmpGroup.getPrimaryEmployees());
     this.overrideEmployees = new HashMap<>(supEmpGroup.getOverrideEmployees());
     this.supOverrideEmployees = HashBasedTable.create(supEmpGroup.supOverrideEmployees);
   }
 }
  @Test
  public void whenCreateTable_thenCreated() {
    final Table<String, String, Integer> distance = HashBasedTable.create();
    distance.put("London", "Paris", 340);
    distance.put("New York", "Los Angeles", 3940);
    distance.put("London", "New York", 5576);

    assertEquals(3940, distance.get("New York", "Los Angeles").intValue());
    assertThat(distance.columnKeySet(), containsInAnyOrder("Paris", "New York", "Los Angeles"));
    assertThat(distance.rowKeySet(), containsInAnyOrder("London", "New York"));
  }
  @Test
  public void whenTransposeTable_thenCorrect() {
    final Table<String, String, Integer> distance = HashBasedTable.create();
    distance.put("London", "Paris", 340);
    distance.put("New York", "Los Angeles", 3940);
    distance.put("London", "New York", 5576);

    final Table<String, String, Integer> transposed = Tables.transpose(distance);
    assertThat(transposed.rowKeySet(), containsInAnyOrder("Paris", "New York", "Los Angeles"));
    assertThat(transposed.columnKeySet(), containsInAnyOrder("London", "New York"));
  }
예제 #19
0
 @Test
 public void testTable() {
   HashBasedTable<Integer, Integer, Integer> table = HashBasedTable.create();
   table.put(1, 1, 1);
   table.put(1, 2, 2);
   table.put(1, 3, 3);
   table.put(2, 1, 4);
   table.put(2, 2, 5);
   table.put(2, 3, 6);
   assert table.containsRow(1);
   assert table.containsColumn(2);
   assert table.row(1).get(3) == 3;
 }
예제 #20
0
/**
 * This class represents a virtual CPU, which is a CPU running on a guest. It associates the guest
 * CPU ID to a virtual machine of the model.
 *
 * @author Geneviève Bastien
 */
public class VirtualCPU {

  private static final Table<VirtualMachine, Long, VirtualCPU> VIRTUAL_CPU_TABLE =
      NonNullUtils.checkNotNull(HashBasedTable.<VirtualMachine, Long, VirtualCPU>create());

  private final VirtualMachine fVm;
  private final Long fCpuId;

  /**
   * Return the virtual CPU for to the virtual machine and requested CPU ID
   *
   * @param vm The virtual machine
   * @param cpu the CPU number
   * @return the virtual CPU
   */
  public static synchronized VirtualCPU getVirtualCPU(VirtualMachine vm, Long cpu) {
    VirtualCPU ht = VIRTUAL_CPU_TABLE.get(vm, cpu);
    if (ht == null) {
      ht = new VirtualCPU(vm, cpu);
      VIRTUAL_CPU_TABLE.put(vm, cpu, ht);
    }
    return ht;
  }

  private VirtualCPU(VirtualMachine vm, Long cpu) {
    fVm = vm;
    fCpuId = cpu;
  }

  /**
   * Get the CPU ID of this virtual CPU
   *
   * @return The zero-based CPU ID
   */
  public Long getCpuId() {
    return fCpuId;
  }

  /**
   * Get the virtual machine object this virtual CPU belongs to
   *
   * @return The guest Virtual Machine
   */
  public VirtualMachine getVm() {
    return fVm;
  }

  @Override
  public String toString() {
    return "VirtualCPU: [" + fVm + ',' + fCpuId + ']'; // $NON-NLS-1$
  }
}
  /**
   * @param executorService the {@link ScheduledExecutorService} to provide the threads that execute
   *     the operations for reliability.
   */
  public IncomingMessageReliabilityHandler(ScheduledExecutorService executorService) {
    this.shutdown = false;
    this.emptyAcknowledgementSchedule =
        TreeMultimap.create(
            Ordering.<Long>natural(), Ordering.<IncomingReliableMessageExchange>arbitrary());

    this.ongoingMessageExchanges = HashBasedTable.create();

    executorService.scheduleAtFixedRate(
        new ReliabilityTask(),
        RELIABILITY_TASK_PERIOD_MILLIS,
        RELIABILITY_TASK_PERIOD_MILLIS,
        TimeUnit.MILLISECONDS);
  }
예제 #22
0
  /** @return the transpose of current matrix */
  public SparseMatrix transpose() {
    if (isCCSUsed) {
      SparseMatrix tr = new SparseMatrix(numColumns, numRows);

      tr.copyCRS(this.rowData, this.rowPtr, this.colInd);
      tr.copyCCS(this.colData, this.colPtr, this.rowInd);

      return tr;
    } else {
      Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
      for (MatrixEntry me : this) dataTable.put(me.column(), me.row(), me.get());
      return new SparseMatrix(numColumns, numRows, dataTable);
    }
  }
  private static class ProductAssociativityGraph {
    private final Table<Vertex, Vertex, Edge> graph = HashBasedTable.create();

    public static ProductAssociativityGraph create() {
      return new ProductAssociativityGraph();
    }

    public void addAssociation(Vertex v1, Vertex v2, int edgeWeight) {
      if (containsAssociation(v1, v2)) {
        Edge edge = getAssociationWeight(v1, v2);
        edge.addWeight(edgeWeight);
      } else {
        graph.put(v1, v2, new Edge(edgeWeight));
      }
    }

    public Edge getAssociationWeight(Vertex v1, Vertex v2) {
      Edge edge = graph.get(v1, v2);
      if (edge == null) {
        edge = graph.get(v2, v1);
      }
      return edge;
    }

    public List<Vertex> getProductAssociations(Vertex v) {
      Map<Vertex, Edge> adjacent = Maps.newHashMap(graph.row(v));
      adjacent.putAll(graph.column(v));

      return adjacent
          .entrySet()
          .stream()
          .sorted((e1, e2) -> e2.getValue().weight - e1.getValue().weight)
          .map(Map.Entry::getKey)
          .collect(Collectors.toList());
    }

    public boolean containsAssociation(Vertex v1, Vertex v2) {
      return graph.contains(v1, v2) || graph.contains(v2, v1);
    }

    public void clear() {
      graph.clear();
    }

    @Override
    public String toString() {
      return "ProductAssociativityGraph{" + "graph=" + graph + '}';
    }
  }
 /**
  * Filter out any employees in this Supervisor emp group that are not under this supervisor during
  * the given dateRange.
  *
  * @param dateRange Range<LocalDate>
  */
 public void filterActiveEmployeesByDate(Range<LocalDate> dateRange) {
   this.setPrimaryEmployees(
       this.getPrimaryEmployees()
           .values()
           .stream()
           .filter(supInfo -> isSupInfoInRange(supInfo, dateRange))
           .collect(Collectors.toMap(EmployeeSupInfo::getEmpId, Function.identity())));
   this.setOverrideEmployees(
       this.getOverrideEmployees()
           .values()
           .stream()
           .filter(supInfo -> isSupInfoInRange(supInfo, dateRange))
           .collect(Collectors.toMap(EmployeeSupInfo::getEmpId, Function.identity())));
   HashBasedTable<Integer, Integer, EmployeeSupInfo> filteredSupOverrideEmps =
       HashBasedTable.create();
   this.supOverrideEmployees
       .values()
       .stream()
       .filter(supInfo -> isSupInfoInRange(supInfo, dateRange))
       .forEach(
           supInfo ->
               filteredSupOverrideEmps.put(supInfo.getSupId(), supInfo.getEmpId(), supInfo));
   this.supOverrideEmployees = filteredSupOverrideEmps;
 }
  private void handleIncomingNonConfirmableMessage(ChannelHandlerContext ctx, MessageEvent me) {
    InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress();
    CoapMessage coapMessage = (CoapMessage) me.getMessage();

    boolean isDuplicate = true;

    if (!ongoingMessageExchanges.contains(remoteEndpoint, coapMessage.getMessageID())) {
      IncomingMessageExchange messageExchange =
          new IncomingMessageExchange(remoteEndpoint, coapMessage.getMessageID());

      synchronized (monitor) {
        if (!ongoingMessageExchanges.contains(remoteEndpoint, coapMessage.getMessageID())) {
          ongoingMessageExchanges.put(remoteEndpoint, coapMessage.getMessageID(), messageExchange);

          isDuplicate = false;
        }
      }

      ctx.sendUpstream(me);
    }

    if (isDuplicate)
      log.info("Received duplicate (non-confirmable). IGNORE! (Message: {})", coapMessage);
  }
예제 #26
0
 private Node<?> node() throws IOException {
   chunk("NODE");
   animations.push(HashBasedTable.<Integer, Optional<Node<?>>, Key>create());
   Triple<Integer, Integer, Float> animData = null;
   Pair<Brush, List<Face>> mesh = null;
   List<Pair<Vertex, Float>> bone = null;
   Map<Integer, Key> keys = new HashMap<Integer, Key>();
   List<Node<?>> nodes = new ArrayList<Node<?>>();
   String name = readString();
   Vector3f pos = new Vector3f(buf.getFloat(), buf.getFloat(), buf.getFloat());
   Vector3f scale = new Vector3f(buf.getFloat(), buf.getFloat(), buf.getFloat());
   Quat4f rot = readQuat();
   dump("NODE(" + name + ", " + pos + ", " + scale + ", " + rot + ") {");
   while (buf.hasRemaining()) {
     readHeader();
     if (isChunk("MESH")) mesh = mesh();
     else if (isChunk("BONE")) bone = bone();
     else if (isChunk("KEYS")) keys.putAll(keys());
     else if (isChunk("NODE")) nodes.add(node());
     else if (isChunk("ANIM")) animData = anim();
     else skip();
   }
   dump("}");
   popLimit();
   Table<Integer, Optional<Node<?>>, Key> keyData = animations.pop();
   Node<?> node;
   if (mesh != null) {
     Node<Mesh> mNode = Node.create(name, pos, scale, rot, nodes, new Mesh(mesh));
     meshes.put(name, mNode);
     node = mNode;
   } else if (bone != null) node = Node.create(name, pos, scale, rot, nodes, new Bone(bone));
   else node = Node.create(name, pos, scale, rot, nodes, new Pivot());
   if (animData == null) {
     for (Table.Cell<Integer, Optional<Node<?>>, Key> key : keyData.cellSet()) {
       animations
           .peek()
           .put(key.getRowKey(), key.getColumnKey().or(Optional.of(node)), key.getValue());
     }
   } else {
     node.setAnimation(animData, keyData);
   }
   return node;
 }
예제 #27
0
  private UIStyleFamily buildFamily(String family, UIStyle defaultStyle) {
    UIStyle baseStyle = new UIStyle(defaultStyle);
    if (!family.isEmpty()) {
      UIStyleFragment fragment = baseStyles.get(family);
      fragment.applyTo(baseStyle);
    }

    Map<Class<? extends UIWidget>, Table<String, String, UIStyle>> familyStyles = Maps.newHashMap();
    Map<StyleKey, UIStyleFragment> styleLookup = elementStyles.row(family);
    Map<StyleKey, UIStyleFragment> baseStyleLookup =
        (family.isEmpty()) ? Maps.<StyleKey, UIStyleFragment>newHashMap() : elementStyles.row("");
    for (StyleKey styleKey : Sets.union(styleLookup.keySet(), baseStyleKeys)) {
      UIStyle elementStyle = new UIStyle(baseStyle);
      List<Class<? extends UIWidget>> inheritanceTree =
          ReflectionUtil.getInheritanceTree(styleKey.element, UIWidget.class);
      applyStylesForInheritanceTree(
          inheritanceTree, "", "", elementStyle, styleLookup, baseStyleLookup);

      if (!styleKey.part.isEmpty()) {
        applyStylesForInheritanceTree(
            inheritanceTree, styleKey.part, "", elementStyle, styleLookup, baseStyleLookup);
      }

      if (!styleKey.mode.isEmpty()) {
        applyStylesForInheritanceTree(
            inheritanceTree,
            styleKey.part,
            styleKey.mode,
            elementStyle,
            styleLookup,
            baseStyleLookup);
      }

      Table<String, String, UIStyle> elementTable = familyStyles.get(styleKey.element);
      if (elementTable == null) {
        elementTable = HashBasedTable.create();
        familyStyles.put(styleKey.element, elementTable);
      }
      elementTable.put(styleKey.part, styleKey.mode, elementStyle);
    }
    return new UIStyleFamily(baseStyle, familyStyles);
  }
예제 #28
0
public class ConnectedComponent {
  int ccid;
  EventType eventtype;
  EventPhrase phrase;
  List<Tuple> tuples = new ArrayList<Tuple>();
  Factor phraseFactor = new Factor();
  List<Factor> tupleFactors = new ArrayList<Factor>();

  HashBasedTable<Integer, Integer, Factor> crossFactors = HashBasedTable.create();

  public String phraseFactorToStr() {
    return Util.counter2str(phraseFactor.features);
  }

  public void addCrossFeature(int i, int j, String f) {
    if (!crossFactors.contains(i, j)) {
      crossFactors.put(i, j, new Factor());
    }
    crossFactors.get(i, j).add(f);
  }
}
예제 #29
0
  @Override
  public Table<DefDescriptor<ComponentDef>, String, FlavorOverrideLocation> computeOverrides()
      throws QuickFixException {
    // component / flavor (might be multiple per cmp) / override location (should only be one per
    // cmp/flavor combo)
    Table<DefDescriptor<ComponentDef>, String, FlavorOverrideLocation> table =
        HashBasedTable.create();

    for (DefDescriptor<FlavoredStyleDef> style : getDefs()) {
      DefDescriptor<ComponentDef> cmp = Flavors.toComponentDescriptor(style);
      Map<String, FlavorAnnotation> annotations = style.getDef().getFlavorAnnotations();
      for (FlavorAnnotation annotation : annotations.values()) {
        table.put(
            cmp,
            annotation.getFlavorName(),
            new FlavorOverrideLocationImpl(style, annotation.getOverridesIf().orNull()));
      }
    }

    return table;
  }
  public static Table<Integer, String, String> parse(InlineTable inlineTable) {
    Table<Integer, String, String> result = HashBasedTable.create();

    Integer rowKey = 1;

    List<Row> rows = inlineTable.getRows();
    for (Row row : rows) {
      List<Object> cells = row.getContent();

      for (Object cell : cells) {

        if (cell instanceof Element) {
          Element element = (Element) cell;

          result.put(rowKey, element.getTagName(), element.getTextContent());
        }
      }

      rowKey += 1;
    }

    return result;
  }