private void adjustDateLineCrossingPoints() {
      ArrayList<LatLon> corners = new ArrayList<LatLon>(Arrays.asList(sw, se, nw, ne));
      if (!LatLon.locationsCrossDateLine(corners)) return;

      double lonSign = 0;
      for (LatLon corner : corners) {
        if (Math.abs(corner.getLongitude().degrees) != 180)
          lonSign = Math.signum(corner.getLongitude().degrees);
      }

      if (lonSign == 0) return;

      if (Math.abs(sw.getLongitude().degrees) == 180
          && Math.signum(sw.getLongitude().degrees) != lonSign)
        sw = new Position(sw.getLatitude(), sw.getLongitude().multiply(-1), sw.getElevation());
      if (Math.abs(se.getLongitude().degrees) == 180
          && Math.signum(se.getLongitude().degrees) != lonSign)
        se = new Position(se.getLatitude(), se.getLongitude().multiply(-1), se.getElevation());
      if (Math.abs(nw.getLongitude().degrees) == 180
          && Math.signum(nw.getLongitude().degrees) != lonSign)
        nw = new Position(nw.getLatitude(), nw.getLongitude().multiply(-1), nw.getElevation());
      if (Math.abs(ne.getLongitude().degrees) == 180
          && Math.signum(ne.getLongitude().degrees) != lonSign)
        ne = new Position(ne.getLatitude(), ne.getLongitude().multiply(-1), ne.getElevation());
    }
  public List<String> find() throws IOException {
    //		Set<String> g1 = new HashSet<String>(Arrays.asList("HRAS", "NRAS", "KRAS"));
    //		Set<String> g2 = new HashSet<String>(Arrays.asList("BRAF"));

    Set<String> g1 = new HashSet<String>(Arrays.asList("HRAS"));
    Set<String> g2 = new HashSet<String>(Arrays.asList("NRAS", "KRAS"));

    Map<String, Double> pvals = calcDifferencePvals(g1, g2);

    System.out.println("pvals.size() = " + pvals.size());

    List<String> list = FDR.select(pvals, null, fdrThr);
    System.out.println("result size = " + list.size());

    Map<String, Boolean> dirs = getChangeDirections(list, g1, g2);

    int up = 0;
    int dw = 0;

    for (String gene : dirs.keySet()) {
      Boolean d = dirs.get(gene);
      if (d) up++;
      else dw++;
    }

    System.out.println("up = " + up);
    System.out.println("dw = " + dw);

    return list;
  }
  private static void patchGtkDefaults(UIDefaults defaults) {
    if (!UIUtil.isUnderGTKLookAndFeel()) return;

    Map<String, Icon> map =
        ContainerUtil.newHashMap(
            Arrays.asList(
                "OptionPane.errorIcon",
                "OptionPane.informationIcon",
                "OptionPane.warningIcon",
                "OptionPane.questionIcon"),
            Arrays.asList(
                AllIcons.General.ErrorDialog,
                AllIcons.General.InformationDialog,
                AllIcons.General.WarningDialog,
                AllIcons.General.QuestionDialog));
    // GTK+ L&F keeps icons hidden in style
    SynthStyle style = SynthLookAndFeel.getStyle(new JOptionPane(""), Region.DESKTOP_ICON);
    for (String key : map.keySet()) {
      if (defaults.get(key) != null) continue;

      Object icon = style == null ? null : style.get(null, key);
      defaults.put(key, icon instanceof Icon ? icon : map.get(key));
    }

    Color fg = defaults.getColor("Label.foreground");
    Color bg = defaults.getColor("Label.background");
    if (fg != null && bg != null) {
      defaults.put("Label.disabledForeground", UIUtil.mix(fg, bg, 0.5));
    }
  }
Example #4
0
  public MainPanel() {
    super(new BorderLayout());
    JPanel p = new JPanel(new GridLayout(2, 1));
    final JComboBox<String> c0 = makeComboBox(true, false);
    final JComboBox<String> c1 = makeComboBox(false, false);
    final JComboBox<String> c2 = makeComboBox(true, true);
    final JComboBox<String> c3 = makeComboBox(false, true);

    p.add(makeTitlePanel("setEditable(false)", Arrays.asList(c0, c1)));
    p.add(makeTitlePanel("setEditable(true)", Arrays.asList(c2, c3)));
    p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    add(p, BorderLayout.NORTH);
    add(
        new JButton(
            new AbstractAction("add") {
              @Override
              public void actionPerformed(ActionEvent e) {
                String str = new Date().toString();
                for (JComboBox<String> c : Arrays.asList(c0, c1, c2, c3)) {
                  MutableComboBoxModel<String> m = (MutableComboBoxModel<String>) c.getModel();
                  m.insertElementAt(str, m.getSize());
                }
              }
            }),
        BorderLayout.SOUTH);
    setPreferredSize(new Dimension(320, 240));
  }
  /**
   * setupPlayZone.
   *
   * @param p a {@link arcane.ui.PlayArea} object.
   * @param c an array of {@link forge.Card} objects.
   */
  public static void setupPlayZone(PlayArea p, Card c[]) {
    List<Card> tmp, diff;
    tmp = new ArrayList<Card>();
    for (arcane.ui.CardPanel cpa : p.cardPanels) tmp.add(cpa.gameCard);
    diff = new ArrayList<Card>(tmp);
    diff.removeAll(Arrays.asList(c));
    if (diff.size() == p.cardPanels.size()) p.clear();
    else {
      for (Card card : diff) {
        p.removeCardPanel(p.getCardPanel(card.getUniqueNumber()));
      }
    }
    diff = new ArrayList<Card>(Arrays.asList(c));
    diff.removeAll(tmp);

    arcane.ui.CardPanel toPanel = null;
    for (Card card : diff) {
      toPanel = p.addCard(card);
      Animation.moveCard(toPanel);
    }

    for (Card card : c) {
      toPanel = p.getCardPanel(card.getUniqueNumber());
      if (card.isTapped()) {
        toPanel.tapped = true;
        toPanel.tappedAngle = arcane.ui.CardPanel.TAPPED_ANGLE;
      } else {
        toPanel.tapped = false;
        toPanel.tappedAngle = 0;
      }
      toPanel.attachedPanels.clear();
      if (card.isEnchanted()) {
        ArrayList<Card> enchants = card.getEnchantedBy();
        for (Card e : enchants) {
          arcane.ui.CardPanel cardE = p.getCardPanel(e.getUniqueNumber());
          if (cardE != null) toPanel.attachedPanels.add(cardE);
        }
      }

      if (card.isEquipped()) {
        ArrayList<Card> enchants = card.getEquippedBy();
        for (Card e : enchants) {
          arcane.ui.CardPanel cardE = p.getCardPanel(e.getUniqueNumber());
          if (cardE != null) toPanel.attachedPanels.add(cardE);
        }
      }

      if (card.isEnchanting()) {
        toPanel.attachedToPanel = p.getCardPanel(card.getEnchanting().get(0).getUniqueNumber());
      } else if (card.isEquipping()) {
        toPanel.attachedToPanel = p.getCardPanel(card.getEquipping().get(0).getUniqueNumber());
      } else toPanel.attachedToPanel = null;

      toPanel.setCard(toPanel.gameCard);
    }
    p.invalidate();
    p.repaint();
  }
Example #6
0
  private static boolean matchFramework(
      ProjectCategory projectCategory, FrameworkSupportInModuleProvider framework) {

    FrameworkRole[] roles = framework.getRoles();
    if (roles.length == 0) return true;

    List<FrameworkRole> acceptable = Arrays.asList(projectCategory.getAcceptableFrameworkRoles());
    return ContainerUtil.intersects(Arrays.asList(roles), acceptable);
  }
 protected void stitchNeighbors(Set<Sector> neighbors, GeoPoint center) {
   assert gatedAssertion(
       neighbors.size() == 6
           || neighbors.size() == 5 && countDistinctGlobalSectors(neighbors) == 5);
   if (!sector.equals(neighbors.iterator().next())) {
     return;
   }
   Map<GeoPoint, GeoPoint> nextPoints = new HashMap<GeoPoint, GeoPoint>();
   Sector second = null;
   for (Sector s : neighbors) {
     char vertex = s.getVertex(center);
     Sector.Triangle cornerTriangle = s.getCornerTriangle(vertex);
     GeoPoint[] geoPoints = cornerTriangle.getPoints(vertex);
     nextPoints.put(geoPoints[1], geoPoints[2]);
     if (second == null && countShared(s.points, sector.points) == 1) {
       second = s;
     }
   }
   assert gatedAssertion(second != null);
   if (second != null) {
     GeoPoint[] acre = new GeoPoint[nextPoints.size()];
     GeoPoint point = nextPoints.values().iterator().next();
     for (int idx = 0; idx < nextPoints.size(); idx++) {
       assert !Arrays.asList(acre).contains(point);
       acre[idx] = point;
       point = nextPoints.get(point);
       assert gatedAssertion(point != null);
       if (point == null) {
         return;
       }
     }
     Sector[] others = new Sector[neighbors.size() - 2];
     int idx = 0;
     for (Sector s : neighbors) {
       if (s != sector && s != second) {
         others[idx++] = s;
       }
     }
     Acre newAcre = new Acre(1, sector, second, Arrays.asList(others), center, acre);
     CartographicElementView cartographicElementView = getFor(subdivisions);
     for (Sector s : neighbors) {
       char vertex = s.getVertex(center);
       assert vertex == 'A' || vertex == 'B' || vertex == 'C';
       Edge e = Edge.values()[vertex - 'A'];
       List<Acre> vertexAcre =
           cartographicElementView.get(
               s.getSharedAcres(), CartographicElementView.Position.Vertex, e, false);
       assert vertexAcre.size() == 1;
       assert vertexAcre.get(0) == null;
       vertexAcre.set(0, newAcre);
     }
     consume(newAcre);
   }
 }
Example #8
0
 public TDTree(Point[] pts, boolean cd) {
   this();
   // for(Point p : pts)
   // insert(p);
   this.size = pts.length;
   // TreeNode newRoot = buildBalanced(new ArrayList<Point>(Arrays.asList(pts)), true);
   ArrayList<Point> xSorted = new ArrayList<Point>(Arrays.asList(pts));
   ArrayList<Point> ySorted = new ArrayList<Point>(Arrays.asList(pts));
   Collections.sort(xSorted, new PointComparator(true));
   Collections.sort(ySorted, new PointComparator(false));
   TreeNode newRoot = buildBalanced(xSorted, ySorted, cd);
   recalculateData(newRoot);
   root = newRoot;
 }
    public AppFrame() {
      // Create the rectangular array of numeric values in the range from 0.0 to 1.0, inclusive, and
      // assign the
      // array a geographic sector.
      this.createRectangularArray();

      // Display the rectangular array of numeric values as a surface that maps each numeric value
      // to a hue, and
      // interpolates the colors between array points.
      RenderableLayer arrayLayer = new RenderableLayer();
      arrayLayer.setName("Rectangular Array");
      this.getWwd().getModel().getLayers().add(arrayLayer);
      this.addRectangularArrayShapes(arrayLayer);

      // Create a layer to group the contour line shapes.
      RenderableLayer contourLayer = new RenderableLayer();
      contourLayer.setName("Contour Lines");
      this.getWwd().getModel().getLayers().add(contourLayer);

      // Create a ContourBuilder with the rectangular array of numeric values as a one-dimensional
      // array of
      // floating point numbers. The contour builder assumes that the array is organized in
      // row-major order, with
      // the first value indicating the value at the upper-left corner.
      ContourBuilder cb = new ContourBuilder(this.arrayWidth, this.arrayHeight, this.arrayValues);

      // Build contour lines for a list of pre-determined threshold values. Contour line coordinates
      // are computed
      // by mapping the rectangular array's coordinates to a geographic sector.
      for (double value : Arrays.asList(0.083, 0.250, 0.416, 0.583, 0.75, 0.916)) {
        List<List<Position>> contourList =
            cb.buildContourLines(value, this.arraySector, 0); // altitude 0
        this.addContourShapes(contourList, value, contourLayer);
      }
    }
Example #10
0
  private void updateDebugPanelState(String result, boolean debug, boolean test) {
    result = result == null ? "nothing" : result;

    List<Component> componentList = Arrays.asList(getComponents());
    if (!componentList.contains(p_debug)) {

      choice = new Label(String.format("Your choice is: %s", result));
      isDebug = new Label(String.format("Debug mode: %b", debug));
      isTest = new Label(String.format("Test mode: %b", test));
      GridBagLayout layout = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
      layout.setConstraints(choice, constraints);
      constraints.gridy = 1;
      layout.setConstraints(isDebug, constraints);
      constraints.gridy = 2;
      layout.setConstraints(isTest, constraints);

      p_debug.setLayout(layout);
      p_debug.add(choice);
      p_debug.add(isDebug);
      p_debug.add(isTest);
      add(p_debug, BorderLayout.SOUTH);

    } else {
      choice.setText(String.format("Your choice is: %s", result));
      isDebug.setText(String.format("Debug mode: %b", debug));
      isTest.setText(String.format("Test mode: %b", test));
    }
  }
 /** {@inheritDoc} */
 public Iterable<AVList> getLinks() {
   if (this.webViewWindowPtr != 0) {
     AVList[] links = WindowsWebViewJNI.getLinks(this.webViewWindowPtr);
     if (links != null) return Arrays.asList(links);
   }
   return Collections.emptyList();
 }
 public MyTableModel() {
   Vector<Vector<String>> rowData = new Vector<Vector<String>>();
   for (int i = 0; i < 1; i++) {
     Vector<String> colData = new Vector<String>(Arrays.asList("players.txt"));
     rowData.add(colData);
   }
 }
  private static void patchHiDPI(UIDefaults defaults) {
    if (!JBUI.isHiDPI()) return;

    List<String> myIntKeys = Arrays.asList("Tree.leftChildIndent", "Tree.rightChildIndent");
    List<String> patched = new ArrayList<String>();
    for (Map.Entry<Object, Object> entry : defaults.entrySet()) {
      Object value = entry.getValue();
      String key = entry.getKey().toString();
      if (value instanceof DimensionUIResource) {
        entry.setValue(JBUI.size((DimensionUIResource) value).asUIResource());
      } else if (value instanceof InsetsUIResource) {
        entry.setValue(JBUI.insets(((InsetsUIResource) value)).asUIResource());
      } else if (value instanceof Integer) {
        if (key.endsWith(".maxGutterIconWidth") || myIntKeys.contains(key)) {
          if (!"true".equals(defaults.get(key + ".hidpi.patched"))) {
            entry.setValue(Integer.valueOf(JBUI.scale((Integer) value)));
            patched.add(key);
          }
        }
      }
    }
    for (String key : patched) {
      defaults.put(key + ".hidpi.patched", "true");
    }
  }
Example #14
0
  private void autoscale() {

    int stateHash = FrameManager.getStateHash();

    //  if(lastFrameStateHash == stateHash) return;

    lastStateHash = stateHash;

    final Collection<Track> trackList = IGV.getInstance().getAllTracks();

    Map<String, List<Track>> autoscaleGroups = new HashMap<String, List<Track>>();

    for (Track track : trackList) {

      if (!track.isVisible()) continue;

      String asGroup = track.getAttributeValue(AttributeManager.GROUP_AUTOSCALE);
      if (asGroup != null) {
        if (!autoscaleGroups.containsKey(asGroup)) {
          autoscaleGroups.put(asGroup, new ArrayList<Track>());
        }
        autoscaleGroups.get(asGroup).add(track);
      } else if (track.getAutoScale()) {
        autoscaleGroup(Arrays.asList(track));
      }
    }

    if (autoscaleGroups.size() > 0) {
      for (List<Track> tracks : autoscaleGroups.values()) {
        autoscaleGroup(tracks);
      }
    }
  }
 public static <T> void assertUnorderedCollection(
     Collection<? extends T> collection, Consumer<T>... checkers) {
   Assert.assertNotNull(collection);
   if (collection.size() != checkers.length) {
     Assert.fail(toString(collection));
   }
   Set<Consumer<T>> checkerSet = new HashSet<Consumer<T>>(Arrays.asList(checkers));
   int i = 0;
   Throwable lastError = null;
   for (final T actual : collection) {
     boolean flag = true;
     for (final Consumer<T> condition : checkerSet) {
       Throwable error = accepts(condition, actual);
       if (error == null) {
         checkerSet.remove(condition);
         flag = false;
         break;
       } else {
         lastError = error;
       }
     }
     if (flag) {
       lastError.printStackTrace();
       Assert.fail("Incorrect element(" + i + "): " + actual);
     }
     i++;
   }
 }
Example #16
0
class AnimeIcon implements Icon {
  private static final Color ELLIPSE_COLOR = new Color(.5f, .5f, .5f);
  private static final double R = 2d;
  private static final double SX = 1d;
  private static final double SY = 1d;
  private static final int WIDTH = (int) (R * 8 + SX * 2);
  private static final int HEIGHT = (int) (R * 8 + SY * 2);
  private final List<Shape> list =
      new ArrayList<Shape>(
          Arrays.asList(
              new Ellipse2D.Double(SX + 3 * R, SY + 0 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 5 * R, SY + 1 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 6 * R, SY + 3 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 5 * R, SY + 5 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 3 * R, SY + 6 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 1 * R, SY + 5 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 0 * R, SY + 3 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 1 * R, SY + 1 * R, 2 * R, 2 * R)));

  private boolean isRunning;

  public void next() {
    if (isRunning) {
      list.add(list.remove(0));
    }
  }

  public void setRunning(boolean isRunning) {
    this.isRunning = isRunning;
  }

  @Override
  public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE);
    g2.fillRect(x, y, getIconWidth(), getIconHeight());
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(ELLIPSE_COLOR);
    g2.translate(x, y);
    int size = list.size();
    for (int i = 0; i < size; i++) {
      float alpha = isRunning ? (i + 1) / (float) size : .5f;
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
      g2.fill(list.get(i));
    }
    // g2.translate(-x, -y);
    g2.dispose();
  }

  @Override
  public int getIconWidth() {
    return WIDTH;
  }

  @Override
  public int getIconHeight() {
    return HEIGHT;
  }
}
  /**
   * Updates the Table based on the selection of the given table. Perform lookups to remove any
   * store files from the shared folder view and to only display store files in the store view
   */
  void updateTableFiles(DirectoryHolder dirHolder) {
    if (dirHolder == null) {
      return;
    }

    if (dirHolder instanceof MediaTypeSavedFilesDirectoryHolder) {
      MediaType mediaType = ((MediaTypeSavedFilesDirectoryHolder) dirHolder).getMediaType();
      setMediaType(mediaType);

      if (mediaType.equals(MediaType.getAudioMediaType())) {
        UXStats.instance().log(UXAction.LIBRARY_BROWSE_FILE_TYPE_AUDIO);
      } else if (mediaType == MediaType.getImageMediaType()) {
        UXStats.instance().log(UXAction.LIBRARY_BROWSE_FILE_TYPE_PICTURES);
      } else if (mediaType == MediaType.getDocumentMediaType()) {
        UXStats.instance().log(UXAction.LIBRARY_BROWSE_FILE_TYPE_DOCUMENTS);
      } else if (mediaType == MediaType.getVideoMediaType()) {
        UXStats.instance().log(UXAction.LIBRARY_BROWSE_FILE_TYPE_VIDEOS);
      } else if (mediaType == MediaType.getTorrentMediaType()) {
        UXStats.instance().log(UXAction.LIBRARY_BROWSE_FILE_TYPE_TORRENTS);
      } else if (mediaType == MediaType.getProgramMediaType()) {
        UXStats.instance().log(UXAction.LIBRARY_BROWSE_FILE_TYPE_APPLICATIONS);
      }
    } else {
      setMediaType(MediaType.getAnyTypeMediaType());
    }
    clearTable();

    List<List<File>> partitionedFiles = split(100, Arrays.asList(dirHolder.getFiles()));

    for (List<File> partition : partitionedFiles) {
      final List<File> fPartition = partition;

      BackgroundExecutorService.schedule(
          new Runnable() {

            @Override
            public void run() {
              for (final File file : fPartition) {
                GUIMediator.safeInvokeLater(
                    new Runnable() {
                      public void run() {
                        addUnsorted(file);
                      }
                    });
              }

              GUIMediator.safeInvokeLater(
                  new Runnable() {
                    public void run() {
                      LibraryMediator.instance().getLibrarySearch().addResults(fPartition.size());
                    }
                  });
            }
          });
    }

    forceResort();
  }
Example #18
0
  /**
   * removes comments, processes commands drawbot shouldn't have to handle.
   *
   * @param line command to send
   * @return true if the robot is ready for another command to be sent.
   */
  public boolean ProcessLine(String line) {
    // tool change request?
    String[] tokens = line.split("\\s");

    // tool change?
    if (Arrays.asList(tokens).contains("M06") || Arrays.asList(tokens).contains("M6")) {
      for (int i = 0; i < tokens.length; ++i) {
        if (tokens[i].startsWith("T")) {
          JOptionPane.showMessageDialog(
              null, "Please change to tool #" + tokens[i].substring(1) + " and click OK.");
        }
      }
      // still ready to send
      return true;
    }

    // end of program?
    if (tokens[0] == "M02" || tokens[0] == "M2") {
      Halt();
      return false;
    }

    // other machine code to ignore?
    if (tokens[0].startsWith("M")) {
      Log("<font color='pink'>" + line + "</font>\n");
      return true;
    }

    // contains a comment?  if so remove it
    int index = line.indexOf('(');
    if (index != -1) {
      String comment = line.substring(index + 1, line.lastIndexOf(')'));
      line = line.substring(0, index).trim();
      Log("<font color='grey'>* " + comment + "</font\n");
      if (line.length() == 0) {
        // entire line was a comment.
        return true; // still ready to send
      }
    }

    // send relevant part of line to the robot
    SendLineToRobot(line);

    return false;
  }
Example #19
0
 private void resetButtonStatus() {
   for (JButton b : Arrays.asList(deleteButton, copyButton)) {
     ButtonModel m = b.getModel();
     m.setRollover(false);
     m.setArmed(false);
     m.setPressed(false);
     m.setSelected(false);
   }
 }
Example #20
0
 {
   for (myjava.gui.syntax.Painter painter : myjava.gui.syntax.Painter.getPainters()) {
     painterComboBox.addItem(painter);
     EntryListPanel panel = new EntryListPanel(painter);
     listPanelSet.add(panel);
     centerPanel.add(panel, painter.getName());
   }
   componentSet.addAll(Arrays.asList(matchBracket, painterComboBox, centerPanel));
 }
  /**
   * Begins the in-place refactoring operation.
   *
   * @return true if the in-place refactoring was successfully started, false if it failed to start
   *     and a dialog should be shown instead.
   */
  public boolean startInplaceIntroduceTemplate() {
    final boolean replaceAllOccurrences = isReplaceAllOccurrences();
    final Ref<Boolean> result = new Ref<>();
    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            () -> {
              final String[] names = suggestNames(replaceAllOccurrences, getLocalVariable());
              final V variable = createFieldToStartTemplateOn(replaceAllOccurrences, names);
              boolean started = false;
              if (variable != null) {
                int caretOffset = getCaretOffset();
                myEditor.getCaretModel().moveToOffset(caretOffset);
                myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);

                final LinkedHashSet<String> nameSuggestions = new LinkedHashSet<>();
                nameSuggestions.add(variable.getName());
                nameSuggestions.addAll(Arrays.asList(names));
                initOccurrencesMarkers();
                setElementToRename(variable);
                updateTitle(getVariable());
                started = super.performInplaceRefactoring(nameSuggestions);
                if (started) {
                  onRenameTemplateStarted();
                  myDocumentAdapter =
                      new DocumentAdapter() {
                        @Override
                        public void documentChanged(DocumentEvent e) {
                          if (myPreview == null) return;
                          final TemplateState templateState =
                              TemplateManagerImpl.getTemplateState(myEditor);
                          if (templateState != null) {
                            final TextResult value =
                                templateState.getVariableValue(
                                    InplaceRefactoring.PRIMARY_VARIABLE_NAME);
                            if (value != null) {
                              updateTitle(getVariable(), value.getText());
                            }
                          }
                        }
                      };
                  myEditor.getDocument().addDocumentListener(myDocumentAdapter);
                  updateTitle(getVariable());
                  if (TemplateManagerImpl.getTemplateState(myEditor) != null) {
                    myEditor.putUserData(ACTIVE_INTRODUCE, this);
                  }
                }
              }
              result.set(started);
              if (!started) {
                finish(true);
              }
            },
            getCommandName(),
            getCommandName());
    return result.get();
  }
  private class LibraryTableInvocationHandler implements InvocationHandler, ProxyDelegateAccessor {
    private final LibraryTable myDelegateTable;

    @NonNls
    private final Set<String> myCheckedNames =
        new HashSet<>(Arrays.asList("removeLibrary" /*,"createLibrary"*/));

    LibraryTableInvocationHandler(LibraryTable table) {
      myDelegateTable = table;
    }

    @Override
    public Object invoke(Object object, Method method, Object[] params) throws Throwable {
      final boolean needUpdate = myCheckedNames.contains(method.getName());
      try {
        final Object result = method.invoke(myDelegateTable, unwrapParams(params));
        if (result instanceof Library) {
          return Proxy.newProxyInstance(
              getClass().getClassLoader(),
              new Class[] {result instanceof LibraryEx ? LibraryEx.class : Library.class},
              new LibraryInvocationHandler((Library) result));
        } else if (result instanceof LibraryTable.ModifiableModel) {
          return Proxy.newProxyInstance(
              getClass().getClassLoader(),
              new Class[] {LibraryTableBase.ModifiableModel.class},
              new LibraryTableModelInvocationHandler((LibraryTable.ModifiableModel) result));
        }
        if (result instanceof Library[]) {
          Library[] libraries = (Library[]) result;
          for (int idx = 0; idx < libraries.length; idx++) {
            Library library = libraries[idx];
            libraries[idx] =
                (Library)
                    Proxy.newProxyInstance(
                        getClass().getClassLoader(),
                        new Class[] {
                          library instanceof LibraryEx ? LibraryEx.class : Library.class
                        },
                        new LibraryInvocationHandler(library));
          }
        }
        return result;
      } catch (InvocationTargetException e) {
        throw e.getCause();
      } finally {
        if (needUpdate) {
          updateOrderEntriesInEditors(true);
        }
      }
    }

    @Override
    public Object getDelegate() {
      return myDelegateTable;
    }
  }
Example #23
0
  /** Main function called by run() every loop. */
  public void tick() {
    long var1 = System.nanoTime();
    ++this.tickCounter;

    if (this.startProfiling) {
      this.startProfiling = false;
      this.theProfiler.profilingEnabled = true;
      this.theProfiler.clearProfiling();
    }

    this.theProfiler.startSection("root");
    this.updateTimeLightAndEntities();

    if (var1 - this.nanoTimeSinceStatusRefresh >= 5000000000L) {
      this.nanoTimeSinceStatusRefresh = var1;
      this.statusResponse.setPlayerCountData(
          new ServerStatusResponse.PlayerCountData(
              this.getMaxPlayers(), this.getCurrentPlayerCount()));
      GameProfile[] var3 = new GameProfile[Math.min(this.getCurrentPlayerCount(), 12)];
      int var4 =
          MathHelper.getRandomIntegerInRange(
              this.random, 0, this.getCurrentPlayerCount() - var3.length);

      for (int var5 = 0; var5 < var3.length; ++var5) {
        var3[var5] =
            ((EntityPlayerMP) this.serverConfigManager.playerEntityList.get(var4 + var5))
                .getGameProfile();
      }

      Collections.shuffle(Arrays.asList(var3));
      this.statusResponse.getPlayerCountData().setPlayers(var3);
    }

    if (this.tickCounter % 900 == 0) {
      this.theProfiler.startSection("save");
      this.serverConfigManager.saveAllPlayerData();
      this.saveAllWorlds(true);
      this.theProfiler.endSection();
    }

    this.theProfiler.startSection("tallying");
    this.tickTimeArray[this.tickCounter % 100] = System.nanoTime() - var1;
    this.theProfiler.endSection();
    this.theProfiler.startSection("snooper");

    if (!this.usageSnooper.isSnooperRunning() && this.tickCounter > 100) {
      this.usageSnooper.startSnooper();
    }

    if (this.tickCounter % 6000 == 0) {
      this.usageSnooper.addMemoryStatsToSnooper();
    }

    this.theProfiler.endSection();
    this.theProfiler.endSection();
  }
    /**
     * Removes specific rows from the list of reading lists.
     *
     * @param aRows rows to remove.
     */
    public void removeRows(int[] aRows) {
      Arrays.sort(aRows);

      java.util.List<ReadingList> newLists = new ArrayList<ReadingList>(Arrays.asList(lists));
      for (int i = aRows.length - 1; i >= 0; i--) {
        newLists.remove(aRows[i]);
      }

      setLists(newLists.toArray(new ReadingList[newLists.size()]));
    }
Example #25
0
 public void selectWindowInRow(
     @NotNull DataContext context, int relativePosition, boolean vertical) {
   final FileEditorManagerEx fileEditorManager = getFileEditorManager(context);
   final EditorWindow currentWindow = fileEditorManager.getCurrentWindow();
   if (currentWindow != null) {
     final EditorWindow[] windows = fileEditorManager.getWindows();
     final List<EditorWindow> row =
         findWindowsInRow(currentWindow, Arrays.asList(windows), vertical);
     selectWindow(currentWindow, row, relativePosition);
   }
 }
Example #26
0
 public static TreePath[] selectMaximals(final TreePath[] paths) {
   if (paths == null) return new TreePath[0];
   final TreePath[] noDuplicates = removeDuplicates(paths);
   final ArrayList<TreePath> result = new ArrayList<TreePath>();
   for (final TreePath path : noDuplicates) {
     final ArrayList<TreePath> otherPaths = new ArrayList<TreePath>(Arrays.asList(noDuplicates));
     otherPaths.remove(path);
     if (!isDescendants(path, otherPaths.toArray(new TreePath[otherPaths.size()])))
       result.add(path);
   }
   return result.toArray(new TreePath[result.size()]);
 }
  public static void main(String[] args) {

    // Page 45
    // ========

    IntStream.iterate(1, i -> i * 2).limit(10).forEachOrdered(System.out::println);

    IntStream.range(1, 6).forEach(System.out::print); // prints 123456

    // Page 46
    // ========

    List<Integer> intList = Arrays.asList(1, 2, 3);

    OptionalDouble maxDistance =
        intList.stream().map(i -> new Point(i % 3, i / 3)).mapToDouble(p -> p.distance(0, 0)).max();

    DoubleStream ds =
        intList.stream().map(i -> new Point(i % 3, i / 3)).mapToDouble(p -> p.distance(0, 0));

    OptionalDouble maxDistance1 = ds.max();

    // Page 48
    // ========

    Optional<Integer> max =
        Arrays.asList(1, 2, 3, 4, 5).stream().map(i -> i + 1).max(Integer::compareTo);

    // Page 49
    // ========

    OptionalInt max1 = IntStream.rangeClosed(1, 5).map(i -> i + 1).max();

    DoubleStream ds1 = IntStream.rangeClosed(1, 10).asDoubleStream();

    Stream<Integer> is = IntStream.rangeClosed(1, 10).boxed();

    Stream<Integer> integerStream = Stream.of(1, 2);
    IntStream is1 = integerStream.mapToInt(Integer::intValue);
  }
Example #28
0
  public Container CreateContentPane() {
    // Create the content-pane-to-be.
    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.setOpaque(true);

    // the log panel
    log = new JTextPane();
    log.setEditable(false);
    log.setBackground(Color.BLACK);
    logPane = new JScrollPane(log);
    kit = new HTMLEditorKit();
    doc = new HTMLDocument();
    log.setEditorKit(kit);
    log.setDocument(doc);
    DefaultCaret c = (DefaultCaret) log.getCaret();
    c.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    ClearLog();

    // the preview panel
    previewPane = new DrawPanel();
    previewPane.setPaperSize(paper_top, paper_bottom, paper_left, paper_right);

    // status bar
    statusBar = new StatusBar();
    Font f = statusBar.getFont();
    statusBar.setFont(f.deriveFont(Font.BOLD, 15));
    Dimension d = statusBar.getMinimumSize();
    d.setSize(d.getWidth(), d.getHeight() + 30);
    statusBar.setMinimumSize(d);

    // layout
    Splitter split = new Splitter(JSplitPane.VERTICAL_SPLIT);
    split.add(previewPane);
    split.add(logPane);
    split.setDividerSize(8);

    contentPane.add(statusBar, BorderLayout.SOUTH);
    contentPane.add(split, BorderLayout.CENTER);

    // open the file
    if (recentFiles[0].length() > 0) {
      OpenFileOnDemand(recentFiles[0]);
    }

    // connect to the last port
    ListSerialPorts();
    if (Arrays.asList(portsDetected).contains(recentPort)) {
      OpenPort(recentPort);
    }

    return contentPane;
  }
  @Override
  public UIDefaults getDefaults() {
    try {
      final Method superMethod = BasicLookAndFeel.class.getDeclaredMethod("getDefaults");
      superMethod.setAccessible(true);
      final UIDefaults metalDefaults = (UIDefaults) superMethod.invoke(new MetalLookAndFeel());

      final UIDefaults defaults = (UIDefaults) superMethod.invoke(base);
      if (SystemInfo.isLinux) {
        if (!Registry.is("darcula.use.native.fonts.on.linux")) {
          Font font = findFont("DejaVu Sans");
          if (font != null) {
            for (Object key : defaults.keySet()) {
              if (key instanceof String && ((String) key).endsWith(".font")) {
                defaults.put(key, new FontUIResource(font.deriveFont(13f)));
              }
            }
          }
        } else if (Arrays.asList("CN", "JP", "KR", "TW")
            .contains(Locale.getDefault().getCountry())) {
          for (Object key : defaults.keySet()) {
            if (key instanceof String && ((String) key).endsWith(".font")) {
              final Font font = defaults.getFont(key);
              if (font != null) {
                defaults.put(key, new FontUIResource("Dialog", font.getStyle(), font.getSize()));
              }
            }
          }
        }
      }

      LafManagerImpl.initInputMapDefaults(defaults);
      initIdeaDefaults(defaults);
      patchStyledEditorKit(defaults);
      patchComboBox(metalDefaults, defaults);
      defaults.remove("Spinner.arrowButtonBorder");
      defaults.put("Spinner.arrowButtonSize", JBUI.size(16, 5).asUIResource());
      MetalLookAndFeel.setCurrentTheme(createMetalTheme());
      if (SystemInfo.isWindows && Registry.is("ide.win.frame.decoration")) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
      }
      if (SystemInfo.isLinux && JBUI.isHiDPI()) {
        applySystemFonts(defaults);
      }
      defaults.put("EditorPane.font", defaults.getFont("TextField.font"));
      return defaults;
    } catch (Exception e) {
      log(e);
    }
    return super.getDefaults();
  }
Example #30
0
  private void processGeneList(Session session, Element element, HashMap additionalInformation) {

    String name = getAttribute(element, SessionAttribute.NAME.getText());

    String txt = element.getTextContent();
    String[] genes = txt.trim().split("\\s+");
    GeneList gl = new GeneList(name, Arrays.asList(genes));
    GeneListManager.getInstance().addGeneList(gl);
    session.setCurrentGeneList(gl);

    // Adjust frames
    processFrames(element);
  }