public boolean equals(Object other) { if (other instanceof TypeToNameMap) { TypeToNameMap otherMap = (TypeToNameMap) other; return myPatterns.equals(otherMap.myPatterns) && myNames.equals(otherMap.myNames); } return false; }
@FXML void loadSelectedPlaylist() { Playlist p = (Playlist) playlistsView.getSelectionModel().getSelectedItem(); if (p == null) return; tracksView.setPlaceholder(offlinePlaceHolder); Platform.runLater( () -> { List<Track> tracks = p.getTracks(); tracksView.getItems().clear(); for (int i = tracks.size() - 1; i >= 0; i--) { tracksView.getItems().add(tracks.get(i)); } if (findTrack) { Platform.runLater( () -> { tracksView.getSelectionModel().select(currentTrack); tracksView.scrollTo(currentTrack); tracksView.requestFocus(); findTrack = false; }); } else { if (tracksView.getItems().size() > 0) { tracksView.scrollTo(0); } } }); }
@NotNull public static List<VcsDirectoryMapping> addMapping( @NotNull List<VcsDirectoryMapping> existingMappings, @NotNull String path, @NotNull String vcs) { List<VcsDirectoryMapping> mappings = new ArrayList<VcsDirectoryMapping>(existingMappings); for (Iterator<VcsDirectoryMapping> iterator = mappings.iterator(); iterator.hasNext(); ) { VcsDirectoryMapping mapping = iterator.next(); if (mapping.isDefaultMapping() && StringUtil.isEmptyOrSpaces(mapping.getVcs())) { LOG.debug("Removing <Project> -> <None> mapping"); iterator.remove(); } else if (FileUtil.pathsEqual(mapping.getDirectory(), path)) { if (!StringUtil.isEmptyOrSpaces(mapping.getVcs())) { LOG.warn( "Substituting existing mapping [" + path + "] -> [" + mapping.getVcs() + "] with [" + vcs + "]"); } else { LOG.debug("Removing [" + path + "] -> <None> mapping"); } iterator.remove(); } } mappings.add(new VcsDirectoryMapping(path, vcs)); return mappings; }
public void copyFrom(TypeToNameMap from) { assert from != this; myPatterns.clear(); myPatterns.addAll(from.myPatterns); myNames.clear(); myNames.addAll(from.myNames); }
// check if sudo password is correct (so sudo can be used in all other scripts, even without // password, lasts for 5 minutes) private void doSudoCmd() { String pass = passwordField.getText(); File file = null; try { // write file in /tmp file = new File("/tmp/cmd_sudo.sh"); // ""c:/temp/run.bat"" FileOutputStream fos = new FileOutputStream(file); fos.write("echo $password | sudo -S ls\nexit $?".getBytes()); // "echo $password > pipo.txt" fos.close(); // execute HashMap vars = new HashMap(); vars.put("password", pass); List oses = new ArrayList(); oses.add( new OsConstraint( "unix", null, null, null)); // "windows",System.getProperty("os.name"),System.getProperty("os.version"),System.getProperty("os.arch"))); ArrayList plist = new ArrayList(); ParsableFile pf = new ParsableFile(file.getAbsolutePath(), null, null, oses); plist.add(pf); ScriptParser sp = new ScriptParser(plist, new VariableSubstitutor(vars)); sp.parseFiles(); ArrayList elist = new ArrayList(); ExecutableFile ef = new ExecutableFile( file.getAbsolutePath(), ExecutableFile.POSTINSTALL, ExecutableFile.ABORT, oses, false); elist.add(ef); FileExecutor fe = new FileExecutor(elist); int retval = fe.executeFiles(ExecutableFile.POSTINSTALL, this); if (retval == 0) { idata.setVariable("password", pass); isValid = true; } // else is already showing dialog // { // JOptionPane.showMessageDialog(this, "Cannot execute 'sudo' cmd, check your password", // "Error", JOptionPane.ERROR_MESSAGE); // } } catch (Exception e) { // JOptionPane.showMessageDialog(this, "Cannot execute 'sudo' cmd, check your password", // "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); isValid = false; } try { if (file != null && file.exists()) file.delete(); // you don't want the file with password tobe arround, in case of error } catch (Exception e) { // ignore } }
public Labyrinth(String fileName) throws Exception { List<GeometricObject> objs = new ArrayList<GeometricObject>(); String[] lines = FileUtil.readTextLines(fileName); int nRect = 0; int nSpace = 0; int maxWidth = 0; for (int y = 0; y < lines.length; y++) { char[] line = lines[y].toCharArray(); if (maxWidth < line.length) { maxWidth = line.length; } for (int x = 0; x < line.length; x++) { switch (line[x]) { case rectangleChar: objs.add( new GeometricObject( new Vertex(rectangleLength * x, rectangleLength * y), rectangleLength, rectangleLength)); nRect++; break; case spaceChar: nSpace++; break; default: throw new Exception("Unsupported char:" + line[x] + " in file:" + fileName); } } } this.objects = objs.toArray(new GeometricObject[0]); this.width = maxWidth * (int) rectangleLength; this.height = lines.length * (int) rectangleLength; }
@Nullable private LocalQuickFix[] createNPEFixes( PsiExpression qualifier, PsiExpression expression, boolean onTheFly) { if (qualifier == null || expression == null) return null; if (qualifier instanceof PsiMethodCallExpression) return null; if (qualifier instanceof PsiLiteralExpression && ((PsiLiteralExpression) qualifier).getValue() == null) return null; try { final List<LocalQuickFix> fixes = new SmartList<LocalQuickFix>(); if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) { final Project project = qualifier.getProject(); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); final PsiBinaryExpression binary = (PsiBinaryExpression) elementFactory.createExpressionFromText("a != null", null); binary.getLOperand().replace(qualifier); fixes.add(new AddAssertStatementFix(binary)); } addSurroundWithIfFix(qualifier, fixes, onTheFly); if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) { fixes.add(new ReplaceWithTernaryOperatorFix(qualifier)); } return fixes.toArray(new LocalQuickFix[fixes.size()]); } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
public boolean avrdude(Collection params) throws RunnerException { List commandDownloader = new ArrayList(); commandDownloader.add("avrdude"); // Point avrdude at its config file since it's in a non-standard location. if (Base.isMacOS()) { commandDownloader.add("-C" + "hardware/tools/avr/etc/avrdude.conf"); } else if (Base.isWindows()) { String userdir = System.getProperty("user.dir") + File.separator; commandDownloader.add("-C" + userdir + "hardware/tools/avr/etc/avrdude.conf"); } else { // ???: is it better to have Linux users install avrdude themselves, in // a way that it can find its own configuration file? commandDownloader.add("-C" + "hardware/tools/avrdude.conf"); } if (Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } // XXX: quick hack to chop the "atmega" off of "atmega8" and "atmega168", // then shove an "m" at the beginning. won't work for attiny's, etc. commandDownloader.add( "-pm" + Preferences.get("boards." + Preferences.get("board") + ".build.mcu").substring(6)); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); }
@Override protected ValidationInfo doValidate() { final String resourceName = getResourceName(); final Module selectedModule = getModule(); final List<String> directoryNames = getDirNames(); final String fileName = getFileName(); if (resourceName.length() == 0) { return new ValidationInfo("specify resource name", myNameField); } else if (!AndroidResourceUtil.isCorrectAndroidResourceName(resourceName)) { return new ValidationInfo(resourceName + " is not correct resource name", myNameField); } else if (fileName.length() == 0) { return new ValidationInfo("specify file name", myFileNameCombo); } else if (selectedModule == null) { return new ValidationInfo("specify module", myModuleCombo); } else if (directoryNames.size() == 0) { return new ValidationInfo("choose directories", myDirectoriesList); } final ValidationInfo info = checkIfResourceAlreadyExists( selectedModule, resourceName, myResourceType, directoryNames, fileName); if (info != null) { return info; } return null; }
private void hideNestedTable(int level) { int n = nestedTableList.size(); for (int i = n - 1; i >= level; i--) { NestedTable ntable = nestedTableList.get(i); ntable.hide(); } }
public void showAtts() { if (ds == null) return; if (attTable == null) { // global attributes attTable = new BeanTableSorted( AttributeBean.class, (PreferencesExt) prefs.node("AttributeBeans"), false); PopupMenu varPopup = new ucar.nc2.ui.widget.PopupMenu(attTable.getJTable(), "Options"); varPopup.addAction( "Show Attribute", new AbstractAction() { public void actionPerformed(ActionEvent e) { AttributeBean bean = (AttributeBean) attTable.getSelectedBean(); if (bean != null) { infoTA.setText(bean.att.toString()); infoTA.gotoTop(); infoWindow.show(); } } }); attWindow = new IndependentWindow("Global Attributes", BAMutil.getImage("netcdfUI"), attTable); attWindow.setBounds( (Rectangle) prefs.getBean("AttWindowBounds", new Rectangle(300, 100, 500, 800))); } List<AttributeBean> attlist = new ArrayList<AttributeBean>(); for (Attribute att : ds.getGlobalAttributes()) { attlist.add(new AttributeBean(att)); } attTable.setBeans(attlist); attWindow.show(); }
@NotNull public static PsiMethod[] findMethodsByName( @NotNull PsiClass aClass, String name, boolean checkBases) { List<PsiMember> methods = findByMap(aClass, name, checkBases, MemberType.METHOD); //noinspection SuspiciousToArrayCall return methods.toArray(new PsiMethod[methods.size()]); }
@NotNull private static List<PsiMethod> findMethodsBySignature( @NotNull PsiClass aClass, @NotNull PsiMethod patternMethod, boolean checkBases, boolean stopOnFirst) { final PsiMethod[] methodsByName = aClass.findMethodsByName(patternMethod.getName(), checkBases); if (methodsByName.length == 0) return Collections.emptyList(); final List<PsiMethod> methods = new SmartList<PsiMethod>(); final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY); for (final PsiMethod method : methodsByName) { final PsiClass superClass = method.getContainingClass(); final PsiSubstitutor substitutor; if (checkBases && !aClass.equals(superClass)) { substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY); } else { substitutor = PsiSubstitutor.EMPTY; } final MethodSignature signature = method.getSignature(substitutor); if (signature.equals(patternSignature)) { methods.add(method); if (stopOnFirst) { break; } } } return methods; }
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == add) { // int sel = userTable.getSelectedRow(); // if (sel < 0) // sel = 0; nameTf.setText(""); abbrTf.setText(""); if (JOptionPane.showConfirmDialog( dialog, journalEditPanel, Localization.lang("Edit journal"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { journals.add(new JournalEntry(nameTf.getText(), abbrTf.getText())); // setValueAt(nameTf.getText(), sel, 0); // setValueAt(abbrTf.getText(), sel, 1); Collections.sort(journals); fireTableDataChanged(); } } else if (e.getSource() == remove) { int[] rows = userTable.getSelectedRows(); if (rows.length > 0) { for (int i = rows.length - 1; i >= 0; i--) { journals.remove(rows[i]); } fireTableDataChanged(); } } }
private void createNodesGroupedByDirectory( CheckedTreeNode root, final List<? extends DetectedFrameworkDescription> frameworks) { Map<VirtualFile, FrameworkDirectoryNode> nodes = new HashMap<>(); List<DetectedFrameworkNode> externalNodes = new ArrayList<>(); for (DetectedFrameworkDescription framework : frameworks) { VirtualFile parent = VfsUtil.getCommonAncestor(framework.getRelatedFiles()); if (parent != null && !parent.isDirectory()) { parent = parent.getParent(); } final DetectedFrameworkNode frameworkNode = new DetectedFrameworkNode(framework, myContext); if (parent != null) { createDirectoryNodes(parent, nodes).add(frameworkNode); } else { externalNodes.add(frameworkNode); } } List<FrameworkDirectoryNode> rootDirs = new ArrayList<>(); for (FrameworkDirectoryNode directoryNode : nodes.values()) { if (directoryNode.getParent() == null) { rootDirs.add(directoryNode); } } for (FrameworkDirectoryNode dir : rootDirs) { root.add(collapseDirectoryNode(dir)); } for (DetectedFrameworkNode node : externalNodes) { root.add(node); } }
public void moveUp(int index) { if (index > 0) { TileScript event = data.remove(index); data.add(index - 1, event); fireContentsChanged(this, index - 1, index); } }
public void moveDown(int index) { if (index < data.size() - 1) { TileScript event = data.remove(index); data.add(index + 1, event); fireContentsChanged(this, index, index + 1); } }
public List<VariableBean> getVariableBeans(NetcdfFile ds) { List<VariableBean> vlist = new ArrayList<VariableBean>(); for (Variable v : ds.getVariables()) { vlist.add(new VariableBean(v)); } return vlist; }
@Override public void compileAndRun( @NotNull final Runnable startRunnable, @NotNull final ExecutionEnvironment environment, @Nullable final RunProfileState state, @Nullable final Runnable onCancelRunnable) { long id = environment.getExecutionId(); if (id == 0) { id = environment.assignNewExecutionId(); } RunProfile profile = environment.getRunProfile(); if (!(profile instanceof RunConfiguration)) { startRunnable.run(); return; } final RunConfiguration runConfiguration = (RunConfiguration) profile; final List<BeforeRunTask> beforeRunTasks = RunManagerEx.getInstanceEx(myProject).getBeforeRunTasks(runConfiguration); if (beforeRunTasks.isEmpty()) { startRunnable.run(); } else { DataContext context = environment.getDataContext(); final DataContext projectContext = context != null ? context : SimpleDataContext.getProjectContext(myProject); final long finalId = id; final Long executionSessionId = new Long(id); ApplicationManager.getApplication() .executeOnPooledThread( () -> { for (BeforeRunTask task : beforeRunTasks) { if (myProject.isDisposed()) { return; } @SuppressWarnings("unchecked") BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myProject, task.getProviderId()); if (provider == null) { LOG.warn( "Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'"); continue; } ExecutionEnvironment taskEnvironment = new ExecutionEnvironmentBuilder(environment).contentToReuse(null).build(); taskEnvironment.setExecutionId(finalId); EXECUTION_SESSION_ID_KEY.set(taskEnvironment, executionSessionId); if (!provider.executeTask( projectContext, runConfiguration, taskEnvironment, task)) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable); } return; } } doRun(environment, startRunnable); }); } }
public List<VariableBean> getStructureVariables(Structure s) { List<VariableBean> vlist = new ArrayList<VariableBean>(); for (Variable v : s.getVariables()) { vlist.add(new VariableBean(v)); } return vlist; }
@Nullable public static TextRange findNext( @NotNull Editor editor, @NotNull String pattern, final int offset, boolean ignoreCase, final boolean forwards) { final List<TextRange> results = findAll(editor, pattern, 0, -1, shouldIgnoreCase(pattern, ignoreCase)); if (results.isEmpty()) { return null; } final int size = EditorHelper.getFileSize(editor); final TextRange max = Collections.max( results, new Comparator<TextRange>() { @Override public int compare(TextRange r1, TextRange r2) { final int d1 = distance(r1, offset, forwards, size); final int d2 = distance(r2, offset, forwards, size); if (d1 < 0 && d2 >= 0) { return Integer.MAX_VALUE; } return d2 - d1; } }); if (!Options.getInstance().isSet("wrapscan")) { final int start = max.getStartOffset(); if (forwards && start < offset || start >= offset) { return null; } } return max; }
protected List<String> getDeletionList(List<AppUpdate> updates) { List<String> fileNames = new ArrayList<String>(); for (AppUpdate list : updates) { fileNames.addAll(list.getDeletionNames()); } return fileNames; }
/*-------------------------------------------------------------------------*/ public FoeTypeSelection(int dirtyFlag) { this.dirtyFlag = dirtyFlag; List<String> foeTypesList = new ArrayList<String>(Database.getInstance().getFoeTypes().keySet()); Collections.sort(foeTypesList); int max = foeTypesList.size(); checkBoxes = new HashMap<String, JCheckBox>(); JPanel panel = new JPanel(new GridLayout(max / 2 + 2, 2, 3, 3)); selectAll = new JButton("Select All"); selectAll.addActionListener(this); selectNone = new JButton("Select None"); selectNone.addActionListener(this); panel.add(selectAll); panel.add(selectNone); for (String s : foeTypesList) { JCheckBox cb = new JCheckBox(s); checkBoxes.put(s, cb); cb.addActionListener(this); panel.add(cb); } JScrollPane scroller = new JScrollPane(panel); this.add(scroller); }
@Override protected void render(ColoredTreeCellRenderer renderer) { SimpleTextAttributes rootAttributes; SimpleTextAttributes branchAttributes; if (remoteName != null && commits.size() != 0 && remoteCommits != 0 || currentBranch == null) { rootAttributes = SimpleTextAttributes.ERROR_ATTRIBUTES.derive( SimpleTextAttributes.STYLE_BOLD, null, null, null); branchAttributes = SimpleTextAttributes.ERROR_ATTRIBUTES; } else if (remoteName == null || commits.size() == 0) { rootAttributes = SimpleTextAttributes.GRAYED_BOLD_ATTRIBUTES; branchAttributes = SimpleTextAttributes.GRAYED_ATTRIBUTES; } else { branchAttributes = SimpleTextAttributes.REGULAR_ATTRIBUTES; rootAttributes = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; } renderer.append(root.getPresentableUrl(), rootAttributes); if (currentBranch != null) { renderer.append(" [" + currentBranch, branchAttributes); if (remoteName != null) { renderer.append(" -> " + remoteName + "#" + remoteBranch, branchAttributes); } renderer.append("]", branchAttributes); } }
public void ConnectToSmartCard() { try { TerminalFactory factory = TerminalFactory.getDefault(); List<CardTerminal> terminals = factory.terminals().list(); System.out.println("Terminals: " + terminals); // get the first terminal // CardTerminals.State. CardTerminal terminal = terminals.get(0); if (terminal.isCardPresent()) { JOptionPane.showMessageDialog(null, "Card is Present"); this.terminal = terminal; } else { JOptionPane.showMessageDialog(null, "Card is absent.Connnect it in 5 secs\nWaiting..."); terminal.waitForCardPresent(5000); JOptionPane.showMessageDialog(null, "Time is Up!\nBye!!!"); return; } // establish a connection with the card Card card = terminal.connect("*"); this.card1 = card; } catch (CardException ce) { } }
private static String buildAllMethodNamesString( String allMethodNames, List<MethodEntry> parents) { StringBuffer allMN = new StringBuffer(120); allMN.append(allMethodNames); if (allMN.length() > 0) { allMN.append("."); } if (parents.size() > 1) { allMN.append("["); } { boolean first = true; for (MethodEntry entry : parents) { if (!first) { allMN.append(","); } first = false; allMN.append(((PsiMethod) entry.myEnd).getName()); } } if (parents.size() > 1) { allMN.append("]"); } return allMN.toString(); }
@Nullable private ProblemDescriptor[] checkMember( final PsiDocCommentOwner docCommentOwner, final InspectionManager manager, final boolean isOnTheFly) { final ArrayList<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>(); final PsiDocComment docComment = docCommentOwner.getDocComment(); if (docComment == null) return null; final Set<PsiJavaCodeReferenceElement> references = new HashSet<PsiJavaCodeReferenceElement>(); docComment.accept(getVisitor(references, docCommentOwner, problems, manager, isOnTheFly)); for (PsiJavaCodeReferenceElement reference : references) { final List<PsiClass> classesToImport = new ImportClassFix(reference).getClassesToImport(); final PsiElement referenceNameElement = reference.getReferenceNameElement(); problems.add( manager.createProblemDescriptor( referenceNameElement != null ? referenceNameElement : reference, cannotResolveSymbolMessage("<code>" + reference.getText() + "</code>"), !isOnTheFly || classesToImport.isEmpty() ? null : new AddImportFix(classesToImport), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, isOnTheFly)); } return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]); }
/** * Read stream into array of strings. * * @param inputStream The InputStream for the file. */ protected void openInputStream(InputStream inputStream) { String textLine; // Collect input lines in an array list. List<String> lines = ListFactory.createNewList(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new UnicodeReader(inputStream, textFileEncoding)); while ((textLine = bufferedReader.readLine()) != null) { lines.add(textLine); } textFileLoaded = true; } catch (IOException e) { } finally { try { if (bufferedReader != null) bufferedReader.close(); } catch (Exception e) { } } // Convert array list to array of strings. textFileLines = new String[lines.size()]; for (int i = 0; i < lines.size(); i++) { textFileLines[i] = lines.get(i); } }
@NotNull public static String buildStringToFindForIndicesFromRegExp( @NotNull String stringToFind, @NotNull Project project) { if (!Registry.is("idea.regexp.search.uses.indices")) return ""; final AccessToken accessToken = ReadAction.start(); try { final List<PsiElement> topLevelRegExpChars = getTopLevelRegExpChars("a", project); if (topLevelRegExpChars.size() != 1) return ""; // leave only top level regExpChars return StringUtil.join( getTopLevelRegExpChars(stringToFind, project), new Function<PsiElement, String>() { final Class regExpCharPsiClass = topLevelRegExpChars.get(0).getClass(); @Override public String fun(PsiElement element) { return regExpCharPsiClass.isInstance(element) ? element.getText() : " "; } }, ""); } finally { accessToken.finish(); } }
public String getAttributeValue(String _name, String namespace) { if (namespace == null) { return getAttributeValue(_name); } XmlTagImpl current = this; PsiElement parent = getParent(); while (current != null) { BidirectionalMap<String, String> map = current.initNamespaceMaps(parent); if (map != null) { List<String> keysByValue = map.getKeysByValue(namespace); if (keysByValue != null && !keysByValue.isEmpty()) { for (String prefix : keysByValue) { if (prefix != null && prefix.length() > 0) { final String value = getAttributeValue(prefix + ":" + _name); if (value != null) return value; } } } } current = parent instanceof XmlTag ? (XmlTagImpl) parent : null; parent = parent.getParent(); } if (namespace.length() == 0 || getNamespace().equals(namespace)) { return getAttributeValue(_name); } return null; }