public void setSwingDataCollection(Collection<ICFSecurityISOCountryObj> value) {
   final String S_ProcName = "setSwingDataCollection";
   swingDataCollection = value;
   if (swingDataCollection == null) {
     arrayOfISOCountry = new ICFSecurityISOCountryObj[0];
   } else {
     int len = value.size();
     arrayOfISOCountry = new ICFSecurityISOCountryObj[len];
     Iterator<ICFSecurityISOCountryObj> iter = swingDataCollection.iterator();
     int idx = 0;
     while (iter.hasNext() && (idx < len)) {
       arrayOfISOCountry[idx++] = iter.next();
     }
     if (idx < len) {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(),
               S_ProcName,
               "Collection iterator did not fully populate the array copy");
     }
     if (iter.hasNext()) {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(),
               S_ProcName,
               "Collection iterator had left over items when done populating array copy");
     }
     Arrays.sort(arrayOfISOCountry, compareISOCountryByQualName);
   }
   PickerTableModel tblDataModel = getDataModel();
   if (tblDataModel != null) {
     tblDataModel.fireTableDataChanged();
   }
 }
Example #2
1
 public static void main(String[] args) {
   FastScanner in = new FastScanner(System.in);
   int sum = in.nextInt();
   int limit = in.nextInt();
   int cnt = 0;
   StringBuilder sb = new StringBuilder();
   Point[] points = new Point[limit + 1];
   points[0] = new Point(0, 0);
   for (int i = 1; i <= limit; i++) points[i] = new Point(i, lb(i));
   Arrays.sort(
       points,
       new Comparator<Point>() {
         public int compare(Point a, Point b) {
           return a.y - b.y;
         }
       });
   // System.out.println(Arrays.toString(points));
   for (int i = limit; i >= 1; i--) {
     if (sum >= points[i].y) {
       sum -= points[i].y;
       sb.append(" ");
       sb.append(points[i].x);
       cnt++;
     }
   }
   if (sum == 0) {
     System.out.println(cnt);
     System.out.println(sb.toString().trim());
   } else {
     System.out.println(-1);
   }
 }
Example #3
0
  /**
   * Paint to an offscreen graphic, e.g. a graphic for an image or svg file.
   *
   * @param g
   * @param rect
   */
  public void paintOffscreen(Graphics2D g, Rectangle rect) {

    // Get the components of the sort by X position.
    Component[] components = getComponents();
    Arrays.sort(
        components,
        new Comparator<Component>() {
          public int compare(Component component, Component component1) {
            return component.getX() - component1.getX();
          }
        });

    for (Component c : this.getComponents()) {

      if (c instanceof DataPanel) {
        Graphics2D g2d = (Graphics2D) g.create();
        Rectangle clipRect = new Rectangle(c.getBounds());
        clipRect.height = rect.height;
        g2d.setClip(clipRect);
        g2d.translate(c.getX(), 0);
        ((DataPanel) c).paintOffscreen(g2d, rect);
      }
    }
    // super.paintBorder(g);
  }
  private void sort() {
    final Locale loc = getLocale();
    final Collator collator = Collator.getInstance(loc);
    final Comparator<Locale> comp =
        new Comparator<Locale>() {
          public int compare(Locale a, Locale b) {
            return collator.compare(a.getDisplayName(loc), b.getDisplayName(loc));
          }
        };
    Arrays.sort(locales, comp);
    setModel(
        new ComboBoxModel<Locale>() {
          public Locale getElementAt(int i) {
            return locales[i];
          }

          public int getSize() {
            return locales.length;
          }

          public void addListDataListener(ListDataListener l) {}

          public void removeListDataListener(ListDataListener l) {}

          public Locale getSelectedItem() {
            return selected >= 0 ? locales[selected] : null;
          }

          public void setSelectedItem(Object anItem) {
            if (anItem == null) selected = -1;
            else selected = Arrays.binarySearch(locales, (Locale) anItem, comp);
          }
        });
    setSelectedItem(selected);
  }
  /**
   * When the user has to specify file names, he can use wildcards (*, ?). This methods handles the
   * usage of these wildcards.
   *
   * @param path The path were to search
   * @param s Wilcards
   * @param sort Set to true will sort file names
   * @return An array of String which contains all files matching <code>s</code> in current
   *     directory.
   */
  public static String[] getWildCardMatches(String path, String s, boolean sort) {
    if (s == null) return null;

    String files[];
    String filesThatMatch[];
    String args = new String(s.trim());
    ArrayList filesThatMatchVector = new ArrayList();

    if (path == null) path = getUserDirectory();

    files = (new File(path)).list();
    if (files == null) return null;

    for (int i = 0; i < files.length; i++) {
      if (match(args, files[i])) {
        File temp = new File(getUserDirectory(), files[i]);
        filesThatMatchVector.add(new String(temp.getName()));
      }
    }

    Object[] o = filesThatMatchVector.toArray();
    filesThatMatch = new String[o.length];
    for (int i = 0; i < o.length; i++) filesThatMatch[i] = o[i].toString();
    o = null;
    filesThatMatchVector = null;

    if (sort) Arrays.sort(filesThatMatch);

    return filesThatMatch;
  }
  /**
   * Calls all public methods declared in the class corresponding to the given object. Does not
   * include methods from superclasses.
   *
   * @param object object to call the public methods on
   * @param comparator method comparator, allows running the methods in a specific order
   * @return list of methods invoked, including the parameters used for calling them
   */
  private static List<MethodInvocation> callPublicMethodsInOrder(
      Object object, Comparator<Method> comparator) {
    try {
      List<MethodInvocation> invocations = new ArrayList<>();
      Method[] methods = object.getClass().getDeclaredMethods();
      if (comparator != null) Arrays.sort(methods, comparator);

      for (Method method : methods) {
        if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers()))
          continue;

        Object[] params = new Object[method.getParameterTypes().length];
        for (int i = 0; i < method.getParameterTypes().length; i++) {
          params[i] = instantiateType(method.getParameterTypes()[i]);
        }
        method.invoke(object, params);
        invocations.add(new MethodInvocation(method.getName(), params));
      }
      return invocations;
    } catch (Exception ex) {
      ex.printStackTrace();
      assertTrue(
          "Error calling public methods on object "
              + object
              + " ("
              + object.getClass().getSimpleName()
              + ")",
          false);
      return new ArrayList<>();
    }
  }
 public void loadData(boolean forceReload) {
   ICFFreeSwitchSchemaObj schemaObj = swingSchema.getSchema();
   if ((containingCluster == null) || forceReload) {
     CFSecurityAuthorization auth = schemaObj.getAuthorization();
     long containingClusterId = auth.getSecClusterId();
     containingCluster = schemaObj.getClusterTableObj().readClusterByIdIdx(containingClusterId);
   }
   if ((listOfTenant == null) || forceReload) {
     arrayOfTenant = null;
     listOfTenant =
         schemaObj
             .getTenantTableObj()
             .readTenantByClusterIdx(containingCluster.getRequiredId(), swingIsInitializing);
     if (listOfTenant != null) {
       Object objArray[] = listOfTenant.toArray();
       if (objArray != null) {
         int len = objArray.length;
         arrayOfTenant = new ICFSecurityTenantObj[len];
         for (int i = 0; i < len; i++) {
           arrayOfTenant[i] = (ICFSecurityTenantObj) objArray[i];
         }
         Arrays.sort(arrayOfTenant, compareTenantByQualName);
       }
     }
   }
 }
Example #8
0
 // Sorts labels from the mapping.  We may get rid of this later perhaps.
 String[] revisedLabels(HashMap map) {
   // Sort labels
   String[] labels = new String[map.size()];
   labels = (String[]) (map.keySet().toArray(labels));
   Arrays.sort(labels);
   return labels;
 }
 Entry[] getParents() {
   List<Entry> list = new ArrayList<Entry>();
   getParents(list);
   Entry[] array = list.toArray(new Entry[list.size()]);
   Arrays.sort(array, new StandardUtilities.StringCompare<Entry>(true));
   return array;
 }
  public NaturalBreaksClassifier(QueryResults qr, int numCategories, Color color1, Color color2) {
    double[] list = new double[qr.items.size()];

    Iterator<QueryResults.QueryResultItem> qrIt = qr.items.values().iterator();

    for (int i = 0; i < list.length; i++) {
      list[i] = qrIt.next().value;
    }

    Arrays.sort(list);

    // we can't classify into more bins than we have values
    if (numCategories > list.length) numCategories = list.length;

    double[] breaks = buildJenksBreaks(list, numCategories);

    if (breaks.length == 0) return;

    for (int i = 0; i < numCategories; i++) {
      // numcategories - 1: fencepost problem. The highest value should get color2
      Color c;
      if (numCategories > 1)
        c = interpolateColor(color1, color2, (float) ((float) i / (float) (numCategories - 1)));
      else c = interpolateColor(color1, color2, 0.5f);

      bins.add(new Bin(breaks[i], breaks[i + 1], c));
    }

    addPercentagesToBins(qr.maxPossible);

    bins.get(0).lower -= 0.00000001;
    bins.get(bins.size() - 1).upper += 0.00000001;
  }
Example #11
0
 /** List results by alphabetical name */
 private void listByProgramName() {
   int nresult = datasets.size();
   String res[] = new String[nresult];
   for (int i = 0; i < nresult; i++) res[i] = (String) datasets.getElementAt(i);
   Arrays.sort(res);
   datasets.removeAllElements();
   for (int i = 0; i < nresult; i++) datasets.addElement(res[i]);
 }
 // calculates average of the median values in the selected part of the array. E.g. for part=3
 // returns average in the middle third.
 public static long averageAmongMedians(@NotNull long[] time, int part) {
   assert part >= 1;
   int n = time.length;
   Arrays.sort(time);
   long total = 0;
   for (int i = n / 2 - n / part / 2; i < n / 2 + n / part / 2; i++) {
     total += time[i];
   }
   return total / (n / part);
 }
    /**
     * 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()]));
    }
  /** Invoked via reflection. */
  LafManagerImpl() {
    myListenerList = new EventListenerList();

    List<UIManager.LookAndFeelInfo> lafList = ContainerUtil.newArrayList();

    if (SystemInfo.isMac) {
      if (Registry.is("ide.mac.yosemite.laf")
          && isIntelliJLafEnabled()
          && SystemInfo.isJavaVersionAtLeast("1.8")) {
        lafList.add(new UIManager.LookAndFeelInfo("Default", IntelliJLaf.class.getName()));
      } else {
        lafList.add(
            new UIManager.LookAndFeelInfo("Default", UIManager.getSystemLookAndFeelClassName()));
      }
    } else {
      if (isIntelliJLafEnabled()) {
        lafList.add(new IntelliJLookAndFeelInfo());
      } else {
        lafList.add(new IdeaLookAndFeelInfo());
      }
      for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
        String name = laf.getName();
        if (!"Metal".equalsIgnoreCase(name)
            && !"CDE/Motif".equalsIgnoreCase(name)
            && !"Nimbus".equalsIgnoreCase(name)
            && !"Windows Classic".equalsIgnoreCase(name)
            && !name.startsWith("JGoodies")) {
          lafList.add(laf);
        }
      }
    }

    lafList.add(new DarculaLookAndFeelInfo());

    myLaFs = lafList.toArray(new UIManager.LookAndFeelInfo[lafList.size()]);

    if (!SystemInfo.isMac) {
      // do not sort LaFs on mac - the order is determined as Default, Darcula.
      // when we leave only system LaFs on other OSes, the order also should be determined as
      // Default, Darcula

      Arrays.sort(
          myLaFs,
          new Comparator<UIManager.LookAndFeelInfo>() {
            @Override
            public int compare(UIManager.LookAndFeelInfo obj1, UIManager.LookAndFeelInfo obj2) {
              String name1 = obj1.getName();
              String name2 = obj2.getName();
              return name1.compareToIgnoreCase(name2);
            }
          });
    }

    myCurrentLaf = getDefaultLaf();
  }
  public final int readCharacter(final char[] allowed) throws IOException {
    // if we restrict to a limited set and the current character
    // is not in the set, then try again.
    char c;

    Arrays.sort(allowed); // always need to sort before binarySearch

    while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0) ;

    return c;
  }
  private Row[] getViewToModel() {
    if (viewToModel == null) {
      int tableModelRowCount = tableModel.getRowCount();
      viewToModel = new Row[tableModelRowCount];
      for (int row = 0; row < tableModelRowCount; row++) {
        viewToModel[row] = new Row(row);
      }

      if (isSorting()) {
        Arrays.sort(viewToModel);
      }
    }
    return viewToModel;
  }
  private static HighlightVisitor[] filterVisitors(
      HighlightVisitor[] highlightVisitors, final PsiFile file) {
    final List<HighlightVisitor> visitors =
        new ArrayList<HighlightVisitor>(highlightVisitors.length);
    List<HighlightVisitor> list = Arrays.asList(highlightVisitors);
    for (HighlightVisitor visitor :
        DumbService.getInstance(file.getProject()).filterByDumbAwareness(list)) {
      if (visitor.suitableForFile(file)) visitors.add(visitor);
    }
    LOG.assertTrue(!visitors.isEmpty(), list);

    HighlightVisitor[] visitorArray = visitors.toArray(new HighlightVisitor[visitors.size()]);
    Arrays.sort(visitorArray, VISITOR_ORDER_COMPARATOR);
    return visitorArray;
  }
 WordListModel(ASDGrammar grammar) {
   Set entrySet = grammar.lexicon().entrySet();
   ArrayList words = new ArrayList(entrySet.size());
   for (Iterator it = entrySet.iterator(); it.hasNext(); ) {
     Map.Entry e = (Map.Entry) it.next();
     String word = (String) e.getKey();
     words.add(word);
   }
   Object[] wordArray = words.toArray();
   if (words.size() > 1)
     //       Arrays.sort(wordArray);
     Arrays.sort(wordArray, new WordComparator());
   for (int j = 0; j < wordArray.length; j++) {
     this.addElement((String) wordArray[j]);
   }
 }
Example #19
0
 public void run() {
   Comparator<Double> comp =
       new Comparator<Double>() {
         public int compare(Double i1, Double i2) {
           component.setValues(values, i1, i2);
           try {
             if (run) Thread.sleep(DELAY);
             else gate.acquire();
           } catch (InterruptedException exception) {
             Thread.currentThread().interrupt();
           }
           return i1.compareTo(i2);
         }
       };
   Arrays.sort(values, comp);
   component.setValues(values, null, null);
 }
Example #20
0
 private void sort(String key, Object3DGui[] objectsGui, int structureIdx) {
   Object3DGui.setAscendingOrger(((ObjectManagerLayout) layout).getAscendingOrder());
   HashMap<Integer, BasicDBObject> objects =
       Core.getExperiment().getConnector().getObjects(currentNucId, structureIdx);
   boolean notFound = false;
   for (Object3DGui o : objectsGui) {
     BasicDBObject dbo = objects.get(o.getLabel());
     if (dbo != null) {
       if (dbo.containsField(key)) o.setValue(dbo.getDouble(key));
       else {
         o.setValue(-1);
         notFound = true;
       }
     }
   }
   if (notFound)
     ij.IJ.log("Warning measurement: " + key + " not found for one or several objects");
   Arrays.sort(objectsGui);
 }
 public void loadData(boolean forceReload) {
   ICFBamSchemaObj schemaObj = swingSchema.getSchema();
   if ((listOfAccessFrequency == null) || forceReload) {
     arrayOfAccessFrequency = null;
     listOfAccessFrequency =
         schemaObj.getAccessFrequencyTableObj().readAllAccessFrequency(swingIsInitializing);
     if (listOfAccessFrequency != null) {
       Object objArray[] = listOfAccessFrequency.toArray();
       if (objArray != null) {
         int len = objArray.length;
         arrayOfAccessFrequency = new ICFBamAccessFrequencyObj[len];
         for (int i = 0; i < len; i++) {
           arrayOfAccessFrequency[i] = (ICFBamAccessFrequencyObj) objArray[i];
         }
         Arrays.sort(arrayOfAccessFrequency, compareAccessFrequencyByQualName);
       }
     }
   }
 }
 public void loadData(boolean forceReload) {
   ICFSecuritySchemaObj schemaObj = swingSchema.getSchema();
   if ((listOfISOTimezone == null) || forceReload) {
     arrayOfISOTimezone = null;
     listOfISOTimezone =
         schemaObj.getISOTimezoneTableObj().readAllISOTimezone(swingIsInitializing);
     if (listOfISOTimezone != null) {
       Object objArray[] = listOfISOTimezone.toArray();
       if (objArray != null) {
         int len = objArray.length;
         arrayOfISOTimezone = new ICFSecurityISOTimezoneObj[len];
         for (int i = 0; i < len; i++) {
           arrayOfISOTimezone[i] = (ICFSecurityISOTimezoneObj) objArray[i];
         }
         Arrays.sort(arrayOfISOTimezone, compareISOTimezoneByQualName);
       }
     }
   }
 }
Example #23
0
  private void recalculateIconRenderersWidth() {
    myLineToRenderersMap.clear();
    for (EditorMessageIconRenderer renderer : myIconRenderers) {
      int yCoordinate = getIconCoordinate(renderer);
      if (yCoordinate < 0) {
        continue;
      }
      List<IconRendererLayoutConstraint> renderersForLine = myLineToRenderersMap.get(yCoordinate);
      if (renderersForLine == null) {
        renderersForLine = new SortedList(myIconRenderersComparator);
        myLineToRenderersMap.put(yCoordinate, renderersForLine);
      }
      renderersForLine.add(new IconRendererLayoutConstraint(renderer));
    }

    myIconRenderersWidth = MIN_ICON_RENDERERS_WIDTH;
    myMaxIconHeight = 0;
    int[] sortedYCoordinates = myLineToRenderersMap.keys();
    Arrays.sort(sortedYCoordinates);

    int initialOffset = getIconRenderersOffset();
    for (int y : sortedYCoordinates) {
      List<IconRendererLayoutConstraint> row = myLineToRenderersMap.get(y);
      assert row.size() != 0;
      int maxIconHeight = 0;
      for (IconRendererLayoutConstraint rendererConstraint : row) {
        maxIconHeight =
            Math.max(maxIconHeight, rendererConstraint.getIconRenderer().getIcon().getIconHeight());
      }
      myMaxIconHeight = Math.max(myMaxIconHeight, maxIconHeight);
      int offset = initialOffset + LEFT_GAP;
      for (Iterator<IconRendererLayoutConstraint> it = row.iterator(); it.hasNext(); ) {
        IconRendererLayoutConstraint rendererConstraint = it.next();
        rendererConstraint.setX(offset);
        offset += rendererConstraint.getIconRenderer().getIcon().getIconWidth();
        if (it.hasNext()) {
          offset += GAP_BETWEEN_ICONS;
        }
      }
      myIconRenderersWidth = Math.max(myIconRenderersWidth, offset - initialOffset);
    }
  }
  public Object getChild(Object parent, int index) {
    Collection c = null;

    if (parent instanceof IProject) {
      if (activeOnly()) c = CurrentProject.getTaskList().getActiveSubTasks(null, CurrentDate.get());
      else c = CurrentProject.getTaskList().getTopLevelTasks();
    } else {
      ITask t = (ITask) parent;
      if (activeOnly())
        c = CurrentProject.getTaskList().getActiveSubTasks(t.getID(), CurrentDate.get());
      else c = t.getSubTasks();
    }

    Object array[] = c.toArray();
    Arrays.sort(array, comparator);
    if (opposite) {
      return array[array.length - index - 1];
    }
    return array[index];
  }
 @NotNull
 public static List<GotoRelatedItem> collectRelatedItems(
     @NotNull PsiElement contextElement, @Nullable DataContext dataContext) {
   Set<GotoRelatedItem> items = ContainerUtil.newLinkedHashSet();
   for (GotoRelatedProvider provider : Extensions.getExtensions(GotoRelatedProvider.EP_NAME)) {
     items.addAll(provider.getItems(contextElement));
     if (dataContext != null) {
       items.addAll(provider.getItems(dataContext));
     }
   }
   GotoRelatedItem[] result = items.toArray(new GotoRelatedItem[items.size()]);
   Arrays.sort(
       result,
       (i1, i2) -> {
         String o1 = i1.getGroup();
         String o2 = i2.getGroup();
         return StringUtil.isEmpty(o1) ? 1 : StringUtil.isEmpty(o2) ? -1 : o1.compareTo(o2);
       });
   return Arrays.asList(result);
 }
  private void draw(DrawContext dc) {
    this.referencePoint = this.computeReferencePoint(dc);

    this.assembleTiles(dc); // Determine the tiles to draw.

    if (this.currentTiles.size() >= 1) {
      MercatorTextureTile[] sortedTiles = new MercatorTextureTile[this.currentTiles.size()];
      sortedTiles = this.currentTiles.toArray(sortedTiles);
      Arrays.sort(sortedTiles, levelComparer);

      GL gl = dc.getGL();

      if (this.isUseTransparentTextures() || this.getOpacity() < 1) {
        gl.glPushAttrib(GL.GL_COLOR_BUFFER_BIT | GL.GL_POLYGON_BIT | GL.GL_CURRENT_BIT);
        gl.glColor4d(1d, 1d, 1d, this.getOpacity());
        gl.glEnable(GL.GL_BLEND);
        gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
      } else {
        gl.glPushAttrib(GL.GL_COLOR_BUFFER_BIT | GL.GL_POLYGON_BIT);
      }

      gl.glPolygonMode(GL.GL_FRONT, GL.GL_FILL);
      gl.glEnable(GL.GL_CULL_FACE);
      gl.glCullFace(GL.GL_BACK);

      dc.setPerFrameStatistic(
          PerformanceStatistic.IMAGE_TILE_COUNT, this.tileCountName, this.currentTiles.size());
      dc.getGeographicSurfaceTileRenderer().renderTiles(dc, this.currentTiles);

      gl.glPopAttrib();

      if (this.drawTileIDs) this.drawTileIDs(dc, this.currentTiles);

      if (this.drawBoundingVolumes) this.drawBoundingVolumes(dc, this.currentTiles);

      this.currentTiles.clear();
    }

    this.sendRequests();
    this.requestQ.clear();
  }
 private static void setRenderers(JTable table, String type) {
   final MetricTableModel model = (MetricTableModel) table.getModel();
   final MetricInstance[] metrics = model.getMetricsInstances();
   Arrays.sort(metrics, new MetricInstanceAbbreviationComparator());
   final TableColumnModel columnModel = table.getColumnModel();
   for (int i = 0; i < model.getColumnCount(); i++) {
     final String columnName = model.getColumnName(i);
     final TableColumn column = columnModel.getColumn(i);
     if (columnName.equals(type)) {
       column.setCellRenderer(new MetricCellRenderer(null));
       column.setHeaderRenderer(new HeaderRenderer(null, model, SwingConstants.LEFT));
     } else {
       final MetricInstance metricInstance = model.getMetricForColumn(i);
       final TableCellRenderer renderer = new MetricCellRenderer(metricInstance);
       column.setCellRenderer(renderer);
       final Metric metric = metricInstance.getMetric();
       final String displayName = metric.getDisplayName();
       column.setHeaderRenderer(new HeaderRenderer(displayName, model, SwingConstants.RIGHT));
     }
   }
 }
Example #28
0
  void updateTable() {
    IDevice[] devices = myBridge != null ? getFilteredDevices(myBridge) : EMPTY_DEVICE_ARRAY;
    if (devices.length > 1) {
      // sort by API level
      Arrays.sort(
          devices,
          new Comparator<IDevice>() {
            @Override
            public int compare(IDevice device1, IDevice device2) {
              int apiLevel1 = safeGetApiLevel(device1);
              int apiLevel2 = safeGetApiLevel(device2);
              return apiLevel2 - apiLevel1;
            }

            private int safeGetApiLevel(IDevice device) {
              try {
                String s = device.getProperty(IDevice.PROP_BUILD_API_LEVEL);
                return StringUtil.isNotEmpty(s) ? Integer.parseInt(s) : 0;
              } catch (Exception e) {
                return 0;
              }
            }
          });
    }

    if (!Arrays.equals(myDisplayedDevices, devices)) {
      myDetectedDevicesRef.set(devices);
      ApplicationManager.getApplication()
          .invokeLater(
              new Runnable() {
                @Override
                public void run() {
                  refreshTable();
                }
              },
              ModalityState.stateForComponent(myDeviceTable));
    }
  }
Example #29
0
 public String[] getNames() {
   String[] names = new String[table.size()];
   names = table.keySet().toArray(names);
   Arrays.sort(names);
   return names;
 }
  @Override
  public void invoke(
      @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
    try {
      final XmlTag contextTag = getContextTag(editor, file);
      if (contextTag == null) {
        throw new CommonRefactoringUtil.RefactoringErrorHintException(
            "Caret should be positioned inside a tag");
      }
      XmlElementDescriptor currentTagDescriptor = contextTag.getDescriptor();
      assert currentTagDescriptor != null;
      final XmlElementDescriptor[] descriptors =
          currentTagDescriptor.getElementsDescriptors(contextTag);
      Arrays.sort(
          descriptors,
          new Comparator<XmlElementDescriptor>() {
            @Override
            public int compare(XmlElementDescriptor o1, XmlElementDescriptor o2) {
              return o1.getName().compareTo(o2.getName());
            }
          });
      final JBList list = new JBList(descriptors);
      list.setCellRenderer(new MyListCellRenderer());
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              final XmlElementDescriptor selected = (XmlElementDescriptor) list.getSelectedValue();
              new WriteCommandAction.Simple(project, "Generate XML Tag", file) {
                @Override
                protected void run() {
                  if (selected == null) return;
                  XmlTag newTag = createTag(contextTag, selected);

                  PsiElement anchor = getAnchor(contextTag, editor, selected);
                  if (anchor == null) { // insert it in the cursor position
                    int offset = editor.getCaretModel().getOffset();
                    Document document = editor.getDocument();
                    document.insertString(offset, newTag.getText());
                    PsiDocumentManager.getInstance(project).commitDocument(document);
                    newTag =
                        PsiTreeUtil.getParentOfType(
                            file.findElementAt(offset + 1), XmlTag.class, false);
                  } else {
                    newTag = (XmlTag) contextTag.addAfter(newTag, anchor);
                  }
                  if (newTag != null) {
                    generateTag(newTag, editor);
                  }
                }
              }.execute();
            }
          };
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        XmlElementDescriptor descriptor =
            ContainerUtil.find(
                descriptors,
                new Condition<XmlElementDescriptor>() {
                  @Override
                  public boolean value(XmlElementDescriptor xmlElementDescriptor) {
                    return xmlElementDescriptor.getName().equals(TEST_THREAD_LOCAL.get());
                  }
                });
        list.setSelectedValue(descriptor, false);
        runnable.run();
      } else {
        JBPopupFactory.getInstance()
            .createListPopupBuilder(list)
            .setTitle("Choose Tag Name")
            .setItemChoosenCallback(runnable)
            .setFilteringEnabled(
                new Function<Object, String>() {
                  @Override
                  public String fun(Object o) {
                    return ((XmlElementDescriptor) o).getName();
                  }
                })
            .createPopup()
            .showInBestPositionFor(editor);
      }
    } catch (CommonRefactoringUtil.RefactoringErrorHintException e) {
      HintManager.getInstance().showErrorHint(editor, e.getMessage());
    }
  }