@Override public void ignoreProblem(RefEntity refEntity, CommonProblemDescriptor problem, int idx) { if (refEntity == null) return; final Set<QuickFix> localQuickFixes = getQuickFixActions().get(refEntity); final QuickFix[] fixes = problem.getFixes(); if (isIgnoreProblem(fixes, localQuickFixes, idx)) { getProblemToElements().remove(problem); Map<RefEntity, CommonProblemDescriptor[]> problemElements = getProblemElements(); synchronized (lock) { CommonProblemDescriptor[] descriptors = problemElements.get(refEntity); if (descriptors != null) { ArrayList<CommonProblemDescriptor> newDescriptors = new ArrayList<CommonProblemDescriptor>(Arrays.asList(descriptors)); newDescriptors.remove(problem); getQuickFixActions().put(refEntity, null); if (!newDescriptors.isEmpty()) { problemElements.put( refEntity, newDescriptors.toArray(new CommonProblemDescriptor[newDescriptors.size()])); for (CommonProblemDescriptor descriptor : newDescriptors) { collectQuickFixes(descriptor.getFixes(), refEntity); } } else { ignoreProblemElement(refEntity); } } } } }
protected boolean processConcludeQuest(QuestClient.ConcludeMessage msg) { Long mobOid = msg.getMobOid(); if (!questOid.equals(msg.getQuestOid())) return true; if (Log.loggingDebug) log.debug("processConcludeQuest: player=" + getPlayerOid() + ", mob=" + mobOid); ArrayList<String> templateList = new ArrayList<String>(); for (CollectionGoalStatus goalStatus : goalsStatus) { for (int i = 0; i < goalStatus.getTargetCount(); i++) { templateList.add(goalStatus.getTemplateName()); } } boolean conclude = false; if (templateList.isEmpty()) { conclude = true; } else { List<Long> removeResult = InventoryClient.removeItems(getPlayerOid(), templateList); if (removeResult != null) { conclude = true; for (Long itemOid : removeResult) { ObjectManagerClient.deleteObject(itemOid); } } } if (conclude) { setConcluded(true); deactivate(); updateQuestLog(); sendStateStatusChange(); } return true; }
protected List<MappingWithDirection> findApplicable(MappingKey key) { ArrayList<MappingWithDirection> result = new ArrayList<MappingWithDirection>(); for (ParsedMapping pm : mappings) { if ((pm.mappingCase == null && key.mappingCase == null) ^ (pm.mappingCase != null && pm.mappingCase.equals(key.mappingCase))) { if (pm.sideA.isAssignableFrom(key.source) && pm.sideB.isAssignableFrom(key.target)) result.add(new MappingWithDirection(pm, true)); else if (pm.sideB.isAssignableFrom(key.source) && pm.sideA.isAssignableFrom(key.target)) result.add(new MappingWithDirection(pm, false)); } } if (!result.isEmpty()) { Collections.sort(result, new MappingComparator(key.target)); } else if (automappingEnabled) { logger.info( "Could not find applicable mappings between {} and {}. A mapping will be created using automapping facility", key.source.getName(), key.target.getName()); ParsedMapping pm = new Mapping(key.source, key.target, this).automap().parse(); logger.debug("Automatically created {}", pm); mappings.add(pm); result.add(new MappingWithDirection(pm, true)); } else logger.warn( "Could not find applicable mappings between {} and {}!", key.source.getName(), key.target.getName()); return result; }
public void draw(node leaf, Graphics2D g, int px, int py) { int lvl = leaf.getLevel(); double l = lvl; counts[lvl]++; double xfraq = counts[lvl] / (spacing[lvl] + 1); double yfraq = l / depth; int x = new Double(1600 * xfraq).intValue(); int y = new Double(1200 * yfraq).intValue() + 10; if (leaf.getAttr() != null) { g.drawString(leaf.getAttr(), x - 20, y); } if (leaf.getCrit() != null) { g.drawString(leaf.getCrit(), x - 20, y + 10); } if (leaf.getResult() != null) { g.drawString(leaf.getResult(), x - 20, y + 10); } g.drawLine(x, y, px, py); // g.fillRect(x,y,20,20); ArrayList children = leaf.getChildren(); while (!children.isEmpty()) { draw((node) children.remove(0), g, x, y); } }
/** * Return certificates for signed bundle, otherwise null. * * @return An array of certificates or null. */ public ArrayList getCertificateChains(boolean onlyTrusted) { if (checkCerts) { Certificate[] c = archive.getCertificates(); checkCerts = false; if (c != null) { ArrayList failed = new ArrayList(); untrustedCerts = Util.getCertificateChains(c, failed); if (!failed.isEmpty()) { // NYI, log Bundle archive has invalid certificates untrustedCerts = null; } } } ArrayList res = trustedCerts; if (!onlyTrusted && untrustedCerts != null) { if (res == null) { res = untrustedCerts; } else { res = new ArrayList(trustedCerts.size() + untrustedCerts.size()); res.addAll(trustedCerts); res.addAll(untrustedCerts); } } return res; }
/** * formatCardType. * * @param card a {@link forge.Card} object. * @return a {@link java.lang.String} object. */ public static String formatCardType(Card card) { ArrayList<String> list = card.getType(); StringBuilder sb = new StringBuilder(); ArrayList<String> superTypes = new ArrayList<String>(); ArrayList<String> cardTypes = new ArrayList<String>(); ArrayList<String> subTypes = new ArrayList<String>(); for (String t : list) { if (CardUtil.isASuperType(t)) superTypes.add(t); if (CardUtil.isACardType(t)) cardTypes.add(t); if (CardUtil.isASubType(t)) subTypes.add(t); } for (String type : superTypes) { sb.append(type).append(" "); } for (String type : cardTypes) { sb.append(type).append(" "); } if (!subTypes.isEmpty()) sb.append("- "); for (String type : subTypes) { sb.append(type).append(" "); } return sb.toString(); }
public static void golf(String file_name) { Random rand = new Random(); ArrayList<Person> players = new ArrayList(); try { Scanner in = new Scanner(new FileReader(file_name)); while (in.hasNextLine()) { String name = in.nextLine(); Person person = new Person(name); players.add(person); } } catch (Exception e) { System.out.println("Could not find file"); } while (!players.isEmpty()) { int first, second; do { first = rand.nextInt(players.size()); second = rand.nextInt(players.size()); } while (first == second); System.out.println("Team:"); System.out.println(players.get(first).name); System.out.println(players.get(second).name); System.out.print("\n"); players.remove(second); if (second < first) { players.remove(first - 1); } else { players.remove(first); } } }
public static Hashtable find_combos(Hashtable table, ArrayList<User> users, int r_value) { ArrayList<Integer> combinations = new ArrayList<Integer>(); ArrayList<List<Integer>> combvalues = new ArrayList<List<Integer>>(); // System.out.println("current hash "+table); Iterator iter = table.keySet().iterator(); while (iter.hasNext()) { ArrayList<Integer> hashvalue = (ArrayList<Integer>) iter.next(); // System.out.println(hashvalue+"::value with support "+table.get(hashvalue)); if ((Integer) table.get(hashvalue) >= MINSUP) { combinations.add((Integer) table.get(hashvalue)); combvalues.add(hashvalue); } } // System.out.println("combinations that survive: "+combvalues); ArrayList<Integer> unique_combo_values = new ArrayList<Integer>(); for (int i = 0; i < combvalues.size(); i++) { for (int k = 0; k < combvalues.get(i).size(); k++) { if (!unique_combo_values.contains(combvalues.get(i).get(k))) { unique_combo_values.add(combvalues.get(i).get(k)); } } } ArrayList<List<Integer>> new_combos = new ArrayList<List<Integer>>(); new_combos = (ArrayList<List<Integer>>) combinations(unique_combo_values, r_value); // System.out.println("generated new combinations: "+new_combos); Hashtable t = new Hashtable(); for (int j = 0; j < new_combos.size(); j++) { for (int i = 1; i <= num_users; i++) { if (users.get(i).hasSameNumbers((new_combos.get(j)))) { if (t.containsKey(new_combos.get(j))) { int count = (Integer) t.get(new_combos.get(j)); count++; t.put(new_combos.get(j), count); // System.out.println("added one to "+new_combos.get(j)); } else { t.put(new_combos.get(j), 1); // System.out.println("set to 1"+new_combos.get(j)); } } } } // System.out.println("before weeding "+t); Iterator final_iter = t.keySet().iterator(); while (final_iter.hasNext()) { ArrayList<Integer> next = (ArrayList<Integer>) final_iter.next(); // System.out.println("current support of "+ next+ " is "+t.get(next)); // System.out.println(MINSUP); if ((Integer) t.get(next) < MINSUP || next.isEmpty()) { // System.out.println("hi"); final_iter.remove(); } } return t; }
/** Mark certificate chain as trusted. */ public void trustCertificateChain(List trustedChain) { if (trustedCerts == null) { trustedCerts = new ArrayList(untrustedCerts.size()); } trustedCerts.add(trustedChain); untrustedCerts.remove(trustedChain); if (untrustedCerts.isEmpty()) { untrustedCerts = null; } }
/** * Gets the list of the vnmrj users(operators) for the current unix user logged in * * @return the list of vnmrj users */ protected Object[] getOperators() { String strUser = System.getProperty("user.name"); User user = LoginService.getDefault().getUser(strUser); ArrayList<String> aListOperators = user.getOperators(); if (aListOperators == null || aListOperators.isEmpty()) aListOperators = new ArrayList<String>(); Collections.sort(aListOperators); if (aListOperators.contains(strUser)) aListOperators.remove(strUser); aListOperators.add(0, strUser); return (aListOperators.toArray()); }
public void createRanks(){ for (int i = 0 ; i < popFromGA.size() ; i++){ //for (int i = 0 ; i < 5 ; i++){ if ((((NSGAII.Solutions.QRTPSolution.OneSolution)popFromGA.get(i)).getNp()) == 0){ ((NSGAII.Solutions.QRTPSolution.OneSolution)popFromGA.get(i)).setRank(0); F.add((NSGAII.Solutions.QRTPSolution.OneSolution)popFromGA.get(i)); } } // System.out.println("After checking np=0"); Fronts.add(F); int rankValue = 1; while(F.isEmpty() == false){ ArrayList Q = new ArrayList(); for (int i = 0; i < F.size() ; i++){ //From the F set (front 1) get all the solutions in Sp that a solution in front 1 dominates ArrayList temp = ((NSGAII.Solutions.QRTPSolution.OneSolution) F.get(i)).getSp(); for (int j = 0; j < temp.size() ; j++){ //makes the value np of all the solutions in Sp of a solution in front 1 equals np-1 // System.out.println("This solution had np"+((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)).getNp()); ((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)).setNpMinus(((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)).getNp()-1); //if any of this solutions np becomes 0 then this solution added in front 2 // System.out.println("This solution has np"+((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)).getNp()); if (((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)).getNp() == 0){ //System.out.println("Gets in"); ((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)).setRank(rankValue); Q.add((NSGAII.Solutions.QRTPSolution.OneSolution) temp.get(j)); } } } rankValue++; F = Q; Fronts.add(F); } }
/** * Returns the clipboard text. * * @return text */ private static String clip() { // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); final Transferable tr = clip.getContents(null); if (tr != null) { final ArrayList<Object> contents = BaseXLayout.contents(tr); if (!contents.isEmpty()) return contents.get(0).toString(); } else { Util.debug("Clipboard has no contents."); } return null; }
public void trav(ArrayList nodes, node cur) { node temp; while (!nodes.isEmpty()) { temp = (node) nodes.get(0); if (temp.getLevel() - 1 == cur.getLevel()) { nodes.remove(0); cur.addChild(temp); trav(nodes, temp); } else { return; } } }
/** {@inheritDoc} */ public void removeHostListener(HostListener listener) { /* * XXX: if a disconnect method is added, make sure it calls * this method to unregister this object from the watcher. otherwise, * an unused MonitoredHostProvider instance may go uncollected. */ synchronized (listeners) { listeners.remove(listener); if (listeners.isEmpty() && (task != null)) { task.cancel(); task = null; } } }
private static void parseArguments(String arguments[]) { /* * format: * -e <exonFileName> * -ex <expressions file> * -sam <mapped reads, sam file> * -ref <reference directory> * -c <chromosomes (start-end)> * -t (prints timing metrics) * -o <output file name> */ try { for (int index = 0; index < arguments.length; index++) { String arg = arguments[index]; if (arg.equals("-e")) exonFileName = arguments[index + 1]; else if (arg.equals("-ex")) expressionFileName = arguments[index + 1]; else if (arg.equals("-sam")) mappedReadsFileName = arguments[index + 1]; else if (arg.equals("-ref")) referenceDirectory = arguments[index + 1]; else if (arg.equals("-t")) printTimingMetrics = true; else if (arg.equals("-o")) outputFileName = arguments[index + 1]; else if (arg.equals("-c")) { String[] fields = arguments[index + 1].split("-"); for (int c = Integer.parseInt(fields[0]); c <= Integer.parseInt(fields[1]); c++) { chromosomes.add(c); } } } if (exonFileName.equals("") || expressionFileName.equals("") || mappedReadsFileName.equals("") || referenceDirectory.equals("") || chromosomes.isEmpty()) { System.err.println("Improper Usage:"); System.err.println( "java exonSeg -e <exonFileName> " + "-ex <expressions file> " + "-sam <mapped reads, sam file> " + "-ref <reference directory> " + "-c <chromosomes (start-end)> " + "[-t] " + "[-o <output file name>]"); throw (new Exception("Improper Usage")); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); e.printStackTrace(); } }
public void recreateTree() { System.out.println("Recreating tree"); ArrayList nodes = new ArrayList(); String attr, crit, result; int level; node leaf; while (!list.isEmpty()) { if (((String) list.remove(0)).compareTo("Node") == 0) { leaf = new node(); attr = (String) list.remove(0); // System.out.println("ATTR:"+attr); crit = (String) list.remove(0); try { level = (new Double(crit)).intValue(); crit = null; } catch (Exception e) { // System.out.println("crit:"+crit); level = (new Double((String) list.remove(0))).intValue(); } // System.out.println("lvl:"+level); if (level > depth) { depth = level; } if (((String) list.get(0)).compareTo("Node") != 0) { result = (String) list.remove(0); leaf.setResult(result); } leaf.setSplitCriteria(crit, 0); leaf.setLevel(level); leaf.setAttr(attr); if (attr.compareTo("_root") == 0) { root = leaf; } else { nodes.add(leaf); } } } depth++; levelCount(nodes); System.out.println("Linking " + nodes.size() + " tree nodes"); trav(nodes, root); }
public void run() { System.out.println("ReminderServiceOld: Starting at " + new Date()); while (!l.isEmpty()) { Date d = new Date(); Item i = (Item) l.get(0); long interval = i.due.getTime() - d.getTime(); if (interval > 0) { System.out.println("Sleeping until " + i.due); try { Thread.sleep(interval); } catch (InterruptedException e) { System.exit(1); // unexpected intr } message(i.due + ": " + i.message); } else message("MISSED " + i.message + " at " + i.due); l.remove(0); } System.exit(0); }
public void setSelectedObjectsFromDB() { this.selectingObject = true; this.list.clearSelection(); int offsetIdx = 0; ArrayList<Integer> selectedIndices = new ArrayList<Integer>(); for (ObjectStructure s : this.currentChannels) { BasicDBList selectedObjects = Core.mongoConnector.getSelectedObjects(currentNucId, s.getIdx()); if (selectedObjects != null && !selectedObjects.isEmpty()) { for (Object o : selectedObjects) selectedIndices.add((Integer) o + offsetIdx); } offsetIdx += s.getObjects().length; } if (!selectedIndices.isEmpty()) { int[] selectedIdx = new int[selectedIndices.size()]; for (int i = 0; i < selectedIdx.length; i++) selectedIdx[i] = selectedIndices.get(i); this.list.setSelectedIndices(selectedIdx); } this.selectingObject = false; }
/** * Creates new JShell instance and runs the Shell. * * @param args not used. */ public static void main(String[] args) { String filename = "JShell.ser"; JShell newShell = loadJShell(filename); if (newShell == null) { newShell = new JShell(); } newShell.printPrompt(); ArrayList<String> input = newShell.readInput(); while (input.isEmpty() || !"exit".equals(input.get(0))) { if (!input.isEmpty()) { List<String> params = newShell.handleRedirection(input.subList(1, input.size())); newShell.executeCommand(input.get(0).toString(), params); } newShell.printPrompt(); input = newShell.readInput(); } filename = "JShell.ser"; newShell.saveJShell(filename); }
public void populateObjects() { try { this.listModel.removeAllElements(); if (currentChannels == null) { return; } this.populatingObjects = true; ArrayList<Integer> selection = null; if (showSelection != null && showSelection.isSelected()) selection = new ArrayList<Integer>(); int currentIdx = 0; for (ObjectStructure ass : currentChannels) { Object3D[] os = ass.getObjects(); if (os != null) { Object3DGui[] osg = new Object3DGui[os.length]; for (int i = 0; i < os.length; i++) osg[i] = new Object3DGui(os[i], ass); if (layout instanceof ObjectManagerLayout && currentChannels.length == 1 && !((ObjectManagerLayout) layout).getSortKey().equals("idx")) this.sort(((ObjectManagerLayout) layout).getSortKey(), osg, ass.getIdx()); // System.out.println("populating objects.. nb objects:"+os.length); for (Object3DGui o3D : osg) { this.listModel.addElement(o3D); if (selection != null && o3D.isInSelection()) selection.add(currentIdx); currentIdx++; } // if (selection!=null) System.out.println("populating objects.. selection // size:"+selection.size()); } // else System.out.println("no objects int channel:"+ass.getChannelName()); } if (selection != null && !selection.isEmpty()) { int[] sel = new int[selection.size()]; int i = 0; for (int idx : selection) sel[i++] = idx; list.setSelectedIndices(sel); } } catch (Exception e) { exceptionPrinter.print(e, "", Core.GUIMode); } this.populatingObjects = false; }
/** * Writes the specified portion of the final content of this output document to the specified * <code>Writer</code>. * * <p>Any zero-length output segments located at <code>begin</code> or <code>end</code> are * included in the output. * * @param writer the destination <code>java.io.Writer</code> for the output. * @param begin the character position at which to start the output, inclusive. * @param end the character position at which to end the output, exclusive. * @throws IOException if an I/O exception occurs. * @see #writeTo(Writer) */ public void writeTo(final Writer writer, final int begin, final int end) throws IOException { try { if (outputSegments.isEmpty()) { Util.appendTo(writer, sourceText, begin, end); return; } int pos = begin; Collections.sort(outputSegments, OutputSegment.COMPARATOR); for (final Iterator i = outputSegments.iterator(); i.hasNext(); ) { final OutputSegment outputSegment = (OutputSegment) i.next(); if (outputSegment.getEnd() < pos) continue; // skip output segments before begin, and any that are enclosed by other output // segments if (outputSegment.getEnd() == pos && outputSegment.getBegin() < pos) continue; // skip output segments that end at pos unless they are zero length if (outputSegment.getBegin() > end) break; // stop processing output segments if they are not longer in the desired output // range if (outputSegment.getBegin() == end && outputSegment.getEnd() > end) break; // stop processing output segments if they start at end unless they are zero length if (outputSegment.getBegin() > pos) { Util.appendTo(writer, sourceText, pos, outputSegment.getBegin()); } if (outputSegment.getBegin() < pos && outputSegment instanceof BlankOutputSegment) { // Overlapping BlankOutputSegments requires special handling to ensure the correct number // of blanks are inserted. for (final int outputSegmentEnd = outputSegment.getEnd(); pos < outputSegmentEnd; pos++) writer.write(' '); } else { outputSegment.writeTo(writer); pos = outputSegment.getEnd(); } } if (pos < end) Util.appendTo(writer, sourceText, pos, end); } finally { writer.flush(); } }
/** * @param addClearListItem - used for detecting whether the "Clear List" action should be added to * the end of the returned list of actions * @return */ public AnAction[] getRecentProjectsActions(boolean addClearListItem) { validateRecentProjects(); final Set<String> openedPaths = ContainerUtil.newHashSet(); for (Project openProject : ProjectManager.getInstance().getOpenProjects()) { ContainerUtil.addIfNotNull(openedPaths, getProjectPath(openProject)); } final LinkedHashSet<String> paths; synchronized (myStateLock) { paths = ContainerUtil.newLinkedHashSet(myState.recentPaths); } paths.remove(null); paths.removeAll(openedPaths); ArrayList<AnAction> actions = new ArrayList<AnAction>(); Set<String> duplicates = getDuplicateProjectNames(openedPaths, paths); for (final String path : paths) { final String projectName = getProjectName(path); String displayName; synchronized (myStateLock) { displayName = myState.names.get(path); } if (StringUtil.isEmptyOrSpaces(displayName)) { displayName = duplicates.contains(path) ? path : projectName; } // It's better don't to remove non-existent projects. Sometimes projects stored // on USB-sticks or flash-cards, and it will be nice to have them in the list // when USB device or SD-card is mounted if (new File(path).exists()) { actions.add(new ReopenProjectAction(path, projectName, displayName)); } } if (actions.isEmpty()) { return AnAction.EMPTY_ARRAY; } ArrayList<AnAction> list = new ArrayList<AnAction>(); for (AnAction action : actions) { list.add(action); } if (addClearListItem) { AnAction clearListAction = new AnAction(IdeBundle.message("action.clear.list")) { public void actionPerformed(AnActionEvent e) { final int rc = Messages.showOkCancelDialog( e.getData(PlatformDataKeys.PROJECT), "Would you like to clear the list of recent projects?", "Clear Recent Projects List", Messages.getQuestionIcon()); if (rc == 0) { synchronized (myStateLock) { myState.recentPaths.clear(); } WelcomeFrame.clearRecents(); } } }; list.add(Separator.getInstance()); list.add(clearListAction); } return list.toArray(new AnAction[list.size()]); }
public void build_bricks() { ImagePlus imp; ImagePlus orgimp; ImageStack stack; FileInfo finfo; if (lvImgTitle.isEmpty()) return; orgimp = WindowManager.getImage(lvImgTitle.get(0)); imp = orgimp; finfo = imp.getFileInfo(); if (finfo == null) return; int[] dims = imp.getDimensions(); int imageW = dims[0]; int imageH = dims[1]; int nCh = dims[2]; int imageD = dims[3]; int nFrame = dims[4]; int bdepth = imp.getBitDepth(); double xspc = finfo.pixelWidth; double yspc = finfo.pixelHeight; double zspc = finfo.pixelDepth; double z_aspect = Math.max(xspc, yspc) / zspc; int orgW = imageW; int orgH = imageH; int orgD = imageD; double orgxspc = xspc; double orgyspc = yspc; double orgzspc = zspc; lv = lvImgTitle.size(); if (filetype == "JPEG") { for (int l = 0; l < lv; l++) { if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) { IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE"); return; } } } // calculate levels /* int baseXY = 256; int baseZ = 256; if (z_aspect < 0.5) baseZ = 128; if (z_aspect > 2.0) baseXY = 128; if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect); if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect); IJ.log("Z_aspect: " + z_aspect); IJ.log("BaseXY: " + baseXY); IJ.log("BaseZ: " + baseZ); */ int baseXY = 256; int baseZ = 128; int dbXY = Math.max(orgW, orgH) / baseXY; if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2; int dbZ = orgD / baseZ; if (orgD % baseZ > 0) dbZ *= 2; lv = Math.max(log2(dbXY), log2(dbZ)) + 1; int ww = orgW; int hh = orgH; int dd = orgD; for (int l = 0; l < lv; l++) { int bwnum = ww / baseXY; if (ww % baseXY > 0) bwnum++; int bhnum = hh / baseXY; if (hh % baseXY > 0) bhnum++; int bdnum = dd / baseZ; if (dd % baseZ > 0) bdnum++; if (bwnum % 2 == 0) bwnum++; if (bhnum % 2 == 0) bhnum++; if (bdnum % 2 == 0) bdnum++; int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0); int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0); int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0); bwlist.add(bw); bhlist.add(bh); bdlist.add(bd); IJ.log("LEVEL: " + l); IJ.log(" width: " + ww); IJ.log(" hight: " + hh); IJ.log(" depth: " + dd); IJ.log(" bw: " + bw); IJ.log(" bh: " + bh); IJ.log(" bd: " + bd); int xyl2 = Math.max(ww, hh) / baseXY; if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2; if (lv - 1 - log2(xyl2) <= l) { ww /= 2; hh /= 2; } IJ.log(" xyl2: " + (lv - 1 - log2(xyl2))); int zl2 = dd / baseZ; if (dd % baseZ > 0) zl2 *= 2; if (lv - 1 - log2(zl2) <= l) dd /= 2; IJ.log(" zl2: " + (lv - 1 - log2(zl2))); if (l < lv - 1) { lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1)); IJ.selectWindow(lvImgTitle.get(0)); IJ.run( "Scale...", "x=- y=- z=- width=" + ww + " height=" + hh + " depth=" + dd + " interpolation=Bicubic average process create title=" + lvImgTitle.get(l + 1)); } } for (int l = 0; l < lv; l++) { IJ.log(lvImgTitle.get(l)); } Document doc = newXMLDocument(); Element root = doc.createElement("BRK"); root.setAttribute("version", "1.0"); root.setAttribute("nLevel", String.valueOf(lv)); root.setAttribute("nChannel", String.valueOf(nCh)); root.setAttribute("nFrame", String.valueOf(nFrame)); doc.appendChild(root); for (int l = 0; l < lv; l++) { IJ.showProgress(0.0); int[] dims2 = imp.getDimensions(); IJ.log( "W: " + String.valueOf(dims2[0]) + " H: " + String.valueOf(dims2[1]) + " C: " + String.valueOf(dims2[2]) + " D: " + String.valueOf(dims2[3]) + " T: " + String.valueOf(dims2[4]) + " b: " + String.valueOf(bdepth)); bw = bwlist.get(l).intValue(); bh = bhlist.get(l).intValue(); bd = bdlist.get(l).intValue(); boolean force_pow2 = false; /* if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true; if(force_pow2){ //force pow2 if(Pow2(bw) > bw) bw = Pow2(bw)/2; if(Pow2(bh) > bh) bh = Pow2(bh)/2; if(Pow2(bd) > bd) bd = Pow2(bd)/2; } if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2; if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2; if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2; */ if (bw > imageW) bw = imageW; if (bh > imageH) bh = imageH; if (bd > imageD) bd = imageD; if (bw <= 1 || bh <= 1 || bd <= 1) break; if (filetype == "JPEG" && (bw < 8 || bh < 8)) break; Element lvnode = doc.createElement("Level"); lvnode.setAttribute("lv", String.valueOf(l)); lvnode.setAttribute("imageW", String.valueOf(imageW)); lvnode.setAttribute("imageH", String.valueOf(imageH)); lvnode.setAttribute("imageD", String.valueOf(imageD)); lvnode.setAttribute("xspc", String.valueOf(xspc)); lvnode.setAttribute("yspc", String.valueOf(yspc)); lvnode.setAttribute("zspc", String.valueOf(zspc)); lvnode.setAttribute("bitDepth", String.valueOf(bdepth)); root.appendChild(lvnode); Element brksnode = doc.createElement("Bricks"); brksnode.setAttribute("brick_baseW", String.valueOf(bw)); brksnode.setAttribute("brick_baseH", String.valueOf(bh)); brksnode.setAttribute("brick_baseD", String.valueOf(bd)); lvnode.appendChild(brksnode); ArrayList<Brick> bricks = new ArrayList<Brick>(); int mw, mh, md, mw2, mh2, md2; double tx0, ty0, tz0, tx1, ty1, tz1; double bx0, by0, bz0, bx1, by1, bz1; for (int k = 0; k < imageD; k += bd) { if (k > 0) k--; for (int j = 0; j < imageH; j += bh) { if (j > 0) j--; for (int i = 0; i < imageW; i += bw) { if (i > 0) i--; mw = Math.min(bw, imageW - i); mh = Math.min(bh, imageH - j); md = Math.min(bd, imageD - k); if (force_pow2) { mw2 = Pow2(mw); mh2 = Pow2(mh); md2 = Pow2(md); } else { mw2 = mw; mh2 = mh; md2 = md; } if (filetype == "JPEG") { if (mw2 < 8) mw2 = 8; if (mh2 < 8) mh2 = 8; } tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2); ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2); tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2); tx1 = 1.0d - 0.5d / mw2; if (mw < bw) tx1 = 1.0d; if (imageW - i == bw) tx1 = 1.0d; ty1 = 1.0d - 0.5d / mh2; if (mh < bh) ty1 = 1.0d; if (imageH - j == bh) ty1 = 1.0d; tz1 = 1.0d - 0.5d / md2; if (md < bd) tz1 = 1.0d; if (imageD - k == bd) tz1 = 1.0d; bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW; by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH; bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD; bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d); if (imageW - i == bw) bx1 = 1.0d; by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d); if (imageH - j == bh) by1 = 1.0d; bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d); if (imageD - k == bd) bz1 = 1.0d; int x, y, z; x = i - (mw2 - mw); y = j - (mh2 - mh); z = k - (md2 - md); bricks.add( new Brick( x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1, by1, bz1)); } } } Element fsnode = doc.createElement("Files"); lvnode.appendChild(fsnode); stack = imp.getStack(); int totalbricknum = nFrame * nCh * bricks.size(); int curbricknum = 0; for (int f = 0; f < nFrame; f++) { for (int ch = 0; ch < nCh; ch++) { int sizelimit = bdsizelimit * 1024 * 1024; int bytecount = 0; int filecount = 0; int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8); byte[] packed_data = new byte[pd_bufsize]; String base_dataname = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f); String current_dataname = base_dataname + "_data" + filecount; Brick b_first = bricks.get(0); if (b_first.z_ != 0) IJ.log("warning"); int st_z = b_first.z_; int ed_z = b_first.z_ + b_first.d_; LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>(); for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); // ImagePlus test; // ImageStack tsst; // test = NewImage.createByteImage("test", imageW, imageH, imageD, // NewImage.FILL_BLACK); // tsst = test.getStack(); for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); if (ed_z > b.z_ || st_z < b.z_ + b.d_) { if (b.z_ > st_z) { for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst(); st_z = b.z_; } else if (b.z_ < st_z) { IJ.log("warning"); for (int s = st_z - 1; s > b.z_; s--) iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); st_z = b.z_; } if (b.z_ + b.d_ > ed_z) { for (int s = ed_z; s < b.z_ + b.d_; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); ed_z = b.z_ + b.d_; } else if (b.z_ + b.d_ < ed_z) { IJ.log("warning"); for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast(); ed_z = b.z_ + b.d_; } } else { IJ.log("warning"); iplist.clear(); st_z = b.z_; ed_z = b.z_ + b.d_; for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); } if (iplist.size() != b.d_) { IJ.log("Stack Error"); return; } // int zz = st_z; int bsize = 0; byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Iterator<ImageProcessor> ipite = iplist.iterator(); while (ipite.hasNext()) { // ImageProcessor tsip = tsst.getProcessor(zz+1); ImageProcessor ip = ipite.next(); ip.setRoi(b.x_, b.y_, b.w_, b.h_); if (bdepth == 8) { byte[] data = (byte[]) ip.crop().getPixels(); System.arraycopy(data, 0, bdata, bsize, data.length); bsize += data.length; } else if (bdepth == 16) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); short[] data = (short[]) ip.crop().getPixels(); for (short e : data) buffer.putShort(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } else if (bdepth == 32) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); float[] data = (float[]) ip.crop().getPixels(); for (float e : data) buffer.putFloat(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } } String filename = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f) + "_ID" + String.valueOf(i); int offset = bytecount; int datasize = bdata.length; if (filetype == "RAW") { int dummy = -1; // do nothing } if (filetype == "JPEG" && bdepth == 8) { try { DataBufferByte db = new DataBufferByte(bdata, datasize); Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null); BufferedImage img = new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY); img.setData(raster); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); String format = "jpg"; Iterator<javax.imageio.ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); javax.imageio.ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality((float) jpeg_quality * 0.01f); writer.setOutput(ios); writer.write(null, new IIOImage(img, null, null), iwp); // ImageIO.write(img, format, baos); bdata = baos.toByteArray(); datasize = bdata.length; } catch (IOException e) { e.printStackTrace(); return; } } if (filetype == "ZLIB") { byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Deflater compresser = new Deflater(); compresser.setInput(bdata); compresser.setLevel(Deflater.DEFAULT_COMPRESSION); compresser.setStrategy(Deflater.DEFAULT_STRATEGY); compresser.finish(); datasize = compresser.deflate(tmpdata); bdata = tmpdata; compresser.end(); } if (bytecount + datasize > sizelimit && bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } filecount++; current_dataname = base_dataname + "_data" + filecount; bytecount = 0; offset = 0; System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } else { System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } Element filenode = doc.createElement("File"); filenode.setAttribute("filename", current_dataname); filenode.setAttribute("channel", String.valueOf(ch)); filenode.setAttribute("frame", String.valueOf(f)); filenode.setAttribute("brickID", String.valueOf(i)); filenode.setAttribute("offset", String.valueOf(offset)); filenode.setAttribute("datasize", String.valueOf(datasize)); filenode.setAttribute("filetype", String.valueOf(filetype)); fsnode.appendChild(filenode); curbricknum++; IJ.showProgress((double) (curbricknum) / (double) (totalbricknum)); } if (bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } } } } for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); Element bricknode = doc.createElement("Brick"); bricknode.setAttribute("id", String.valueOf(i)); bricknode.setAttribute("st_x", String.valueOf(b.x_)); bricknode.setAttribute("st_y", String.valueOf(b.y_)); bricknode.setAttribute("st_z", String.valueOf(b.z_)); bricknode.setAttribute("width", String.valueOf(b.w_)); bricknode.setAttribute("height", String.valueOf(b.h_)); bricknode.setAttribute("depth", String.valueOf(b.d_)); brksnode.appendChild(bricknode); Element tboxnode = doc.createElement("tbox"); tboxnode.setAttribute("x0", String.valueOf(b.tx0_)); tboxnode.setAttribute("y0", String.valueOf(b.ty0_)); tboxnode.setAttribute("z0", String.valueOf(b.tz0_)); tboxnode.setAttribute("x1", String.valueOf(b.tx1_)); tboxnode.setAttribute("y1", String.valueOf(b.ty1_)); tboxnode.setAttribute("z1", String.valueOf(b.tz1_)); bricknode.appendChild(tboxnode); Element bboxnode = doc.createElement("bbox"); bboxnode.setAttribute("x0", String.valueOf(b.bx0_)); bboxnode.setAttribute("y0", String.valueOf(b.by0_)); bboxnode.setAttribute("z0", String.valueOf(b.bz0_)); bboxnode.setAttribute("x1", String.valueOf(b.bx1_)); bboxnode.setAttribute("y1", String.valueOf(b.by1_)); bboxnode.setAttribute("z1", String.valueOf(b.bz1_)); bricknode.appendChild(bboxnode); } if (l < lv - 1) { imp = WindowManager.getImage(lvImgTitle.get(l + 1)); int[] newdims = imp.getDimensions(); imageW = newdims[0]; imageH = newdims[1]; imageD = newdims[3]; xspc = orgxspc * ((double) orgW / (double) imageW); yspc = orgyspc * ((double) orgH / (double) imageH); zspc = orgzspc * ((double) orgD / (double) imageD); bdepth = imp.getBitDepth(); } } File newXMLfile = new File(directory + basename + ".vvd"); writeXML(newXMLfile, doc); for (int l = 1; l < lv; l++) { imp = WindowManager.getImage(lvImgTitle.get(l)); imp.changes = false; imp.close(); } }
private void list() throws IOException { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("type", "album")); formparams.add(new BasicNameValuePair("scope", "all")); BufferedReader entityReader = sendRequest(g.getUrlString() + api + "item/1", "get", formparams); JSONParser parser = new JSONParser(); ListContentHandler lch = new ListContentHandler(); HashMap<String,String> url2parentUrl = new HashMap<String,String>(); HashMap<String,Album> url2album = new HashMap<String,Album>(); ArrayList<Album> albums = new ArrayList<Album>(); try { Album rootAlbum = g.createRootAlbum(); rootAlbum.setUrl(g.getUrlString() + api + "item/1"); rootAlbum.setSuppressEvents(true); lch.setAlbum(rootAlbum); parser.parse(entityReader, lch, true); rootAlbum.setSuppressEvents(false); // map album names to albums url2album.put(rootAlbum.getUrl(), rootAlbum); url2parentUrl.put(rootAlbum.getUrl(), lch.getParentUrl()); while (!lch.isEnd()) { Album a = g.newAlbum(); a.setSuppressEvents(true); lch.setAlbum(a); parser.parse(entityReader, lch, true); a.setSuppressEvents(false); albums.add(a); // map album names to albums url2album.put(a.getUrl(), a); url2parentUrl.put(a.getUrl(), lch.getParentUrl()); } } catch (ParseException e) { Log.logException(Log.LEVEL_CRITICAL, MODULE, e); } Log.log(Log.LEVEL_TRACE, MODULE, "Created " + albums.size() + " albums"); // link albums to parents for (Object o : url2parentUrl.keySet()) { String name = (String) o; String parentName = url2parentUrl.get(name); Album child = url2album.get(name); Album parent = url2album.get(parentName); if (child != null && parent != null) { parent.add(child); } } Log.log(Log.LEVEL_TRACE, MODULE, "Linked " + url2parentUrl.size() + " albums to their parents"); // reorder Collections.sort(albums, new NaturalOrderComparator<Album>()); Collections.reverse(albums); ArrayList<Album> orderedAlbums = new ArrayList<Album>(); int depth = 0; while (!albums.isEmpty()) { Iterator<Album> it = albums.iterator(); while (it.hasNext()) { Album a = it.next(); try { if (a.getAlbumDepth() == depth) { it.remove(); a.sortSubAlbums(); Album parentAlbum = a.getParentAlbum(); if (parentAlbum == null) { orderedAlbums.add(0, a); } else { int i = orderedAlbums.indexOf(parentAlbum); orderedAlbums.add(i + 1, a); } } } catch (IllegalArgumentException e) { it.remove(); Log.log(Log.LEVEL_TRACE, MODULE, "Gallery server album list is corrupted: " + "album " + a.getName() + " has a bad containment hierarchy."); } } depth++; } Log.log(Log.LEVEL_TRACE, MODULE, "Ordered " + orderedAlbums.size() + " albums"); status(su, StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "ftchdAlbms")); }
public void postBatchToPipeline(List docs) throws Exception { int numDocs = docs.size(); int requestId = requestCounter.incrementAndGet(); ArrayList<String> mutable = null; synchronized (this) { mutable = new ArrayList<String>(sessions.keySet()); } if (mutable.isEmpty()) { // completely hosed ... try to re-establish all sessions synchronized (this) { try { Thread.sleep(2000); } catch (InterruptedException ie) { Thread.interrupted(); } sessions = establishSessions(originalEndpoints, fusionUser, fusionPass, fusionRealm); mutable = new ArrayList<String>(sessions.keySet()); } if (mutable.isEmpty()) throw new IllegalStateException( "No available endpoints! " + "Check log for previous errors as to why there are no more endpoints available. This is a fatal error."); } if (mutable.size() > 1) { Exception lastExc = null; // try all the endpoints until success is reached ... or we run out of endpoints to try ... while (!mutable.isEmpty()) { String endpoint = getLbEndpoint(mutable); if (endpoint == null) { // no more endpoints available ... fail if (lastExc != null) { log.error( "No more endpoints available to retry failed request (" + requestId + ")! raising last seen error: " + lastExc); throw lastExc; } else { throw new RuntimeException( "No Fusion pipeline endpoints available to process request " + requestId + "! Check logs for previous errors."); } } if (log.isDebugEnabled()) log.debug( "POSTing batch of " + numDocs + " input docs to " + endpoint + " as request " + requestId); Exception retryAfterException = postJsonToPipelineWithRetry(endpoint, docs, mutable, lastExc, requestId); if (retryAfterException == null) { lastExc = null; break; // request succeeded ... } lastExc = retryAfterException; // try next endpoint (if available) after seeing an exception } if (lastExc != null) { // request failed and we exhausted the list of endpoints to try ... log.error("Failing request " + requestId + " due to: " + lastExc); throw lastExc; } } else { String endpoint = getLbEndpoint(mutable); if (log.isDebugEnabled()) log.debug( "POSTing batch of " + numDocs + " input docs to " + endpoint + " as request " + requestId); Exception exc = postJsonToPipelineWithRetry(endpoint, docs, mutable, null, requestId); if (exc != null) throw exc; } }
public void treatmentGenStateGraph() { try { PrintWriter file = new PrintWriter(new FileWriter(destination)); // We want color wells in red ArrayList<String> lesPuits = new ArrayList<String>(); file.println("digraph G {"); file.println(); // Prepare a bubble giving all genes file.println("/* Order of genes */"); file.print("/*$g*/" + "\""); for (int j = 0; j < autoGraphState.vGeneNames.size(); j++) { file.print(autoGraphState.vGeneNames.get(j)); file.print(" ; "); } file.println("\"" + "/*$fg*/" + " [color=green,fontcolor=black];"); file.println(); // List potential and their position statements file.println("/* States and their transitions */"); for (int j = 0; j < autoGraphState.vStates.size(); j++) { file.print("/*$e*/" + "\""); file.print(autoGraphState.vStates.get(j).getEtiquette()); file.print("\""); // x et y file.print( "/*x:" + autoGraphState.vStates.get(j).getX() + ";y:" + autoGraphState.vStates.get(j).getY() + " $fe*/"); file.println(";"); } file.println(); // Recherche des transitions /* * A faire : les clous ! */ file.println("/* Transitions */"); for (int i = 0; i < autoGraphState.vTranStates.size(); i++) { TransState trans = (TransState) autoGraphState.vTranStates.get(i); file.print("/*$t*/" + "\""); for (int j = 0; j < autoGraphState.vStates.size(); j++) { State state = (State) autoGraphState.vStates.get(j); if (state.getNum() == trans.getNumInitialState()) { /* * L'�tiquette est de la forme "[0, 1, 2]" * On la veut sous la forme "0,1,2" dans le .gen */ String labelGen = state.getEtiquette(); labelGen = labelGen.replace("[", ""); labelGen = labelGen.replace("]", ""); labelGen = labelGen.replace(" ", ""); file.print(labelGen); } } file.print("\""); file.print("->"); file.print("\""); for (int j = 0; j < autoGraphState.vStates.size(); j++) { State state = (State) autoGraphState.vStates.get(j); if (state.getNum() == trans.getNumFinalState()) { /* * The label is of the form "[0, 1, 2]" * We want it in the form "0,1,2" in the .gen */ String labelGen = state.getEtiquette(); labelGen = labelGen.replace("[", ""); labelGen = labelGen.replace("]", ""); labelGen = labelGen.replace(" ", ""); file.print(labelGen); if (state.couleurPuit.equals(Color.red)) { lesPuits.add("\"" + labelGen + "\""); } } } file.print("\"" + "/*$ft*/"); file.println(";"); } file.println(); // Ecrire dans le .gen les puits, et dire qu'il faudra afficher leur police en rouge file.println("/* Stable states */"); while (lesPuits.isEmpty() == false) { String lePuit = lesPuits.get(0); file.println("/*$p*/" + lePuit + "/*$fp*/" + " [fontcolor=red];"); while (lesPuits.contains(lePuit)) { lesPuits.remove(lePuit); } } file.println(); file.println("}"); file.println(""); file.println(autoGraphState.comment); file.println(""); // uncomment file.println("$ed"); file.println("gene x"); file.println("equation : 2 + 3 * s(p,y,theta(x,x)) * s(n,x,theta(x,y)) ;"); file.println("thetas : theta(x,x) < theta(x,y) ;"); file.println("gene y"); file.println("equation : 1 + 2 * s(p,y,theta(y,x)) ;"); file.println("thetas : theta(y,x) ;"); file.println("$fed"); file.println(""); /* Le systeme d'equation ci-dessous sert pour les tests * Il sera a supprimer */ // fichier.println("$ed"); // fichier.println("gene x"); // fichier.println("equation : 2 + 3 * s(p,y,theta(x,x)) * s(n,x,theta(x,y)) ;"); // fichier.println("thetas : theta(x,x) < theta(x,y) ;"); // fichier.println("gene y"); // fichier.println("equation : 1 + 2 * s(p,y,theta(y,x)) ;"); // fichier.println("thetas : theta(y,x) ;"); // fichier.println("$fed"); // fichier.println(""); file.close(); } catch (Exception e) { e.printStackTrace(); } }
public void run() { started = true; Thread.currentThread().setName("Q2-" + getInstanceId().toString()); try { /* * The following code determines whether a MBeanServer exists * already. If so then the first one in the list is used. * I have not yet find a way to interrogate the server for * information other than MBeans so to pick a specific one * would be difficult. */ ArrayList mbeanServerList = MBeanServerFactory.findMBeanServer(null); if (mbeanServerList.isEmpty()) { server = MBeanServerFactory.createMBeanServer(JMX_NAME); } else { server = (MBeanServer) mbeanServerList.get(0); } final ObjectName loaderName = new ObjectName(Q2_CLASS_LOADER); try { loader = (QClassLoader) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { return new QClassLoader(server, libDir, loaderName, mainClassLoader); } }); server.registerMBean(loader, loaderName); loader = loader.scan(false); } catch (Throwable t) { if (log != null) log.error("initial-scan", t); else t.printStackTrace(); } factory = new QFactory(loaderName, this); initSystemLogger(); addShutdownHook(); q2Thread = Thread.currentThread(); q2Thread.setContextClassLoader(loader); if (cli != null) cli.start(); initConfigDecorator(); for (int i = 1; !shutdown; i++) { try { boolean forceNewClassLoader = scan(); QClassLoader oldClassLoader = loader; loader = loader.scan(forceNewClassLoader); if (loader != oldClassLoader) { oldClassLoader = null; // We want't this to be null so it gets GCed. System.gc(); // force a GC log.info( "new classloader [" + Integer.toString(loader.hashCode(), 16) + "] has been created"); } deploy(); checkModified(); relax(SCAN_INTERVAL); if (i % (3600000 / SCAN_INTERVAL) == 0) logVersion(); } catch (Throwable t) { log.error("start", t); relax(); } } undeploy(); try { server.unregisterMBean(loaderName); } catch (InstanceNotFoundException e) { log.error(e); } if (decorator != null) { decorator.uninitialize(); } if (exit && !shuttingDown) System.exit(0); } catch (Exception e) { if (log != null) log.error(e); else e.printStackTrace(); System.exit(1); } }
public static void contactBookOperations(String contactBookName) throws IOException, ParseException { FileWriter fr = new FileWriter(contactBookName, true); BufferedReader fileReader = new BufferedReader(new FileReader(contactBookName)); BufferedWriter fileWriter = new BufferedWriter(fr); String address = ""; String name = ""; boolean validName = false; String dateOfBirth = ""; boolean dateValid = false; String petName = ""; int tag = 0; String contactType = ""; boolean invalidTag = false; boolean moreEmail = false; String email = ""; String emailChoice = ""; boolean morePhone = true; String phoneChoice = ""; String phoneList = ""; String contactAdded = ""; long phoneNum = 0; int choice = 0; ArrayList<String> nameList = new ArrayList<String>(); // arrayList to hold names of contacts in the file... Scanner sc = new Scanner(System.in); String searchString = ""; Scanner stringReader = new Scanner(System.in); String line = ""; String totalDetails = ""; // System.out.println(fileReader); while (choice != 6) { System.out.println("\nTO ADD CONTACT->PRESS 1 "); System.out.println("TO EDIT CONTACT->PRESS 2 "); System.out.println("TO REMOVE CONTACT->PRESS 3 "); System.out.println("TO LIST CONTACTS->PRESS 4 "); System.out.println("TO SEARCH CONTACT->PRESS 5 "); System.out.println("TO GO BACK TO PREVIOUS MENU->PRESS 6 "); while (!sc.hasNextInt()) { System.out.println("\nENTER ONLY NUMBERS RANGED FROM 0 - 6"); sc.next(); } choice = sc.nextInt(); switch (choice) { // ADD A NEW CONTACT........ case 1: // add contact option............. // add name dateValid = false; invalidTag = true; moreEmail = true; morePhone = true; email = ""; phoneList = ""; nameList.clear(); System.out.println("\nENTER NAME OF THE PERSON(Ex: Aditya Dey)"); validName = false; fileReader = new BufferedReader(new FileReader(contactBookName)); while (!validName) { name = stringReader.nextLine(); // read contact name from user name = name.trim(); if (name.equals("")) { System.out.println( "\nNAME OF THE PERSON CANNOT BE BLANK\nENTER NAME OF THE PERSON(Ex: Aditya Dey)"); continue; } while (((line = fileReader.readLine()) != null)) // read till end of file { String s = line.substring(0, line.indexOf('=')); // add each name that exists in the file if (!nameList.contains(s)) { nameList.add(s); } } // System.out.println(nameList); if (nameList.contains(name)) // if name already exists, print error message { System.out.println("\nA CONTACT NAMED " + name + " ALREADY EXISTS."); System.out.println("\nPLEASE ADD ANOTHER NAME(Ex: Aditya Dey)"); } else { validName = true; nameList.add(name); } } // date of birth System.out.println( "\nENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT Ex: 12/05/1992 OR PRESS ENTER TO SKIP"); while (!dateValid) { dateOfBirth = stringReader.nextLine(); if (dateOfBirth.trim().compareTo("") == 0) dateValid = true; else // doubt? next() skips next scan... dateValid = isValidDate(dateOfBirth); if (!dateValid) { System.out.println( "\nINVALID DATE...\nENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT Ex: 12/05/1992"); } } // System.out.println(dateOfBirth); // add contact type System.out.println("\nENTER PET NAME OF THE PERSON OR ENTER TO SKIP"); petName = stringReader.nextLine(); System.out.println("\nCHOOSE CONTACT TYPE..."); System.out.println("\nFOR FAMILY->PRESS 1 "); System.out.println("FOR FRIENDS->PRESS 2 "); System.out.println("FOR ASSOCIATES->PRESS 3 "); System.out.println("FOR OTHERS->PRESS 4 "); while (!sc.hasNextInt()) { System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1 - 4"); sc.nextLine(); } tag = sc.nextInt(); while (invalidTag) { switch (tag) { case 1: contactType = "Family"; invalidTag = false; break; case 2: contactType = "Friend"; invalidTag = false; break; case 3: contactType = "Associate"; invalidTag = false; break; case 4: contactType = "Others"; invalidTag = false; break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-4"); invalidTag = true; break; } } // System.out.println(contactType); System.out.println("\nENTER ADDRESS IN ONE LINE OR PRESS ENTER TO SKIP"); address = stringReader.nextLine(); // System.out.println(address); while (moreEmail) { System.out.println("\nENTER EMAIL ADDRESS OR PRESS ENTER TO SKIP"); email = email + "," + stringReader.nextLine(); // System.out.println(email); if (!(email.trim()).equals(",")) { System.out.println( "\nTO ADD EMAIL ADRESS->PRESS 'Y' OR 'y'..TO STOP ADDING EMAIL PRESS ANY OTHER KEY"); emailChoice = stringReader.nextLine(); if (emailChoice.equals("y") || emailChoice.equals("Y")) { moreEmail = true; } else { moreEmail = false; } } else { moreEmail = false; } } email = email.substring(1, email.length()); // System.out.println(email); while (morePhone) { System.out.println("\nENTER CONTACT NUMBER"); while (!sc.hasNextLong()) { System.out.println("\nINVALID CONTACT NUMBER.\nENTER A VALID CONTACT NUMBER"); sc.next(); } phoneNum = sc.nextLong(); phoneList = phoneList + "," + phoneNum; sc.nextLine(); // doubt? not included: doesnt read phonechoice..... System.out.println( "\nTO ADD MORE PHONE NUMBERS->PRESS 'Y' OR 'y' \nOTHERWISE PRESS ANY OTHER KEY"); phoneChoice = sc.nextLine(); if (phoneChoice.equals("y") || phoneChoice.equals("Y")) { morePhone = true; } else { morePhone = false; } } phoneList = phoneList.substring(1, phoneList.length()); System.out.println("FOLLOWING DETAILS HAS BEEN SAVED IN THE PHONEBOOK"); System.out.println("---------------------------------------------------"); System.out.println( "[" + name + "," + petName + "," + contactType + "," + address + "," + dateOfBirth + "," + email + "," + phoneList + "]"); totalDetails = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + new Date(); fileWriter.write(totalDetails); fileWriter.newLine(); fileWriter.flush(); break; // EDITING A CONTACT case 2: String editName = ""; String details = ""; String line3 = ""; String[] detailParts; String newDob = ""; String newPetName = ""; String newAddress = ""; String newContactType = ""; String newEmail = ""; String newPhone = ""; String newString = ""; String name3 = ""; choice = 0; nameList.clear(); String[] parts; fileReader = new BufferedReader(new FileReader(contactBookName)); while (((line = fileReader.readLine()) != null)) // read till end of file { String s = line.substring(0, line.indexOf('=')); // add each name that exists in the file if (!nameList.contains(s)) { nameList.add(s); } } BufferedReader editReader = new BufferedReader(new FileReader(contactBookName)); dateValid = false; invalidTag = true; String editContact = ""; System.out.println("\nENTER THE CONTACT TO BE EDITED"); editName = stringReader.nextLine(); if (!nameList.contains(editName)) { System.out.println("\nA CONTACT NAMED " + editName + " DOES NOT EXIST"); } else { while ((line3 = editReader.readLine()) != null) { // System.out.println(line3); name3 = line3.substring(0, line3.indexOf("=")); if (!name3.equals(editName)) { newString = newString + line3 + System.getProperty("line.separator"); } else { editContact = line3; } } details = editContact.substring(editContact.indexOf("=") + 1, editContact.length()); detailParts = details.split(":"); newDob = detailParts[0]; newPetName = detailParts[1]; newContactType = detailParts[2]; newAddress = detailParts[3]; newEmail = detailParts[4]; newPhone = detailParts[5]; while (choice != 7) { System.out.println("\nTO EDIT DATE OF BIRTH->PRESS 1"); System.out.println("TO EDIT PET NAME->PRESS 2 "); System.out.println("TO EDIT CONTACT TYPE->PRESS 3 "); System.out.println("TO EDIT ADDRESS->PRESS 4 "); System.out.println("TO ADD EMAIL->PRESS 5 "); System.out.println("TO ADD PHONE NUMBER->PRESS 6 "); System.out.println("TO GO BACK TO THE PREVIOUS MENU->PRESS 7 "); System.out.print("ENTER YOUR CHOICE::\t"); while (!sc.hasNextInt()) { System.out.println("ENTER ONLY INTEGERS IN THE RANGE 1-7"); sc.nextLine(); } choice = sc.nextInt(); switch (choice) { case 1: System.out.println( "\nENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT EG: 12/05/1992"); while (!dateValid) { newDob = stringReader.nextLine(); // doubt? next() skips next scan... dateValid = isValidDate(newDob); if (!dateValid) { System.out.println( "\nINVALID DATE...ENTER DOB OF THE PERSON IN DD/MM/YYYY FORMAT EG: 12/05/1992"); } } break; case 2: System.out.println("\nENTER NEW PET NAME OF THE PERSON OR ENTER TO SKIP"); newPetName = stringReader.nextLine(); break; case 3: System.out.println("\nCHOOSE CONTACT TYPE..."); System.out.println("\nFOR FAMILY->PRESS 1 "); System.out.println("FOR FRIENDS->PRESS 2 "); System.out.println("FOR ASSOCIATES->PRESS 3 "); System.out.println("FOR OTHERS->PRESS 4 "); while (!sc.hasNextInt()) { System.out.println("\nENTER ONLY NUMBERS IN THE RANGE 1 - 3"); sc.nextLine(); } tag = sc.nextInt(); while (invalidTag) { switch (tag) { case 1: newContactType = "Family"; invalidTag = false; break; case 2: newContactType = "Friend"; invalidTag = false; break; case 3: newContactType = "Associate"; invalidTag = false; break; case 4: newContactType = "Others"; invalidTag = false; break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-4"); invalidTag = true; break; } } break; case 4: System.out.println("\nENTER NEW ADDRESS IN ONE LINE"); newAddress = stringReader.nextLine(); break; case 5: moreEmail = true; while (moreEmail) { System.out.println("\nENTER EMAIL ADDRESS OR PRESS ENTER TO SKIP"); newEmail = newEmail + "," + stringReader.nextLine(); // System.out.println(email); if (!(newEmail.trim()).equals(",")) { System.out.println( "TO ADD EMAIL->PRESS 'Y' OR 'y'..TO STOP ADDING EMAIL PRESS ANY OTHER KEY"); emailChoice = stringReader.nextLine(); if (emailChoice.equals("y") || emailChoice.equals("Y")) { moreEmail = true; } else { moreEmail = false; } } else { moreEmail = false; } } break; case 6: morePhone = true; while (morePhone) { System.out.println("\nENTER PHONE NUMBER"); while (!sc.hasNextLong()) { System.out.println("\nONLY VALID PHONE NUMBERS ALLOWED"); sc.next(); } phoneNum = sc.nextLong(); newPhone = phoneNum + ","; sc.nextLine(); // doubt? not included: doesnt read phonechoice..... System.out.println( "\nTO ADD MORE PHONE NUMBERS->PRESS 'y' or 'Y'\nOTHERWISE PRESS ANY OTHER KEY"); phoneChoice = sc.nextLine(); if (phoneChoice.equals("y") || phoneChoice.equals("Y")) { morePhone = true; } else { morePhone = false; } } phoneList = newPhone; phoneList = phoneList.substring(1, phoneList.length()); break; case 7: System.out.println( "[" + editName + "," + newPetName + "," + newContactType + "," + newAddress + "," + newDob + "," + newEmail + "," + newPhone + "]"); String newDetails = editName + "=" + newDob + ":" + newPetName + ":" + newContactType + ":" + newAddress + ":" + newEmail + ":" + newPhone + ":" + new Date(); newString = newString + newDetails + System.getProperty("line.separator"); BufferedWriter editWriter = new BufferedWriter(new FileWriter(contactBookName)); editWriter.write(newString); editWriter.close(); break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-7"); break; } } } // dob:petname:tag:address:email1,email2,email3..:ph1,ph2,...:crtdate break; case 3: // REMOVING A CONTACT BufferedReader removalReader = new BufferedReader(new FileReader(contactBookName)); String name2 = ""; String line2 = ""; String nameRemoved = ""; String finalString = ""; System.out.println("\nENTER THE NAME TO BE REMOVED"); nameRemoved = stringReader.nextLine(); if (!nameList.contains(nameRemoved)) { System.out.println("\nA CONTACT WITH NAME " + nameRemoved + " DOES NOT EXIST\n"); } else { while ((line2 = removalReader.readLine()) != null) { name2 = line2.substring(0, line2.indexOf("=")); if (!name2.equals(nameRemoved)) { finalString = finalString + line2 + System.getProperty("line.separator"); } } BufferedWriter removalWriter = new BufferedWriter(new FileWriter(contactBookName)); removalWriter.write(finalString); removalWriter.close(); System.out.println("CONTACT " + nameRemoved + " REMOVED "); } break; // LISTING ELEMENTS case 4: int listChoice = 0; BufferedReader listReader = new BufferedReader(new FileReader(contactBookName)); parts = null; TreeMap<String, String> nameDetailMap = new TreeMap<String, String>(); String line4 = ""; while (listChoice != 4) { System.out.println("\nTO DISPLAY CONTACTS BY ALPHABETICAL ORDERING OF NAMES->PRESS 1 "); System.out.println("TO DISPLAY CONTACTS BY CREATED DATE->PRESS 2 "); System.out.println("TO DISPLAY CONTACTS BY TAG->PRESS 3 "); System.out.println("TO GO BACK TO PREVIOUS MENU->PRESS 4 "); System.out.print("ENTER CHOICE::\t"); while (!sc.hasNextInt()) { System.out.println("ENTER ONLY INTEGERS IN THE RANGE 1-4"); sc.next(); } listChoice = sc.nextInt(); switch (listChoice) { // ORDERING CONTACTS BY ALPHABETICAL ORDERING OF NAMES.............. case 1: listReader = new BufferedReader(new FileReader(contactBookName)); line4 = ""; parts = null; while ((line4 = listReader.readLine()) != null) { parts = line4.split("="); nameDetailMap.put(parts[0], parts[1]); } Collection<String> c = nameDetailMap.keySet(); Iterator<String> it = c.iterator(); if (it.hasNext()) { System.out.println( "\nCONTACTS BELOW ARE LISTED IN ALPHABETICAL ORDERING OF NAMES"); System.out.println("-----------------------------------------------------------"); } else { System.out.println("NO CONTACTS AVAILABLE"); } while (it.hasNext()) { String s = (String) it.next(); System.out.println("\n\n" + s); System.out.println("---------------------------------"); String[] contactDetail = nameDetailMap.get(s).split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println("Date of Birth::\t" + contactDetail[0]); System.out.println("Pet name::\t" + contactDetail[1]); System.out.println("Contact Type::\t" + contactDetail[2]); System.out.println("Address::\t" + contactDetail[3]); System.out.println("Email Address::\t" + contactDetail[4]); System.out.println("Phone No::\t" + contactDetail[5]); System.out.println("Contact added::\t" + contactDetail[6]); } break; // ORDERING CONTACTS BY CREATED DATE.............. case 2: BufferedReader br = new BufferedReader(new FileReader(contactBookName)); line4 = ""; String date = ""; String[] part; TreeMap<Date, String> tm = new TreeMap<Date, String>(); while ((line4 = br.readLine()) != null) { part = line4.split(":"); SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd H:m"); String h = (part[6] + ":" + part[7]); Date d = formatter.parse(h); tm.put(d, line4); } Collection<Date> c1 = tm.keySet(); // System.out.println(c1); Iterator<Date> it1 = c1.iterator(); if (it1.hasNext()) { System.out.println("\nCONTACTS BELOW ARE LISTED IN ORDER OF CREATED DATES"); System.out.println("--------------------------------------------------------"); } else { System.out.println("NO CONTACTS AVAILABLE"); } while (it1.hasNext()) { String s = it1.next().toString() + ""; // System.out.println(s); System.out.println("\n\n" + s); SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd H:m"); Date d = formatter.parse(s); System.out.println("---------------------------------"); String[] nameContact = tm.get(d).split("="); System.out.println(nameContact[0]); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println("Date of Birth::\t" + contactDetail[0]); System.out.println("Pet name::\t" + contactDetail[1]); System.out.println("Contact Type::\t" + contactDetail[2]); System.out.println("Address::\t" + contactDetail[3]); System.out.println("Email Address::\t" + contactDetail[4]); System.out.println("Phone No::\t" + contactDetail[5]); } break; //// ORDERING CONTACTS BY TAG.............. // dob:petname:tag:address:email1,email2,email3..:ph1,ph2,...:crtdate case 3: ArrayList<String> familyList = new ArrayList<String>(); ArrayList<String> friendsList = new ArrayList<String>(); ArrayList<String> colleaguesList = new ArrayList<String>(); ArrayList<String> othersList = new ArrayList<String>(); line4 = ""; parts = null; br = new BufferedReader(new FileReader(contactBookName)); while ((line4 = br.readLine()) != null) { parts = line4.split(":"); String relation = parts[2]; if (relation.equals("Family")) { familyList.add(line4); } else if (relation.equals("Friend")) { friendsList.add(line4); } else if (relation.equals("Associate")) { colleaguesList.add(line4); } else { othersList.add(line4); } } if (familyList.isEmpty() && friendsList.isEmpty() && colleaguesList.isEmpty() && othersList.isEmpty()) { System.out.println("NO CONTACTS AVAILABLE."); } else { System.out.println("\nCONTACTS BELOW ARE LISTED ACCORDING TO TAGS"); System.out.println("--------------------------------------------------------"); } if (!familyList.isEmpty()) { System.out.println("\nFAMILY CONTACTS\n----------------------------"); for (Object s : familyList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } if (!friendsList.isEmpty()) { System.out.println("\nFRIEND CONTACTS\n----------------------------"); for (Object s : friendsList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } if (!colleaguesList.isEmpty()) { System.out.println("\nASSOCIATE CONTACTS\n----------------------------"); for (Object s : colleaguesList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } if (!othersList.isEmpty()) { System.out.println("\nOTHER CONTACTS\n----------------------------"); for (Object s : othersList) { String[] nameContact = s.toString().split("="); System.out.println(nameContact[0] + "\n"); String[] contactDetail = nameContact[1].split(":"); for (int i = 0; i < contactDetail.length; i++) { if (contactDetail[i].trim().compareTo("") == 0) { contactDetail[i] = "Unavailable"; } } System.out.println(" Date of Birth::\t" + contactDetail[0]); System.out.println(" Pet name::\t\t" + contactDetail[1]); System.out.println(" Address::\t\t" + contactDetail[3]); System.out.println(" Email Address::\t" + contactDetail[4]); System.out.println(" Phone No::\t\t" + contactDetail[5]); System.out.println(" Contact added::\t" + contactDetail[6]); } } break; case 4: break; default: System.out.println("\nENTER ONLY INTEGERS IN THE RANGE 1-5"); break; } } break; // SEARCH CONTACTS BOOK... case 5: String[] details1 = null; line4 = ""; searchString = ""; parts = null; String addedDetails = ""; fileReader = new BufferedReader(new FileReader(contactBookName)); System.out.println("ENTER THE STRING TO BE SERCHED FOR IN THE CONTACTS BOOK"); searchString = stringReader.nextLine(); ArrayList<String> nameMatchList = new ArrayList<String>(); ArrayList<String> emailMatchList = new ArrayList<String>(); ArrayList<String> tagMatchList = new ArrayList<String>(); ArrayList<String> addressMatchList = new ArrayList<String>(); ArrayList<String> dobMatchList = new ArrayList<String>(); ArrayList<String> phoneMatchList = new ArrayList<String>(); ArrayList<String> petNameMatchList = new ArrayList<String>(); String addedString = ""; while ((line4 = fileReader.readLine()) != null) { parts = line4.split("="); name = parts[0]; details1 = parts[1].split(":"); dateOfBirth = details1[0]; petName = details1[1]; contactType = details1[2]; address = details1[3]; email = details1[4]; phoneList = details1[5]; contactAdded = details1[6]; addedString = ""; // System.out.println("name = "+name+" dateOfbirth = "+dateOfBirth+" petName // ="+petName+" contactType ="+contactType+"address ="+address+"email // ="+email+"phoneList ="+phoneList); if (name.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; nameMatchList.add(addedString); } if (dateOfBirth.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; dobMatchList.add(addedString); } if (petName.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; petNameMatchList.add(addedString); } if (contactType.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; tagMatchList.add(addedString); } if (address.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; addressMatchList.add(addedString); } if (email.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; emailMatchList.add(addedString); } if (phoneList.contains(searchString)) { addedString = name + "=" + dateOfBirth + ":" + petName + ":" + contactType + ":" + address + ":" + email + ":" + phoneList + ":" + contactAdded; phoneMatchList.add(addedString); } } System.out.println( "\nTOTAL NUMBER OF MATCHES = " + (nameMatchList.size() + dobMatchList.size() + petNameMatchList.size() + tagMatchList.size() + addressMatchList.size() + emailMatchList.size() + phoneMatchList.size())); if (!nameMatchList.isEmpty()) { System.out.println( "\nTOTAL " + nameMatchList.size() + " NAMES MATCH WITh " + searchString + "\n"); System.out.println( "\nTHE NAMES OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : nameMatchList) { showContactByType(s, 2); } } if (!dobMatchList.isEmpty()) { System.out.println( "\nTOTAL " + dobMatchList.size() + " DOBS' MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE DOB'S OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : dobMatchList) { showContactByType(s, 2); } } if (!petNameMatchList.isEmpty()) { System.out.println( "\nTOTAL " + petNameMatchList.size() + " PET NAMES MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE PET NAMES OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : petNameMatchList) { showContactByType(s, 2); } } if (!tagMatchList.isEmpty()) { System.out.println( "\nTOTAL " + tagMatchList.size() + " CONTACT TYPES MATCH WITH THE " + searchString + "\n"); System.out.println( "\nTHE TAGS OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : tagMatchList) { showContactByType(s, 2); } } if (!addressMatchList.isEmpty()) { System.out.println( "\nTOTAL " + addressMatchList.size() + " ADDRESSES MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE ADDRESSES OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : addressMatchList) { showContactByType(s, 2); } } if (!emailMatchList.isEmpty()) { System.out.println( "\nTOTAL " + emailMatchList.size() + " EMAILS MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE EMAIL'S OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : emailMatchList) { showContactByType(s, 2); } } if (!phoneMatchList.isEmpty()) { System.out.println( "\nTOTAL " + phoneMatchList.size() + " CONTACT NUMBERS MATCH WITH " + searchString + "\n"); System.out.println( "\nTHE PHONE NUMBERS OF THE FOLLOWING CONTACTS MATCHES WITH THE SEARCH STRING "); System.out.println( "--------------------------------------------------------------------------------\n"); for (Object s : phoneMatchList) { showContactByType(s, 2); } } break; case 6: break; default: System.out.println("\nENTER ONLY NUMBERS RANGED FROM 1-6"); break; } } // fileReader.close(); // fileWriter.close(); // stringReader.close(); // sc.close(); }
/** Lists made transactions, searchable by either Date or Account number. */ private static void listaTransaktioner() { ArrayList<GjordTransaktion> logs = new ArrayList<GjordTransaktion>(); System.out.print( "Vill du lista transaktioner efter\n" + "1. kontonummer 2. datum\nAnge ditt val: "); String datumEllerKonto = "konto"; switch (tbScanner.nextLine()) { case "1": datumEllerKonto = "konto"; break; case "2": datumEllerKonto = "datum"; break; case "0": System.out.println("Avbryter."); return; default: System.out.println("Fel inmatning. Avbryter."); return; } if (datumEllerKonto == "konto") { System.out.print("Ange det konto vars transaktioner du vill visa: "); String svar; while (true) { svar = tbScanner.nextLine(); if (m.accountExists(svar)) { System.out.println("Kontot hittades, söker i transaktionsloggen..."); break; } else { System.out.print("Inte ett giltigt konto. Forsok igen: "); } } logs = m.getLogsByAccountNumber(svar); } else if (datumEllerKonto == "datum") { // Försöker läsa in ett datum System.out.print("Ange det datum transaktionen(erna) genomforts: (yyyyMMdd)"); SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd"); Date svar; String temp; while (true) { // loopar tills ett datum ar inmatat try { // testa om datum temp = tbScanner.nextLine(); svar = dFormat.parse(temp); } catch (ParseException | NumberFormatException e) { // om inte ett datum.. System.out.println("Använd formatet yyyyMMdd!"); continue; // börja om loop } break; // annars avbryt loop; } // listar transaktioner under ett visst datum System.out.println("Forsoker lista transaktioner under ett visst datum.."); logs = m.getLogsAfter(svar); } else { System.out.println("Detta alternativ finns inte."); } if (logs.isEmpty()) { System.out.println("Hittade inga rader!"); } else { for (GjordTransaktion log : logs) { System.out.println(log.toFileString()); } } }
public static void maingame() throws IOException { // Declaring Variables String rulechoice; Scanner fin = new Scanner(new FileReader("Rules of Cheat.txt")); Scanner in = new Scanner(System.in); PrintWriter fout = new PrintWriter(new FileWriter("Cheat Game Results.txt")); int loop = 3; System.out.println("Hi " + name + ","); System.out.println("Welcome to the Cheat Card Game"); System.out.println( "Would you like to display rules? Press Y for yes or any other key to continue"); rulechoice = in.nextLine(); if (rulechoice.equalsIgnoreCase("y")) { System.out.println(fin.nextLine()); System.out.println(fin.nextLine()); System.out.println(fin.nextLine()); System.out.println(fin.nextLine()); System.out.println(fin.nextLine()); System.out.println(fin.nextLine()); System.out.println(fin.nextLine()); System.out.println(fin.nextLine()); } fin.close(); // First loop outer: while (loop > 0) { // Checking if the last person played allowing you to call cheat on them if (lastPlayerHand != null) { playerCallCheat(); } // Showing your cards System.out.println("Here are your cards"); System.out.println(bubblesort(p1hand).toString()); // Telling you what Rank of cards you have to play System.out.println("You have to play " + currentRank()); // Second Loop while (true) { // Asking the user to pick from 2 options System.out.println("What would you like to do? Type the letter"); System.out.println("a. Play Cards \nb. Check status"); option = in.nextLine(); // deciding which option if (option.equalsIgnoreCase("a")) { // initialize playcard method playCard(); for (int i = 2; i <= 4; i++) { // Giving the computer opponents a chance to call cheat on the player opponentCallCheat(getHand(i)); // Checking if the player's hand is empty after the opponents have had the opportunity // to call cheat if (p1hand.isEmpty() == true) { System.out.println("You won!"); System.out.println( "The game results have been printed in a text file in the project folder."); // exporting results to a txt file fout.println("Player:" + name); fout.println("The pile had " + pile.size() + " card(s)"); fout.println("You had " + p1hand.size() + " card(s)"); fout.println("AI Player 1 had " + p2hand.size() + " card(s)"); fout.println("AI Player 2 had " + p3hand.size() + " card(s)"); fout.println("AI Player 3 had " + p4hand.size() + " card(s)"); fout.println("You were on turn " + turnnumber); fout.println("Result: Player Won"); fout.close(); // Breaks the first loop break outer; } // AI player number (i) plays their cards compPlayer(getHand(i)); if (i < 4) { // Gives the player a chance to call cheat after the AI plays playerCallCheat(); // Checks if the AI player has an empty hand after the player has had the opportunity // to call cheat if (getHand(i).isEmpty() == true) { System.out.println("You lose!"); System.out.println( "The game results have been printed in a text file in the project folder."); // exporting results to a txt file fout.println("Player:" + name); fout.println("The pile had " + pile.size() + " card(s)"); fout.println("You had " + p1hand.size() + " card(s)"); fout.println("AI Player 1 had " + p2hand.size() + " card(s)"); fout.println("AI Player 2 had " + p3hand.size() + " card(s)"); fout.println("AI Player 3 had " + p4hand.size() + " card(s)"); fout.println("You were on turn " + turnnumber); fout.println("Result: Computer Won"); fout.close(); // Breaks the first loop break outer; } } } // adds a turn to the turn counter turnnumber++; break; } else if (option.equalsIgnoreCase("b")) { // display the status System.out.println("The pile has " + pile.size() + " card(s)"); System.out.println("You have " + p1hand.size() + " card(s)"); System.out.println("AI Player 1 has " + p2hand.size() + " card(s)"); System.out.println("AI Player 2 has " + p3hand.size() + " card(s)"); System.out.println("AI Player 3 has " + p4hand.size() + " card(s)"); System.out.println("You are on turn " + turnnumber); } else { System.out.println("Please enter a to Play Cards or b to Check Status"); } } } }