Example #1
1
  private void watchOpenedTCs() {
    ArrayList<TopComponent> windowsToWatch = findShowingTCs();
    ArrayList<TopComponent> toAddListeners = new ArrayList<>(windowsToWatch);
    toAddListeners.removeAll(watchedLkpResults.keySet());

    ArrayList<TopComponent> toRemoveListeners = new ArrayList<>(watchedLkpResults.keySet());
    toRemoveListeners.removeAll(windowsToWatch);

    toRemoveListeners
        .stream()
        .forEach(
            (tc) -> {
              Lookup.Result res = watchedLkpResults.get(tc);
              if (null != res) {
                res.removeLookupListener(this);
                watchedLkpResults.remove(tc);
              }
            });

    toAddListeners
        .stream()
        .forEach(
            (tc) -> {
              Lookup.Result res = tc.getLookup().lookupResult(LayoutScene.class);
              res.addLookupListener(this);
              res.allItems();
              watchedLkpResults.put(tc, res);
            });
  }
 public void printWithDescription() {
   System.out.println("======MAPPING======");
   System.out.println("Similarity: " + similarity);
   System.out.println("___________________");
   System.out.println("Nodes:");
   System.out.println("___________________");
   nodeEntries
       .stream()
       .forEach(e -> System.out.println(e.nq.toString() + " -> " + e.nc.toString()));
   System.out.println("___________________");
   System.out.println("Edges:");
   System.out.println("___________________");
   edgeEntries
       .stream()
       .forEach(
           e ->
               System.out.println(
                   "("
                       + e.eq.getTail().toString()
                       + ", "
                       + e.eq.getHead().toString()
                       + ") -> "
                       + "("
                       + e.ec.getTail().toString()
                       + ", "
                       + e.ec.getHead().toString()
                       + ")"));
 }
 public void printWithIDs() {
   System.out.println("___________________");
   System.out.println("======MAPPING======");
   System.out.println("Similarity: " + similarity);
   System.out.println("Nodes:");
   nodeEntries.stream().forEach(e -> System.out.println(e.nq.getId() + " -> " + e.nc.getId()));
   System.out.println("Edges:");
   edgeEntries.stream().forEach(e -> System.out.println(e.eq.getId() + " -> " + e.ec.getId()));
 }
Example #4
1
  @Override
  public Command getCommand() {
    // edit command
    final ArrayList<Command> changes = new ArrayList<>();
    super.addEditCommands.accept(changes);

    if (productOwnerProperty().get() != modelWrapper.get().getProductOwner()) {
      changes.add(
          new EditCommand<>(modelWrapper.get(), "productOwner", productOwnerProperty().get()));
    }

    if (scrumMasterProperty().get() != modelWrapper.get().getScrumMaster()) {
      changes.add(
          new EditCommand<>(modelWrapper.get(), "scrumMaster", scrumMasterProperty().get()));
    }

    if (!(teamMembersProperty().get().containsAll(modelWrapper.get().getTeamMembers())
        && modelWrapper.get().getTeamMembers().containsAll(teamMembersProperty().get()))) {
      // BEWARE: magic
      ArrayList<Person> teamMembers = new ArrayList<>();
      teamMembers.addAll(teamMembersProperty().get());
      changes.add(new EditCommand<>(modelWrapper.get(), "teamMembers", teamMembers));
    }

    if (!(devTeamProperty().get().containsAll(modelWrapper.get().getDevTeam())
        && modelWrapper.get().getDevTeam().containsAll(devTeamProperty().get()))) {
      // BEWARE: magic
      ArrayList<Person> devTeam = new ArrayList<>();
      devTeam.addAll(devTeamProperty().get());
      changes.add(new EditCommand<>(modelWrapper.get(), "devTeam", devTeam));
    }

    final ArrayList<Person> newMembers = new ArrayList<>(teamMembersProperty().get());
    newMembers.removeAll(modelWrapper.get().observableTeamMembers());
    final ArrayList<Person> oldMembers =
        new ArrayList<>(modelWrapper.get().observableTeamMembers());
    oldMembers.removeAll(teamMembersProperty().get());

    // Loop through all the new members and add a command to set their team
    // Set the person's team field to this team
    changes.addAll(
        newMembers
            .stream()
            .map(person -> new EditCommand<>(person, "team", modelWrapper.get()))
            .collect(Collectors.toList()));

    // Loop through all the old members and add a command to remove their team
    // Set the person's team field to null, since they're no longer in the team
    changes.addAll(
        oldMembers
            .stream()
            .map(person -> new EditCommand<>(person, "team", null))
            .collect(Collectors.toList()));

    return new CompoundCommand("Edit Team", changes);
  }
Example #5
1
  public static void main(String[] args) throws FileNotFoundException {
    ArrayList<String> names = new ArrayList<>();
    File f = new File("people.csv");
    Scanner scanner = new Scanner(f);
    scanner.nextLine();
    while (scanner.hasNext()) {
      String line = scanner.nextLine();
      String[] columns = line.split(",");
      String name = columns[1] + " " + columns[2];
      names.add(name);
    }
    String searchTerm = "ali";
    ArrayList<String> results = new ArrayList<>();
    for (String name : names) {
      if (name.toLowerCase().contains(searchTerm)) {
        results.add(name);
      }
    }
    System.out.println(results);

    // To use stream:
    results =
        names
            .stream()
            .filter(
                (name) -> {
                  return name.toLowerCase().contains(searchTerm);
                })
            .collect(Collectors.toCollection(ArrayList<String>::new));
    System.out.println(results);
  }
  @Override
  public V getVariable(V[] variables) {
    oldv.clear();
    newv.clear();
    Collections.addAll(oldv, variables);
    // 1. remove instantied variables
    newv.addAll(oldv.stream().filter(v -> !v.isInstantiated()).collect(Collectors.toList()));
    if (newv.size() == 0) return null;

    // Then apply each heuristic one by one
    for (VariableEvaluator<V> h : heuristics) {
      double minValue = Double.MAX_VALUE - 1;
      oldv.clear();
      oldv.addAll(newv);
      newv.clear();
      for (V v : oldv) {
        double val = h.evaluate(v);
        if (val < minValue) {
          newv.clear();
          newv.add(v);
          minValue = val;
        } else if (val == minValue) {
          newv.add(v);
        }
      }
    }
    switch (oldv.size()) {
      case 0:
        return null;
      default:
      case 1:
        return oldv.get(0);
    }
  }
Example #7
0
 private Segment createSegmentFromEdges(long edgeId, long segmentId, boolean isEdgeOrigin) {
   double length = 0.0;
   Segment seg = null;
   try {
     List<Edge> subset = null;
     seg = db.ReadSegment(segmentId);
     ArrayList<Edge> edges = db.ReadEdges(segmentId);
     Edge edge = null;
     if (!edges.isEmpty()) {
       if (isEdgeOrigin) {
         edge =
             edges
                 .stream()
                 .filter(
                     (Edge e) -> {
                       return e.mOrigin == edgeId;
                     })
                 .findFirst()
                 .get();
       } else {
         edge =
             edges
                 .stream()
                 .filter(
                     (Edge e) -> {
                       return e.mDestination == edgeId;
                     })
                 .findFirst()
                 .get();
       }
       int index = edges.indexOf(edge);
       subset = edges.subList(index, edges.size());
       for (Edge ed : subset) {
         length = +ed.mLength;
       }
     }
     long origin, destination;
     origin = (isEdgeOrigin ? edgeId : seg.mOrigin);
     destination = (isEdgeOrigin ? seg.mDestination : edgeId);
     Segment s = new Segment(nextSegId++, length, seg.mWayId, origin, destination);
     return s;
   } catch (SQLException e) {
     System.err.println("Error getting segmentid from method modelNodeToSegment");
     e.printStackTrace();
   }
   return null;
 }
 private String getProductLineName(int productLineID) {
   List<ProductLine> productLine =
       productLines
           .stream()
           .filter((p) -> p.getProductLineID() == productLineID)
           .collect(Collectors.toList());
   return productLine.get(0).getProductLineName();
 }
  public void sendNicklist(User target) {
    ArrayList<User> users = Globals.server.getChannelUsers(this.name);

    String nicklist = users.stream().map(u -> u.getName()).collect(Collectors.joining(" "));

    target.sendMessage(353, target.getName() + " @ " + this.name, nicklist);
    target.sendMessage(366, target.getName() + " " + this.name, "END of /NAMES list.");
  }
Example #10
0
 public static void main(String args[]) {
   // DeepList.evalList("{12}");
   ArrayList<String> tester = new ArrayList<String>();
   tester.add("I");
   tester.add("Am");
   tester.add("Awesome");
   String toPrint = tester.stream().collect(Collectors.joining(" "));
   System.out.println(toPrint);
 }
  @Override
  public void train(
      int[] numInputCategory, int[][] inputCategory, int numOutputClass, int[] outputClass)
      throws Exception {
    shuffleTrainingSet(inputCategory, outputClass);
    OfflineLearningNominalDataClassifier[] candidate = new OfflineLearningNominalDataClassifier[k];
    double[] accuracy = new double[k];
    int selected = 0;
    for (int i = 0; i < k; i++) {
      candidate[i] = classifier.copy();

      // pisah set menjadi tr dan cv
      ArrayList<int[]> trInputCategory = new ArrayList<int[]>();
      ArrayList<Integer> trOutputClass = new ArrayList<Integer>();
      ArrayList<int[]> cvInputCategory = new ArrayList<int[]>();
      ArrayList<Integer> cvOutputClass = new ArrayList<Integer>();
      for (int j = 0; j < i * inputCategory.length / k; j++) {
        trInputCategory.add(inputCategory[j]);
        trOutputClass.add(outputClass[j]);
      }
      for (int j = i * inputCategory.length / k; j < (i + 1) * inputCategory.length / k; j++) {
        cvInputCategory.add(inputCategory[j]);
        cvOutputClass.add(outputClass[j]);
      }
      for (int j = (i + 1) * inputCategory.length / k; j < inputCategory.length; j++) {
        trInputCategory.add(inputCategory[j]);
        trOutputClass.add(outputClass[j]);
      }
      candidate[i].train(
          numInputCategory,
          (int[][]) trInputCategory.toArray(new int[trInputCategory.size()][]),
          numOutputClass,
          trOutputClass.stream().mapToInt(Integer::intValue).toArray());
      accuracy[i] =
          calculateAccuracy(
              candidate[i],
              cvInputCategory.toArray(new int[cvInputCategory.size()][]),
              cvOutputClass.stream().mapToInt(Integer::intValue).toArray());
      if (accuracy[i] > accuracy[selected]) selected = i;
    }
    classifier = candidate[selected];
  }
Example #12
0
 /**
  * This method is geting The parameters for the command ,it separets the parameters from the
  * command .
  *
  * @param input
  * @return String[]
  */
 public String[] getParam(String input) {
   if (!input.contains("<")) return new String[0];
   String param = input.substring(input.indexOf('<') - 1);
   String[] tmp = param.split("(<)|(>)");
   ArrayList<String> finalParam = new ArrayList<String>();
   for (String string2 : tmp) {
     if (!string2.equals(" ")) finalParam.add(string2);
   }
   String[] a = finalParam.stream().toArray(String[]::new);
   return a;
 }
 /**
  * Fetches the list of products selected in UI
  *
  * @return The list of selected products to be used as input source
  */
 public Product[] getSourceProducts() {
   List<Product> sourceProducts = new ArrayList<>();
   ArrayList<SourceProductSelector> sourceProductSelectorList =
       ioParamPanel.getSourceProductSelectorList();
   sourceProducts.addAll(
       sourceProductSelectorList
           .stream()
           .map(SourceProductSelector::getSelectedProduct)
           .collect(Collectors.toList()));
   return sourceProducts.toArray(new Product[sourceProducts.size()]);
 }
  public static void main(String[] args) {
    ArrayList<Contact> contacts = new ArrayList<>();
    contacts.add(new Contact("Abc", "*****@*****.**"));
    contacts.add(new Contact("Xyz", "*****@*****.**"));
    contacts.add(new Contact("Def", "*****@*****.**"));
    contacts.add(new Contact("Pqr", "*****@*****.**"));

    contacts
        .stream()
        .filter(v -> v.getEmail().contains("yahoo.com"))
        .forEach(v -> System.out.println(v));
  }
Example #15
0
  @Override
  public void addTagToIndex(String tag, String subscribeId) {
    ArrayList<String> subMapped = null;
    if (tagIndex.get(tag) == null) {
      subMapped = new ArrayList();
      tagIndex.put(tag, subMapped);
    } else subMapped = tagIndex.get(tag);

    if (subMapped.stream().filter(x -> (x.equalsIgnoreCase(subscribeId))).count() == 0) {
      subMapped.add(subscribeId);
    }
  }
  private void showProductDetails(int ID) {
    List<Products> productWithID =
        products.stream().filter((p) -> p.getProductID() == ID).collect(Collectors.toList());
    List<Supplier> supplierWithID =
        suppliers
            .stream()
            .filter((p) -> p.getSupplierID() == p.getSupplierID())
            .collect(Collectors.toList());

    Products product = productWithID.get(0);
    Supplier supplier = supplierWithID.get(0);

    String productName_ =
        (productLineMap.get(product.getProductLineID())
                + " "
                + product.getDescription()
                + " "
                + product.getCharacteristics()
                + " "
                + product.getMotors())
            .replaceAll("\\s+", " ");
    String productDescription_ =
        (product.getDescription() + " " + product.getCharacteristics() + " " + product.getMotors())
            .replaceAll("\\s+", " ");

    iProductName.setText(productName_);
    iItemNumber.setText(String.valueOf(product.getProductID()));
    iAddMotoCode.setText(product.getAddmotoCode());
    iProductLine.setText(productLineMap.get(product.getProductLineID()));
    iItemDescription.setText(productDescription_);
    iSellingPrice.setText(Formatter.format(product.getSellingPrice()));
    iUnitCost.setText(Formatter.format(product.getUnitPrice()));
    iOnHandQuantity.setText(String.valueOf(product.getCurrentQuantity()));
    iQtyThreshold.setText(String.valueOf(product.getThresholdCount()));
    iStatus.setText("Not Yet Implemented");
    iSupplier.setText(supplier.getSupplierName());
    iEditUpdateRSP.setEnabled(true);
    iEditUpdateUC.setEnabled(true);
    iEditUpdateQT.setEnabled(true);
  }
Example #17
0
 private void removeSelectedMediaSource() {
   sourceTree
       .getSourcesSelected()
       .ifPresent(
           (ArrayList<MusicSource> e) ->
               e.stream()
                   .forEach(
                       (MusicSource ms) ->
                           sources
                               .stream()
                               .filter(s -> s.equals(ms))
                               .forEach(s -> sources.remove(s))));
 }
Example #18
0
 public void reset(ArrayList<Animation> animations) {
   this.animations.clear();
   animations
       .stream()
       .filter((anim) -> (isGroup(anim.group)))
       .forEach(
           (anim) -> {
             this.animations.add(anim);
           });
   startTime = originalStartTime;
   pathTime = 0;
   // Fixme: angle, opacity
 }
 public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   ArrayList<String> list = new ArrayList<>(Arrays.asList(input.nextLine().split(" ")));
   ArrayList<String> filter =
       new ArrayList<>(list.stream().filter(p -> p.length() > 3).collect(Collectors.toList()));
   if (filter.size() != 0) {
     for (String str : filter) {
       System.out.print(str + " ");
     }
   } else {
     System.out.println("(empty)");
   }
 }
Example #20
0
 //    int x1, x2, y;
 private void drawLine(int currentY, int index) {
   // добавление рассматриваемых плоскостей
   for (; index < setBorders.size() && setBorders.get(index) >= currentY; index++) {
     changeDrawnSurfacesList(currentY, true);
   }
   // поиск всех точек, пересекающих эту плоскость, и составление из них отрезков
   // поиск точек пересечения между этими отрезками
   findAllIntersections(currentY);
   // сортировка
   pointsList =
       (ArrayList<Point>)
           pointsList
               .stream()
               .sorted((a, b) -> Double.compare(a.getX(), b.getX()))
               .collect(Collectors.toList());
   // отрисовка
   Point last = new Point(0, currentY, 0);
   for (Point p : pointsList) {
     ArrayList<PointEvent> events = listPointsEvent.getEvent((int) p.getX());
     for (PointEvent event : events) {
       if (event.event == PointEventsList.START) {
         drawnSegments.add(event.point.getParent());
       }
     }
     if (drawnSegments.size() > 0) {
       double maxZ = -Double.MAX_VALUE;
       Segment chosen = null;
       for (Segment seg : drawnSegments) {
         double z = seg.getZOnX(p.getX());
         if (z > maxZ) {
           maxZ = z;
           chosen = seg;
         }
       }
       if (chosen != null && maxZ > -Double.MAX_VALUE) {
         context.setStroke(chosen.getSurfaceColor());
         double x1 = canvas.getWidth() / 4 + last.getX() * 2,
             x2 = canvas.getWidth() / 4 + p.getX() * 2,
             y = canvas.getHeight() / 2 + currentY;
         context.strokeLine(x1, y, x2, y);
       }
     }
     // актуализация отрезков
     for (PointEvent event : events) {
       if (event.event == PointEventsList.FINISH) {
         drawnSegments.remove(event.point.getParent());
       }
     }
     last = p;
   }
 }
  /**
   * Sets model values according to the given variations
   *
   * @param variations variations vector
   */
  public void setVariations(ArrayList<IVariation> variations) {
    reset();

    variations
        .stream()
        .forEach(
            (variation) -> {
              int row = VariationsFactory.getVariationIndex(variation.getName());

              setValueAt(variation.getName(), row, 0);
              setValueAt(Double.toString(variation.getCoefficient()), row, 1);
              setValueAt(variation.getParameters(), row, 2);
            });
  }
Example #22
0
  public static void main(String[] args) {
    File file = new File(System.getProperty("user.dir") + "\\" + args[0]);

    TransactionGenerator transactionDataFromFile = new TransactionDataFromFile(file);
    try {
      transactions = (ArrayList<Transaction>) transactionDataFromFile.loadTransactions();
    } catch (IOException e) {
      e.printStackTrace();
    }

    sum =
        transactions.stream().map(Transaction::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
    System.out.println(sum);
  }
Example #23
0
 public double getUsedProportion() {
   int total = list.size();
   if (total == 0) {
     return 0.0;
   }
   int used =
       (int)
           list.stream()
               .filter(
                   loca -> {
                     return loca.getOrderID().length() > 0;
                   })
               .count();
   return used / (double) total;
 }
Example #24
0
  public boolean saveFile() {
    try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
      dataRows
          .stream()
          .forEach(
              (s) -> {
                writer.println(s);
              });
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
      SyncTags.showErrorMessage(e, "Error occured while writing " + file);
      return false;
    }

    return true;
  }
Example #25
0
  private ArrayList<State> extractFollowStates() {
    ArrayList<State> states = new ArrayList<>();

    ArrayList<Road> neighborStates = currentNode.getEdges();

    neighborStates
        .stream()
        .filter(road -> road.isBidirectional() || road.getStart().equals(currentNode))
        .forEach(
            road -> {
              State newState = followRouteAction(road, truck);
              states.add(newState);
            });

    return states;
  }
  static void solveViaStream(ArrayList<String> names) {
    List<String> newNames =
        names
            .stream() // calls method called stream.
            .map(
                (name) -> { // map function takes an anonymous function
                  return name.toUpperCase();
                })
            .filter(
                (name) -> { // filter function tells if name should be included in the results
                  return !name.startsWith("A");
                })
            .collect(Collectors.toList()); // turn this string back into a list

    System.out.println(newNames);
  }
Example #27
0
 /**
  * Create a list of {@link ItemCategory} and a list of {@link ItemWidget} Add name of {@link
  * ItemCategory} to the context to link itemWiget with itemCategory
  */
 public void separate() {
   widgetGroupList
       .stream()
       .forEach(
           (widgetGroup) -> {
             ItemCategory itemCategory =
                 new DefaultCategory(
                     widgetGroup.getName(), widgetGroup.getContext(), widgetGroup.getIcon());
             categoryList.add(itemCategory);
             for (ItemWidget itemwidget : widgetGroup.getItems()) {
               itemwidget.addContext("+" + itemCategory.getName());
               itemwidget.removeSpaceContext();
               widgetList.add(itemwidget);
             }
           });
 }
Example #28
0
 @Override
 public String toString() {
   StringBuilder display = new StringBuilder();
   display.append("---------- Pizza Order-----------");
   display.append("ordered by:").append(orderedBy);
   display.append("name:").append(name);
   display.append("dough:").append(dough);
   display.append("sauce:").append(sauce);
   toppings
       .stream()
       .forEach(
           (topping) -> {
             display.append(topping).append("\n");
           });
   return display.toString();
 }
Example #29
0
 private void changeDrawnSurfacesList(int currentY, boolean isAdd) {
   ArrayList<SurfaceEvent> events = listSurfacesEvents.getEvent(currentY);
   if (events == null) {
     return;
   }
   events
       .stream()
       .forEach(
           event -> {
             if (isAdd && event.isStart) {
               drawnSurfaces.add(event.surface);
             } else if (!isAdd && !event.isStart) {
               drawnSurfaces.remove(event.surface);
             }
           });
 }
Example #30
0
 private ArrayList<FakeNode> getNeighbours(long id) {
   ArrayList<FakeNode> retNodes = new ArrayList<>();
   ArrayList<Segment> neighbours =
       this.segments
           .stream()
           .filter(
               (Segment s) -> {
                 return s.mOrigin == id;
               })
           .collect(Collectors.toCollection(ArrayList<Segment>::new));
   neighbours.addAll(
       this.fakeSegments
           .stream()
           .filter(
               (Segment s) -> {
                 return s.mOrigin == id;
               })
           .collect(Collectors.toCollection(ArrayList<Segment>::new)));
   FakeNode node;
   for (Segment s : neighbours) {
     if (fakeNodes.containsKey(s.mDestination)) {
       node = fakeNodes.get(s.mDestination);
     } else {
       node = new FakeNode(nodes.get(s.mDestination));
       fakeNodes.put(s.mDestination, node);
     }
     ArrayList<CostFunction> functions =
         costs
             .stream()
             .filter(
                 (CostFunction c) -> {
                   return c.getSegmentId() == s.mId;
                 })
             .collect(Collectors.toCollection(ArrayList<CostFunction>::new));
     functions.addAll(
         fakeCosts
             .stream()
             .filter(
                 (CostFunction c) -> {
                   return c.getSegmentId() == s.mId;
                 })
             .collect(Collectors.toCollection(ArrayList<CostFunction>::new)));
     node.node.cost = functions.get(0);
     retNodes.add(fakeNodes.get(s.mDestination));
   }
   return retNodes;
 }