// Creates a new thread, runs the program in that thread, and reports any errors as needed. private void run(String clazz) { try { // Makes sure the JVM resets if it's already running. if (JVMrunning) kill(); // Some String constants for java path and OS-specific separators. String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; // Tries to run compiled code. ProcessBuilder builder = new ProcessBuilder(path, clazz); // Should be good now! Everything past this is on you. Don't mess it up. println( "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr); println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr); JVM = builder.start(); // Note that as of right now, there is no support for input. Only output. Reader errorReader = new InputStreamReader(JVM.getErrorStream()); Reader outReader = new InputStreamReader(JVM.getInputStream()); // Writer inReader = new OutputStreamWriter(JVM.getOutputStream()); redirectErr = redirectIOStream(errorReader, err); redirectOut = redirectIOStream(outReader, out); // redirectIn = redirectIOStream(null, inReader); } catch (Exception e) { // This catches any other errors we might get. println("Some error thrown", progErr); logError(e.toString()); displayLog(); return; } }
private byte[] loadClassData(String className) throws IOException { Playground.println("Loading class " + className + ".class", warning); File f = new File(System.getProperty("user.dir") + "/" + className + ".class"); byte[] b = new byte[(int) f.length()]; new FileInputStream(f).read(b); return b; }
private static String expand(String str) { if (str == null) { return null; } StringBuilder result = new StringBuilder(); Pattern re = Pattern.compile("^(.*?)\\$\\{([^}]*)\\}(.*)"); while (true) { Matcher matcher = re.matcher(str); if (matcher.matches()) { result.append(matcher.group(1)); String property = matcher.group(2); if (property.equals("/")) { property = "file.separator"; } String value = System.getProperty(property); if (value != null) { result.append(value); } str = matcher.group(3); } else { result.append(str); break; } } return result.toString(); }
private InstanceList readFile() throws IOException { String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(fileName), encoding); ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); pipeList.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}\\p{L}+"))); pipeList.add(new TokenSequence2FeatureSequence()); InstanceList testing = new InstanceList(new SerialPipes(pipeList)); try { while (scanner.hasNextLine()) { String text = scanner.nextLine(); text = text.replaceAll("\\x0d", ""); Pattern patten = Pattern.compile("^(.*?),(.*?),(.*)$"); Matcher matcher = patten.matcher(text); if (matcher.find()) { docIds.add(matcher.group(1)); testing.addThruPipe(new Instance(matcher.group(3), null, "test instance", null)); } } } finally { scanner.close(); } return testing; }
public void init(Editor _editor) { this.m_editor = _editor; File toolRoot = null; try { toolRoot = new File( SequantoAutomationTool.class .getProtectionDomain() .getCodeSource() .getLocation() .toURI()) .getParentFile() .getParentFile(); } catch (java.net.URISyntaxException ex) { toolRoot = new File( SequantoAutomationTool.class .getProtectionDomain() .getCodeSource() .getLocation() .getPath()) .getParentFile() .getParentFile(); } m_generatorPy = new File(new File(toolRoot, "generator"), "generate_automation_defines.py") .getAbsolutePath(); m_isWindows = System.getProperty("os.name").toLowerCase().contains("win"); if (m_isWindows) { for (File root : File.listRoots()) { File[] files = root.listFiles( new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().startsWith("python"); } }); if (files != null) { for (File directory : files) { m_pythonPath = new File(directory, "python.exe"); break; } } } if (m_pythonPath == null) { Base.showMessage( "ERROR", String.format( "Could not python interpreter - Generate Automation tool will not work.")); } } }
protected String replace(String key, Link link) { if (link != null && link.contains(key)) return "${infinite:" + link.toString() + "}"; if (key != null) { key = key.trim(); if (key.length() > 0) { Processor source = domain; String value = null; if (key.indexOf(';') < 0) { Instruction ins = new Instruction(key); if (!ins.isLiteral()) { SortedList<String> sortedList = SortedList.fromIterator(domain.iterator()); StringBuilder sb = new StringBuilder(); String del = ""; for (String k : sortedList) { if (ins.matches(k)) { String v = replace(k, new Link(source, link, key)); if (v != null) { sb.append(del); del = ","; sb.append(v); } } } return sb.toString(); } } while (value == null && source != null) { value = source.getProperties().getProperty(key); source = source.getParent(); } if (value != null) return process(value, new Link(source, link, key)); value = doCommands(key, link); if (value != null) return process(value, new Link(source, link, key)); if (key != null && key.trim().length() > 0) { value = System.getProperty(key); if (value != null) return value; } if (!flattening && !key.equals("@")) domain.warning("No translation found for macro: " + key); } else { domain.warning("Found empty macro key"); } } else { domain.warning("Found null macro key"); } return "${" + key + "}"; }
void getTable() { if (chooser == null) { File userdir = new File(System.getProperty("user.dir")); chooser = new JFileChooser(userdir); } if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); fileLength = file.length(); setTitle(windowTitle + ": " + file.getAbsolutePath()); int size = Key.getEncryptionKeySize(this, true); key = Key.getEncryptionKey(this, true, size); if (key == null) key = defaultKey; initCipher(); } else System.exit(0); }
static void realMain(String[] args) throws Throwable { // jmap doesn't work on Windows if (System.getProperty("os.name").startsWith("Windows")) return; final String childClassName = Job.class.getName(); final String classToCheckForLeaks = Job.classToCheckForLeaks(); final String uniqueID = String.valueOf(new Random().nextInt(Integer.MAX_VALUE)); final String[] jobCmd = { java, "-Xmx8m", "-classpath", System.getProperty("test.classes", "."), childClassName, uniqueID }; final Process p = new ProcessBuilder(jobCmd).start(); final String childPid = match( commandOutputOf(jps, "-m"), "(?m)^ *([0-9]+) +\\Q" + childClassName + "\\E *" + uniqueID + "$", 1); final int n0 = objectsInUse(p, childPid, classToCheckForLeaks); final int n1 = objectsInUse(p, childPid, classToCheckForLeaks); equal(p.waitFor(), 0); equal(p.exitValue(), 0); failed += p.exitValue(); // Check that no objects were leaked. System.out.printf("%d -> %d%n", n0, n1); check(Math.abs(n1 - n0) < 2); // Almost always n0 == n1 check(n1 < 20); drainers.shutdown(); }
/** * 异步请求手动处理测试 * * @param req * @param res */ public static void asyncManual(HttpServletRequest req, HttpServletResponse res) { System.out.println("*************************system prop is " + System.getProperty("0")); IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt(); iAsyncMgntInt.setAsyncCall(true); // 标志异步调用 SSysOperatorsListHolder holder = new SSysOperatorsListHolder(); CBSErrorMsg errMsg = new CBSErrorMsg(); try { // iAsyncMgntInt.setMessageConsumer("test_worker"); int result = iAsyncMgntInt.select_sysOperators(holder, errMsg); // System.out.println("*****result is "+result); // System.out.println(iAsyncMgntInt.getMseq().getMessageKey()+ ":" // + iAsyncMgntInt.getMseq().getMessageSequence()); res.getWriter().println("<html>"); res.getWriter().println("<head>"); res.getWriter().println("<title>"); res.getWriter().println("异步架构系统测试"); res.getWriter().println("</title>"); res.getWriter().println("</head>"); res.getWriter().println("<body>"); res.getWriter().println("<form name=\"testform\" action=\"./test\" method=\"get\">"); res.getWriter().println("<input type=\"hidden\" name=\"method\" value=\"asyncResult\">"); res.getWriter() .println( "<input type=\"hidden\" name=\"mseq\" value=\"" + iAsyncMgntInt.getMseq().getMessageSequence() + "\">"); res.getWriter().println("<input type=\"submit\" name=\"test\" value=\"获取异步响应\">"); res.getWriter().println("</form>"); res.getWriter().println("</body>"); res.getWriter().println("</html>"); } catch (Exception e) { try { res.getWriter().println("<pre>"); e.printStackTrace(res.getWriter()); } catch (IOException e1) { e1.printStackTrace(); } } }
// remove temp files, the pipeline.jar operator isn't working. public void deleteTempFiles() { System.out.println("\nRemoving these temp files:"); File workingDir = new File(System.getProperty("user.dir")); File[] toExamine = workingDir.listFiles(); for (File f : toExamine) { boolean d = false; String n = f.getName(); if (n.startsWith("pipeinstancelog")) d = true; else if (n.contains(".DOC.sample")) d = true; else if (n.contains("allDepths.")) d = true; else if (n.startsWith("nocalls.")) d = true; else if (n.startsWith("snpeff.")) d = true; else if (n.contains("plice")) d = true; if (d) { System.out.println("\t" + n); f.deleteOnExit(); } } // delete the temp uncompressed vcf (required by Pipeline.jar) if (deleteTempVcf) System.out.println("\t" + finalVcf.getName()); }
static String javahome() { String jh = System.getProperty("java.home"); return (jh.endsWith("jre")) ? jh.substring(0, jh.length() - 4) : jh; }
public final class ListOfCallPoints { @Nonnull private static final String EOL = System.getProperty("line.separator"); private static final Pattern LESS_THAN_CHAR = Pattern.compile("<"); @Nonnull private final StringBuilder content; public ListOfCallPoints() { content = new StringBuilder(100); } public void insertListOfCallPoints(@Nullable List<CallPoint> callPoints) { if (content.length() == 0) { content.append(EOL).append(" "); } content.append(" <ol style='display:none'>"); if (callPoints == null) { content.append("</ol>").append(EOL).append(" "); return; } content.append(EOL); CallPoint currentCP = callPoints.get(0); appendTestMethod(currentCP.getStackTraceElement()); appendRepetitionCountIfNeeded(currentCP); for (int i = 1, n = callPoints.size(); i < n; i++) { CallPoint nextCP = callPoints.get(i); StackTraceElement ste = nextCP.getStackTraceElement(); if (nextCP.isSameTestMethod(currentCP)) { content.append(", ").append(ste.getLineNumber()); } else { content.append("</li>").append(EOL); appendTestMethod(ste); } appendRepetitionCountIfNeeded(nextCP); currentCP = nextCP; } content.append("</li>").append(EOL).append(" </ol>").append(EOL).append(" "); } private void appendTestMethod(@Nonnull StackTraceElement current) { content.append(" <li>"); content.append(current.getClassName()).append('#'); content .append(LESS_THAN_CHAR.matcher(current.getMethodName()).replaceFirst("<")) .append(": "); content.append(current.getLineNumber()); } private void appendRepetitionCountIfNeeded(@Nonnull CallPoint callPoint) { int repetitionCount = callPoint.getRepetitionCount(); if (repetitionCount > 0) { content.append('x').append(1 + repetitionCount); } } @Nonnull public String getContents() { String result = content.toString(); content.setLength(0); return result; } }
private Matcher getClassNameRegex(String propertySuffix) { String regex = System.getProperty("jmockit-coverage-" + propertySuffix, ""); return regex.length() == 0 ? null : Pattern.compile(regex).matcher(""); }
public class _336_D_Bear_Vasily_and_Beautiful_Strings { // ->solution screencast http://youtu.be/oHg5SJYRHA0 public void solve() { int n = ni(); long res = 0; out.println(res); } // IO methods void run() throws Exception { long s = System.currentTimeMillis(); solve(); out.flush(); pr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new _336_D_Bear_Vasily_and_Beautiful_Strings().run(); } InputStream in = System.in; PrintWriter out = new PrintWriter(System.out); private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } public String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } public char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } public int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } void pr(Object... ob) { if (!oj) System.out.println(Arrays.deepToString(ob).replace("],", "],\n")); } }
/** * a View for rendering Text's based on bitmaps (when available) or TextLayout (when image not * available) */ public class TextViewHybrid extends LeafElementView implements Runnable { boolean wantToComputeLatexDimensions = true; // from preferences: do we want to run LateX to compute preferences boolean wantToGetBitMap = true; // from preferences: do we want to run LateX+pstoimg to get a bitmap. // wantToGetBitMap=true should Imply wantToComputeLatexDimensions=true protected double strx, stry; // TextLayout/Image location with respect to PicText's anchor point // [pending] pas joli. A enlever sous peu (utilise juste dans HitInfo que je ne comprends pas, je // laisse donc en attendant) protected TextLayout textLayout; // the TextLayout that renders the text string of this TextEditable // [inherited] shape; But here it's the frame box !!! (not textLayout !) protected AffineTransform text2ModelTr = new AffineTransform();; // maps text coordinates to Model coordinates protected BufferedImage image; // bitmap (if null, we rely on TextLayout) protected boolean areDimensionsComputed; // has the real dimensions been read from the log file ? protected int fileDPI = 300; // Dot Per Inch of the file (for image resizing) [pending] gerer les preferences de ce // parametre // il faut passer la valeur en DPI en argument a create_bitmap.sh /** pattern used for parsing log file */ private static final Pattern LogFilePattern = Pattern.compile("JPICEDT INFO:\\s*([0-9.]*)pt,\\s*([0-9.]*)pt,\\s*([0-9.]*)pt"); private static final String CR_LF = System.getProperty("line.separator"); private PicPoint ptBuf = new PicPoint(); /** construct a new View for the given PicRectangle */ public TextViewHybrid(PicText te, AttributesViewFactory f) { super(te, f); areDimensionsComputed = false; changedUpdate(null); } public PicText getElement() { return (PicText) element; } /** * Returns the text rotation in radians : subclassers that don't support rotating text may return * 0 here. Used by TextLayout only. */ protected double getRotation() { // debug(set.getAttribute(TEXT_ROTATION).toString()); return Math.toRadians(element.getAttribute(TEXT_ROTATION).doubleValue()); } /** * Give notification from the model that a change occured to the text this view is responsible for * rendering. * * <p> */ public void changedUpdate(DrawingEvent.EventType eventType) { PicText text = (PicText) element; if (textLayout == null) { // new *************************** begin (by ss & bp) textLayout = new TextLayout( text.getText(text.getTextMode()).length() == 0 ? " " : text.getText(text.getTextMode()), // new *************************** end (by ss & bp) DefaultViewFactory.textFont, // static field new FontRenderContext(null, false, false)); } if (eventType == DrawingEvent.EventType.TEXT_CHANGE) { // new *************************** begin (by ss & bp) textLayout = new TextLayout( text.getText(text.getTextMode()).length() == 0 ? " " : text.getText(text.getTextMode()), // new *************************** end (by ss & bp) DefaultViewFactory.textFont, new FontRenderContext(null, false, false)); // first try to create a bitmap image = null; // aka "reset" image => we might temporarily resort to TextLayout until the image is // ready areDimensionsComputed = false; // reset dimensions to the textlayout dimensions text.setDimensions( textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent()); // new *************************** begin (by ss & bp) if (wantToComputeLatexDimensions && text.getText(text.getTextMode()).length() > 0) { // new *************************** end (by ss & bp) // don't produce a bitmap for an empty string (LaTeX might not like it) // [pending] this should be made dependent on a preference's option new Thread(this).start(); } if (image == null) super.changedUpdate(null); // ie resort to TextLayout (update all) } else { text.updateFrame(); super.changedUpdate(eventType); } } // Thread's run method aimed at creating a bitmap asynchronously public void run() { Drawing drawing = new Drawing(); PicText rawPicText = new PicText(); String s = ((PicText) element).getText(); rawPicText.setText(s); drawing.add( rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former // parent... (then pb with the view ) drawing.setNotparsedCommands( "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{" + s + "}" + CR_LF + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{" + s + "}" + CR_LF + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{" + s + "}" + CR_LF + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight, \\the\\jpicdepth }" + CR_LF); RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION; // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun); boolean isWriteTmpTeXfile = true; String bitmapExt = "png"; // [pending] preferences String cmdLine = "{i}/unix/tetex/create_bitmap.sh {p} {f} " + bitmapExt + " " + fileDPI; // [pending] preferences ContentType contentType = getContainer().getContentType(); RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug RunExternalCommand command = new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile); command .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX // process has completed) if (wantToComputeLatexDimensions) { // load size of text: try { File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log"); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(logFile)); } catch (FileNotFoundException fnfe) { System.out.println("Cannot find log file! " + fnfe.getMessage()); System.out.println(logFile); } catch (IOException ioex) { System.out.println("Log file IO exception"); ioex.printStackTrace(); } // utile ? System.out.println("Log file created! file=" + logFile); getDimensionsFromLogFile(reader, (PicText) element); syncStringLocation(); // update dimensions syncBounds(); syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that dimensions are available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } if (wantToGetBitMap) { // load image: try { File bitmapFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt); this.image = ImageIO.read(bitmapFile); System.out.println( "Bitmap created! file=" + bitmapFile + ", width=" + image.getWidth() + "pixels, height=" + image.getHeight() + "pixels"); if (image == null) return; syncStringLocation(); // sets strx, stry, and dimensions of text syncBounds(); // update the AffineTransform that will be applied to the bitmap before displaying on screen PicText te = (PicText) element; text2ModelTr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! text2ModelTr.translate(te.getLeftX(), te.getTopY()); text2ModelTr.scale( te.getWidth() / image.getWidth(), -(te.getHeight() + te.getDepth()) / image.getHeight()); // [pending] should do something special to avoid dividing by 0 or setting a rescaling // factor to 0 [non invertible matrix] (java will throw an exception) syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that bitmap is available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } } /** * update strx stry = location of TextLayout's bottom-Left corner with respect to PicText's * anchor-point */ protected void syncStringLocation() { PicText te = (PicText) element; PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); if (image == null) { if (!areDimensionsComputed) { te.setDimensions( textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent()); } strx = te.getLeftX() - anchor.x; stry = te.getBaseLineY() - anchor.y; } else { // image not null strx = te.getLeftX() - anchor.x; stry = te.getBottomY() - anchor.y; } } /** * Synchronize the textLayout and the shape (=frame box, by calling syncFrame) with the model When * <code>TextLayout</code> is used, this delegates to <code>getRotation()</code> where computing * rotation angle is concerned, and updates the AffineTransform returned by <code> * getTextToModelTransform()</code>. */ protected void syncShape() { PicText te = (PicText) element; // textLayout = new TextLayout(te.getText().length()==0 ? " " : te.getText(), // textFont, // new FontRenderContext(null,false,false)); text2ModelTr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! // the reference point of an image is the top-left one, but the refpoint of a text layout is on // the baseline if (image != null) { text2ModelTr.translate(te.getLeftX(), te.getTopY()); if (te.getWidth() != 0 && image.getWidth() != 0 && (te.getDepth() + te.getHeight()) != 0 && image.getHeight() != 0) text2ModelTr.scale( te.getWidth() / image.getWidth(), -(te.getHeight() + te.getDepth()) / image.getHeight()); } else { // Hack ? Just cheating a little bit ? Ou juste ruse ? // we want here to use the dimensions of the textLayout instead of latex dimensions if // areDimensionsComputed // sinon on va aligner le textlayout en fonction des parametres latex, et l'Utilisateur (qui // est bien bete) ne va rien comprendre. double latexH = 0; double latexD = 0; double latexW = 0; if (areDimensionsComputed) { // store latex dimensions, and setDimensions to textLayout ones latexH = te.getHeight(); latexD = te.getDepth(); latexW = te.getWidth(); te.setDimensions( textLayout.getBounds().getWidth(), textLayout.getAscent(), textLayout.getDescent()); } text2ModelTr.translate(te.getLeftX(), te.getBaseLineY()); if (areDimensionsComputed) { // restore latex dimensions te.setDimensions(latexW, latexH, latexD); } // Autre possibilite= comprimer le texte pour qu'il rentre dans la boite (evite le hack // ci-dessus): // text2ModelTr.scale(te.getWidth()/textLayout.getWidth(),-(te.getHeight()+te.getDepth())/textLayout.getHeight()); text2ModelTr.scale(1.0, -1.0); } syncFrame(); } /** * synchronize frame shape and location (TextLayout only) ; this is called by syncShape(), so that * subclasser might override easily when only rectangular shapes are availables. */ protected void syncFrame() { PicText te = (PicText) element; if (!te.isFramed()) { return; } AffineTransform tr = new AffineTransform(); // maps Image coordinates to Model coordinates (see paint) tr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); tr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! shape = tr.createTransformedShape(te.getShapeOfFrame()); } protected void getDimensionsFromLogFile(BufferedReader reader, PicText text) { if (reader == null) { return; } String line = ""; // il rale si j'initialise pas ... boolean finished = false; while (!finished) { try { line = reader.readLine(); } catch (IOException ioex) { ioex.printStackTrace(); return; } if (line == null) { System.out.println("Size of text not found in log file..."); return; } System.out.println(line); Matcher matcher = LogFilePattern.matcher(line); if (line != null && matcher.find()) { System.out.println("FOUND :" + line); finished = true; try { text.setDimensions( 0.3515 * Double.parseDouble(matcher.group(1)), // height, pt->mm (1pt=0.3515 mm) 0.3515 * Double.parseDouble(matcher.group(2)), // width 0.3515 * Double.parseDouble(matcher.group(3))); // depth areDimensionsComputed = true; } catch (NumberFormatException e) { System.out.println("Logfile number format problem: $line" + e.getMessage()); } catch (IndexOutOfBoundsException e) { System.out.println("Logfile regexp problem: $line" + e.getMessage()); } } } return; } /** Synchronizes bounding box with the model ; */ protected void syncBounds() { PicText te = (PicText) element; // [pending] Il faut tenir compte de la rotation ! Rectangle2D latexBB = null; // BB relative to latex dimensions (including rotation) (without frame) Rectangle2D textLayoutBB = null; // BB relative to textLayout dimensions (including rotation) (without frame) Rectangle2D textBB = null; // BB of the text (including rotation), without frame if (areDimensionsComputed) { // compute latexBB Rectangle2D nonRotated = new Rectangle2D.Double( te.getLeftX(), te.getBottomY(), te.getWidth(), te.getHeight() + te.getDepth()); AffineTransform tr = new AffineTransform(); // maps Image coordinates to Model coordinates (see paint) tr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); tr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! latexBB = tr.createTransformedShape(nonRotated).getBounds2D(); } if (image == null) { // compute textLayoutBB Rectangle2D nonRotated = textLayout.getBounds(); textLayoutBB = text2ModelTr.createTransformedShape(nonRotated).getBounds2D(); } // use textLayoutBB or latexBB or their union if (image != null) textBB = latexBB; else { if (!areDimensionsComputed) textBB = textLayoutBB; else { textBB = latexBB.createUnion(textLayoutBB); } } // union with frame BB if (te.isFramed()) { super.syncBounds(); // update bounds of the frame if necessary Rectangle2D.union(super.bounds, textBB, this.bounds); } else this.bounds = textBB; } /** * Render the View to the given graphic context. This implementation render the interior first, * then the outline. */ public void paint(Graphics2D g, Rectangle2D a) { if (!a.intersects(getBounds())) return; if (image != null) { // paint bitmap g.drawImage(image, text2ModelTr, null); // debug: g.setPaint(Color.red); g.draw(this.bounds); super.paint(g, a); // possibly paint framebox if non-null } else { // paint textlayout super.paint(g, a); // possibly paint framebox if non-null AffineTransform oldAT = g.getTransform(); // paint text in black g.setPaint(Color.black); // from now on, we work in Y-direct (<0) coordinates to avoid inextricable problems with font // being mirrored... g.transform(text2ModelTr); // also include rotation textLayout.draw(g, 0.0f, 0.0f); // [pending] ajouter un cadre si areDimensionsComputed (wysiwyg du pauvre) // get back to previous transform g.setTransform(oldAT); if (DEBUG) { g.setPaint(Color.red); g.draw(bounds); } } } /** * This implementation calls <code>super.hitTest</code> and returns the result if non-null (this * should be a HitInfo.Point), then returns a HitInfo.Interior if the mouse-click occured inside * the text bound (as defined by text layout) * * @return a HitInfo corresponding to the given mouse-event */ public HitInfo hitTest(PEMouseEvent e) { // from Bitmap: if (image != null) { if (getBounds().contains(e.getPicPoint())) { return new HitInfo.Interior((PicText) element, e); } return null; } // from TextLayout: if (!getBounds().contains(e.getPicPoint())) return null; PicText te = (PicText) element; // recompute textlayout b-box, but store it in a temporary field ! Rectangle2D tb = textLayout.getBounds(); Shape text_bounds = text2ModelTr.createTransformedShape(tb); if (text_bounds.contains(e.getPicPoint())) { // [SR:pending] for the hitInfo to be reliable, getPicPoint() should first be transformed by // inverse text2ModelTr ! (especially when rotationAngle != 0) TextHitInfo thi = textLayout.hitTestChar( (float) (e.getPicPoint().x - strx), (float) (e.getPicPoint().y - stry)); // guaranteed to return a non-null thi return new HitInfo.Text((PicText) element, thi, e); } // test hit on textlayout's bounding rectangle : // else if (bounds.contains(e.getPicPoint())) return new HitInfo.Interior(element,e); return null; } /** * [SR:pending] make this view implement aka TextEditableView interface (or something like it), * where TextEditableView is a subinterface of View with text-editing specific capabilities. * * <p>Returns the TextLayout which is responsible for painting the textual content of this element */ public TextLayout getTextLayout() { return textLayout; } /** * Return an affine transform which translat b/w the TextLayout coordinate system and the * jpicedt.graphic.model coordinate system. [SR:pending] refactor method name to something more * explanatory */ public AffineTransform getTextToModelTransform() { return text2ModelTr; } } // TextView
public class Main6 { public void solve() { // Scanner sc = new Scanner(System.in); // int n = Integer.parseInt(sc.nextLine()); // n = 10000; pr("\n".getBytes()); int n = ni(); // int xx=100000; while (n != 0) { String s = ns1(); // int size = (int)(Math.random()*10000); // char [] axx = new char[size]; // for (int i = 0; i < axx.length; i++) { // char ccc = (char)((Math.random()*('z'-'a'))+'a'); //// pr(ccc); // axx[i]=ccc; // } // String s =new String(axx); // for (int i = 0; i < 1000000; i++) { // s+='x'; // } // int[] xa = new int[1000000000]; // pr(s); int a = 0; HashMap<Character, Integer> set = new HashMap<Character, Integer>(); // int [] alf= new int[128]; int r = 0; for (int i = 0; i < s.length(); i++) { // pr(set); // char that = s.charAt(a); char thix = s.charAt(i); if (set.size() < n) { Integer ax = set.get(thix); if (ax == null) { set.put(thix, 1); } else set.put(thix, ax + 1); } else if (set.size() == n) { if (!set.containsKey(thix)) { while (set.size() == n && a < s.length()) { char that = s.charAt(a); if (set.containsKey(that) && set.get(that) > 1) set.put(that, set.get(that) - 1); else set.remove(that); a++; } set.put(thix, 1); } else set.put(thix, set.get(thix) + 1); } int newr = i - a + 1; // pr(newr, set,a,i,s.substring(a,i)); if (newr > r) { // pr() // pr(set,a,i,s.substring(a,i)); r = newr; } // r=max(r,); } out.println(r); // n = (int)(Math.random()*128); n = ni(); } } void run() throws Exception { in = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); // pr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main6().run(); } InputStream in; PrintWriter out; String INPUT = ""; private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private String ns1() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b) && b != ' ')) { // when nextLine, sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } void pr(Object... ob) { if (!oj) System.out.println(Arrays.deepToString(ob).replace("],", "],\n")); } }
static { String flag = System.getProperty("sikuli.console"); if (flag != null && flag.equals("false")) { ENABLE_IO_REDIRECT = false; } }
public class EditorConsolePane extends JPanel implements Runnable { private static final String me = "EditorConsolePane: "; static boolean ENABLE_IO_REDIRECT = true; static { String flag = System.getProperty("sikuli.console"); if (flag != null && flag.equals("false")) { ENABLE_IO_REDIRECT = false; } } private int NUM_PIPES; private JTextPane textArea; private Thread[] reader; private boolean quit; private PipedInputStream[] pin; private JPopupMenu popup; Thread errorThrower; // just for testing (Throws an Exception at this Console) class PopupListener extends MouseAdapter { JPopupMenu popup; PopupListener(JPopupMenu popupMenu) { popup = popupMenu; } public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } public EditorConsolePane() { super(); textArea = new JTextPane(); textArea.setEditorKit(new HTMLEditorKit()); textArea.setTransferHandler(new JTextPaneHTMLTransferHandler()); String css = PreferencesUser.getInstance().getConsoleCSS(); ((HTMLEditorKit) textArea.getEditorKit()).getStyleSheet().addRule(css); textArea.setEditable(false); setLayout(new BorderLayout()); add(new JScrollPane(textArea), BorderLayout.CENTER); if (ENABLE_IO_REDIRECT) { Debug.log(3, "EditorConsolePane: starting redirection to message area"); int npipes = 2; NUM_PIPES = npipes * ScriptRunner.scriptRunner.size(); pin = new PipedInputStream[NUM_PIPES]; reader = new Thread[NUM_PIPES]; for (int i = 0; i < NUM_PIPES; i++) { pin[i] = new PipedInputStream(); } int irunner = 0; for (IScriptRunner srunner : ScriptRunner.scriptRunner.values()) { Debug.log(3, "EditorConsolePane: redirection for %s", srunner.getName()); if (srunner.doSomethingSpecial( "redirect", Arrays.copyOfRange(pin, irunner * npipes, irunner * npipes + 2))) { Debug.log(3, "EditorConsolePane: redirection success for %s", srunner.getName()); quit = false; // signals the Threads that they should exit // TODO Hack to avoid repeated redirect of stdout/err ScriptRunner.systemRedirected = true; // Starting two seperate threads to read from the PipedInputStreams for (int i = irunner * npipes; i < irunner * npipes + npipes; i++) { reader[i] = new Thread(this); reader[i].setDaemon(true); reader[i].start(); } irunner++; } } } // Create the popup menu. popup = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Clear messages"); // Add ActionListener that clears the textArea menuItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { textArea.setText(""); } }); popup.add(menuItem); // Add listener to components that can bring up popup menus. MouseListener popupListener = new PopupListener(popup); textArea.addMouseListener(popupListener); } private void appendMsg(String msg) { HTMLDocument doc = (HTMLDocument) textArea.getDocument(); HTMLEditorKit kit = (HTMLEditorKit) textArea.getEditorKit(); try { kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null); } catch (Exception e) { Debug.error(me + "Problem appending text to message area!\n%s", e.getMessage()); } } /* public synchronized void windowClosed(WindowEvent evt) { quit=true; this.notifyAll(); // stop all threads try { reader.join(1000);pin.close(); } catch (Exception e){} try { reader2.join(1000);pin2.close(); } catch (Exception e){} System.exit(0); } public synchronized void windowClosing(WindowEvent evt) { frame.setVisible(false); // default behaviour of JFrame frame.dispose(); } */ static final String lineSep = System.getProperty("line.separator"); private String htmlize(String msg) { StringBuilder sb = new StringBuilder(); Pattern patMsgCat = Pattern.compile("\\[(.+?)\\].*"); msg = msg.replace("&", "&").replace("<", "<").replace(">", ">"); for (String line : msg.split(lineSep)) { Matcher m = patMsgCat.matcher(line); String cls = "normal"; if (m.matches()) { cls = m.group(1); } line = "<span class='" + cls + "'>" + line + "</span>"; sb.append(line).append("<br>"); } return sb.toString(); } @Override public synchronized void run() { try { for (int i = 0; i < NUM_PIPES; i++) { while (Thread.currentThread() == reader[i]) { try { this.wait(100); } catch (InterruptedException ie) { } if (pin[i].available() != 0) { String input = this.readLine(pin[i]); appendMsg(htmlize(input)); if (textArea.getDocument().getLength() > 0) { textArea.setCaretPosition(textArea.getDocument().getLength() - 1); } } if (quit) { return; } } } } catch (Exception e) { Debug.error(me + "Console reports an internal error:\n%s", e.getMessage()); } } public synchronized String readLine(PipedInputStream in) throws IOException { String input = ""; do { int available = in.available(); if (available == 0) { break; } byte b[] = new byte[available]; in.read(b); input = input + new String(b, 0, b.length); } while (!input.endsWith("\n") && !input.endsWith("\r\n") && !quit); return input; } public void clear() { textArea.setText(""); } }
public void actionPerformed(ActionEvent e) { if (isDirectorySelected()) { File dir = getDirectory(); if (dir != null) { try { // Strip trailing ".." dir = ShellFolder.getNormalizedFile(dir); } catch (IOException ex) { // Ok, use f as is } changeDirectory(dir); return; } } JFileChooser chooser = getFileChooser(); String filename = getFileName(); FileSystemView fs = chooser.getFileSystemView(); File dir = chooser.getCurrentDirectory(); if (filename != null) { // Remove whitespaces from end of filename int i = filename.length() - 1; while (i >= 0 && filename.charAt(i) <= ' ') { i--; } filename = filename.substring(0, i + 1); } if (filename == null || filename.length() == 0) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; } File selectedFile = null; File[] selectedFiles = null; // Unix: Resolve '~' to user's home directory if (File.separatorChar == '/') { if (filename.startsWith("~/")) { filename = System.getProperty("user.home") + filename.substring(1); } else if (filename.equals("~")) { filename = System.getProperty("user.home"); } } if (chooser.isMultiSelectionEnabled() && filename.length() > 1 && filename.charAt(0) == '"' && filename.charAt(filename.length() - 1) == '"') { List<File> fList = new ArrayList<File>(); String[] files = filename.substring(1, filename.length() - 1).split("\" \""); // Optimize searching files by names in "children" array Arrays.sort(files); File[] children = null; int childIndex = 0; for (String str : files) { File file = fs.createFileObject(str); if (!file.isAbsolute()) { if (children == null) { children = fs.getFiles(dir, false); Arrays.sort(children); } for (int k = 0; k < children.length; k++) { int l = (childIndex + k) % children.length; if (children[l].getName().equals(str)) { file = children[l]; childIndex = l + 1; break; } } } fList.add(file); } if (!fList.isEmpty()) { selectedFiles = fList.toArray(new File[fList.size()]); } resetGlobFilter(); } else { selectedFile = fs.createFileObject(filename); if (!selectedFile.isAbsolute()) { selectedFile = fs.getChild(dir, filename); } // check for wildcard pattern FileFilter currentFilter = chooser.getFileFilter(); if (!selectedFile.exists() && isGlobPattern(filename)) { changeDirectory(selectedFile.getParentFile()); if (globFilter == null) { globFilter = new GlobFilter(); } try { globFilter.setPattern(selectedFile.getName()); if (!(currentFilter instanceof GlobFilter)) { actualFileFilter = currentFilter; } chooser.setFileFilter(null); chooser.setFileFilter(globFilter); return; } catch (PatternSyntaxException pse) { // Not a valid glob pattern. Abandon filter. } } resetGlobFilter(); // Check for directory change action boolean isDir = (selectedFile != null && selectedFile.isDirectory()); boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); boolean isCtrl = (e != null && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0); if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { changeDirectory(selectedFile); return; } else if ((isDir || !isFileSelEnabled) && (!isDir || !isDirSelEnabled) && (!isDirSelEnabled || selectedFile.exists())) { selectedFile = null; } } if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { selectedFiles = new File[] {selectedFile}; } chooser.setSelectedFiles(selectedFiles); // Do it again. This is a fix for bug 4949273 to force the // selected value in case the ListSelectionModel clears it // for non-existing file names. chooser.setSelectedFiles(selectedFiles); } else { chooser.setSelectedFile(selectedFile); } chooser.approveSelection(); } else { if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } chooser.cancelSelection(); } }
/** * This class contains some static methods to retrieve information on the Pokepon package itself. * THIS IS A VERY DELICATE CLASS: HANDLE WITH CARE! * * @author Giacomo Parolini */ public class Meta { public static final char DIRSEP = '/'; // probably superfluous /** * Working directory of the pokepon class tree; if game is launched from JAR, this is the * directory where the JAR resides; else, it is the directory containing 'pokepon'. */ private static Path cwd; static { String tmp = Meta.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // Strip the leading slash if on windows if (tmp.matches("^/[A-Z]:/.*")) { tmp = tmp.substring(1); } cwd = Paths.get(tmp); } private static URL cwdURL; public static final boolean LAUNCHED_FROM_JAR = cwd.toString().endsWith(".jar"); /** Are we on Windows or on POSIX os? */ public static final boolean IS_WINDOWS = System.getProperty("os.name").toUpperCase().contains("WIN"); /** Directory containing variable data (teams, confs, ...) */ public static final String APPDATA_DIR = (IS_WINDOWS ? System.getenv("APPDATA") + DIRSEP : System.getenv("HOME") + DIRSEP + ".") + "pokepon"; static { // if launched from a jar, use the parent as cwd if (LAUNCHED_FROM_JAR) cwd = cwd.getParent(); if (Debug.on) printDebug("[Meta] cwd: " + cwd + "\nLaunched from jar: " + LAUNCHED_FROM_JAR); } private static String cwdStr = "file://" + cwd.toString(); public static URL getCwd() { if (cwdURL != null) return cwdURL; try { cwdURL = new URL(cwdStr); return cwdURL; } catch (MalformedURLException e) { return null; } } public static Path getCwdPath() { return cwd; } private static URL getSubURL(final String subdir) { if (LAUNCHED_FROM_JAR) { if (Debug.pedantic) printDebug( "[Meta.getSubURL(" + POKEPON_ROOTDIR + DIRSEP + subdir + ")]: " + Meta.class.getClassLoader().getResource(POKEPON_ROOTDIR + DIRSEP + subdir)); return Meta.class.getClassLoader().getResource(POKEPON_ROOTDIR + DIRSEP + subdir); } else { try { return new URL( getCwd().getProtocol() + "://" + getCwd().getPath() + DIRSEP + POKEPON_ROOTDIR + DIRSEP + subdir); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } private static URL getAppDataURL(final String subdir) { try { if (Debug.pedantic) printDebug( "[Meta.getAppDataURL(" + subdir + ")]: " + "file://" + APPDATA_DIR + DIRSEP + subdir); return new URL("file://" + APPDATA_DIR + DIRSEP + subdir); } catch (MalformedURLException e) { throw new RuntimeException(e); } } /** Returns the URL of the package root */ public static URL getRootURL() { return getSubURL(""); } /** Returns the URL of the pony directory. */ public static URL getPonyURL() { return getSubURL(PONY_DIR); } /** Returns the URL of the move directory. */ public static URL getMoveURL() { return getSubURL(MOVE_DIR); } /** Returns the URL of the item directory. */ public static URL getItemURL() { return getSubURL(ITEM_DIR); } /** Returns the URL of the ability directory. */ public static URL getAbilityURL() { return getSubURL(ABILITY_DIR); } /** Returns the URL of the save directory. NOTE: this is in local AppData */ public static URL getSaveURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(SAVE_DIR) : getSubURL("data" + DIRSEP + SAVE_DIR); } /** Returns the URL of the battle directory. */ public static URL getBattleURL() { return getSubURL(BATTLE_DIR); } /** Returns the URL of the data directory. NOTE: this is in local AppData */ public static URL getDataURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(DATA_DIR) : getSubURL("data"); } /** Returns the URL of the resources directory */ public static URL getResourcesURL() { return getSubURL(RESOURCE_DIR); } /** Returns the URL of the sprites directory */ public static URL getSpritesURL() { return getSubURL(SPRITE_DIR); } /** Returns the URL of the tokens directory */ public static URL getTokensURL() { return getSubURL(TOKEN_DIR); } /** Returns the URL of the hazards directory */ public static URL getHazardsURL() { return getSubURL(HAZARD_DIR); } /** Returns the URL of the net directory */ public static URL getNetURL() { return getSubURL(NET_DIR); } /** Returns the URL of the audiofiles directory */ public static URL getAudioURL() { return getSubURL(AUDIO_DIR); } /** Returns the URL of the battle records directory. THIS IS IN APPDATA */ public static URL getBattleRecordsURL() { return LAUNCHED_FROM_JAR ? getAppDataURL(BATTLE_RECORDS_DIR) : getSubURL("data" + DIRSEP + BATTLE_RECORDS_DIR); } /** Takes a string and hides its extension */ public static String hideExtension(final String str) { String[] arr = str.split("\\."); if (arr.length <= 1) return str; // there was no "." in str. StringBuilder sb = new StringBuilder(""); for (int i = 0; i < arr.length - 1; ++i) { if (sb.length() > 0) sb.append("."); sb.append(arr[i]); } return sb.toString(); } /** * Given a simple class name, returns the package to which it belongs (stripped of the initial * "pokepon.") or null if no file is found; NOTE: the only searched packages are pony, move, * ability and item. */ public static String getPackage(final String className) { if (findSubclassesNames(complete(PONY_DIR), Pony.class).contains(className)) return "pony"; if (findSubclassesNames(complete(MOVE_DIR), Move.class).contains(className)) return "move"; if (findSubclassesNames(complete(ABILITY_DIR), Ability.class).contains(className)) return "ability"; if (findSubclassesNames(complete(ITEM_DIR), Item.class).contains(className)) return "item"; return null; } /** * Takes a path name and appends it to POKEPON_ROOTDIR to return a valid "relatively absolute" * path (id est: absolute relatively to the java classpath directory) */ public static String complete(final String path) { return POKEPON_ROOTDIR + DIRSEP + path; } /** * This is used to cross-platform-ly locate resources in JAR file; to safely find a resource, do: * getClass().getResource(Meta.complete2(Meta.SOME_DIR)+"/"+resourceName); */ public static String complete2(String path) { String cmp = DIRSEP + complete(path); if (cmp.matches("^/[A-Z]:/.*")) return cmp.substring(1); else return cmp; } /** * Convert all special tags in a string to local URL (e.g [sprite: NameOfPony] => * file://path/to/local/sprite.png); allowed special tags are: sprite, type, movetype * * @return The converted string */ public static String toLocalURL(final String msg) { StringBuilder converted = new StringBuilder(); boolean parsingTag = false; boolean inTagName = true; StringBuilder tagName = new StringBuilder(10); StringBuilder tagArg = new StringBuilder(30); for (int i = 0; i < msg.length(); ++i) { char c = msg.charAt(i); switch (c) { case '[': if (!parsingTag) { parsingTag = true; } else { if (inTagName) tagName.append(c); else tagArg.append(c); } break; case ']': if (parsingTag) { parsingTag = false; converted.append( convertLocalURLTag(tagName.toString().trim(), tagArg.toString().trim())); tagName.setLength(0); tagArg.setLength(0); inTagName = true; } else { converted.append(c); } break; case ':': if (parsingTag) { if (inTagName) inTagName = false; else tagArg.append(c); } else { converted.append(c); } break; default: if (parsingTag) { if (inTagName) tagName.append(c); else tagArg.append(c); } else { converted.append(c); } } } return converted.toString(); } private static String convertLocalURLTag(final String name, final String arg) { if (name.equals("sprite")) { try { Pony tmp = PonyCreator.create(arg); return "" + tmp.getFrontSprite(); } catch (ReflectiveOperationException e) { printDebug("[Meta.toLocalURL] Error creating pony " + arg + ": " + e); e.printStackTrace(); } } else if (name.equals("type")) { try { return "" + pokepon.enums.Type.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating type " + arg); e.printStackTrace(); } } else if (name.equals("movetype")) { try { return "" + Move.MoveType.forName(arg).getToken(); } catch (NullPointerException e) { printDebug("[Meta.toLocalURL] Error creating movetype " + arg); e.printStackTrace(); } } return ""; } /** * Searches for the directory 'dirPath'; if not found, tries to create it, then returns a File * object for that directory. */ public static File ensureDirExists(final String dirPath) { File dirpath = new File(dirPath); if (!dirpath.isDirectory()) { if (!dirpath.exists()) { printDebug("[Meta] " + dirpath + " does not exist: creating it..."); try { Files.createDirectories(Paths.get(dirpath.getPath())); return dirpath; } catch (IOException e) { printDebug("[Meta] Exception while creating directory:"); e.printStackTrace(); return null; } } else { printDebug( "[Meta] Error: path `" + dirpath + "' is not a valid directory path, and could not create it."); return null; } } else return dirpath; } /** * Checks if a given file exists and, if not, create it by copying a default template from * resources; used to create default conf files. * * @param file The path of the file that needs to exist * @param template The path of the template for the file */ public static void ensureFileExists(final String file, final String template) { if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) { if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one."); InputStream stream = Meta.class.getResourceAsStream(template); if (stream == null) { printDebug( "[ WARNING ] template for " + template + " not found. Won't create a default " + file + "."); } else { int readBytes; byte[] buffer = new byte[4096]; try (OutputStream outStream = new FileOutputStream(new File(file))) { while ((readBytes = stream.read(buffer)) > 0) { outStream.write(buffer, 0, readBytes); } if (Debug.on) printDebug("[Meta] created default file " + file + " from " + template + "."); } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException ignore) { } } } } else { if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + "."); } } /** Path of the Pokepon root directory, relative to the java classpath */ public static final String POKEPON_ROOTDIR = "pokepon"; // These are relative to POKEPON_ROOTDIR public static final String PONY_DIR = "pony"; public static final String MOVE_DIR = "move"; public static final String HAZARD_DIR = "move" + DIRSEP + "hazard"; public static final String BATTLE_DIR = "battle"; public static final String MAIN_DIR = "main"; public static final String ENUM_DIR = "enums"; public static final String ITEM_DIR = "item"; public static final String ABILITY_DIR = "ability"; public static final String RESOURCE_DIR = "resources"; public static final String SPRITE_DIR = "resources" + DIRSEP + "sprites"; public static final String TOKEN_DIR = "resources" + DIRSEP + "tokens"; public static final String AUDIO_DIR = "resources" + DIRSEP + "audio"; public static final String NET_DIR = "net"; public static final String ANIMATION_DIR = "gui" + DIRSEP + "animation"; // These are in APPDATA when the game is launched from jar (i.e. in release version) public static final String DATA_DIR = ""; public static final String SAVE_DIR = "teams"; public static final String BATTLE_RECORDS_DIR = "battle_records"; public static void main(String[] args) { consoleHeader(" META "); printMsg("Rootdir:\t" + getRootURL()); printMsg("PonyURL:\t" + getPonyURL()); printMsg("MoveURL:\t" + getMoveURL()); printMsg("HazardURL:\t" + getHazardsURL()); printMsg("BattleURL:\t" + getBattleURL()); printMsg("ItemURL:\t" + getItemURL()); printMsg("AbilityURL:\t" + getAbilityURL()); printMsg("ResourcesURL:\t" + getResourcesURL()); printMsg("SpritesURL:\t" + getSpritesURL()); printMsg("TokensURL:\t" + getTokensURL()); printMsg("AudioURL:\t" + getAudioURL()); printMsg("NetURL: \t" + getNetURL()); printMsg("DataURL:\t" + getDataURL()); printMsg("SaveURL:\t" + getSaveURL()); } }
public class SolrEvalUtils { protected static final String NL = System.getProperty("line.separator"); /** Some fake document ID, which is unlikely to be equal to a real one */ private static final String FAKE_DOC_ID = "THIS_IS_A_VERY_LONG_FAKE_DOCUMENT_ID_THAT_SHOULD_NOT_MATCH_ANY_REAL_ONES"; /** * Saves query results to a TREC result file. * * @param topicId a question ID. * @param results found entries to memorize. * @param trecFile an object used to write to the output file. * @param runId a run ID. * @param maxNum a maximum number of results to save (can be less than the number of retrieved * entries). * @throws IOException */ public static void saveTrecResults( String topicId, SolrRes[] results, BufferedWriter trecFile, String runId, int maxNum) throws IOException { boolean bNothing = true; for (int i = 0; i < Math.min(results.length, maxNum); ++i) { bNothing = false; saveTrecOneEntry(trecFile, topicId, results[i].mDocId, (i + 1), results[i].mScore, runId); } /* * If nothing is returned, let's a fake entry, otherwise trec_eval * will completely ignore output for this query (it won't give us zero * as it should have been!) */ if (bNothing) { saveTrecOneEntry(trecFile, topicId, FAKE_DOC_ID, 1, 0, runId); } } /** * Save positions, scores, etc information for a single retrieved documents. * * @param trecFile an object used to write to the output file. * @param topicId a question ID. * @param docId a document ID of the retrieved document. * @param docPos a position in the result set (the smaller the better). * @param score a score of the document in the result set. * @param runId a run ID. * @throws IOException */ private static void saveTrecOneEntry( BufferedWriter trecFile, String topicId, String docId, int docPos, float score, String runId) throws IOException { trecFile.write( String.format("%s\tQ0\t%s\t%d\t%f\t%s%s", topicId, docId, docPos, score, runId, NL)); } /** * Add one line to the TREC QREL file. * * @param qrelFile * @param topicId * @param docId * @param relGrade */ public static void saveQrelOneEntry( BufferedWriter qrelFile, String topicId, String docId, int relGrade) throws IOException { qrelFile.write(String.format("%s 0 %s %d%s", topicId, docId, relGrade, NL)); } /* * This is for our private use only. */ public static void saveEvalResults( String questionTemplate, String topicId, SolrRes[] results, ArrayList<String> allKeyWords, String docDirName, int maxNum) throws Exception { File docRootDir = new File(docDirName); if (!docRootDir.exists()) { if (!docRootDir.mkdir()) throw new Exception("Cannot create: " + docRootDir.getAbsolutePath()); } String docDirPrefix = docDirName + "/" + topicId; File docDir = new File(docDirPrefix); if (!docDir.exists()) { if (!docDir.mkdir()) throw new Exception("Cannot create: " + docDir.getAbsolutePath()); } // Let's precompile replacement regexps Pattern[] replReg = new Pattern[allKeyWords.size()]; String[] replRepl = new String[allKeyWords.size()]; for (int i = 0; i < allKeyWords.size(); ++i) { replReg[i] = Pattern.compile("(^| )(" + allKeyWords.get(i) + ")( |$)", Pattern.CASE_INSENSITIVE); replRepl[i] = "$1<b>$2</b>$3"; } for (int docNum = 0; docNum < Math.min(results.length, maxNum); ++docNum) { String docId = results[docNum].mDocId; ArrayList<String> docText = results[docNum].mDocText; StringBuilder sb = new StringBuilder(); sb.append("<html><body><br>"); sb.append("<p><i>" + questionTemplate + "</i></p><hr><br>"); for (String s : docText) { for (int k = 0; k < replReg.length; ++k) { while (true) { /* * When words share a space, the replacement will not work in the first pass * Imagine you have * word1 word2 * And both words need to be replaced. In the first pass, only * word1 is replaced. */ String sNew = replReg[k].matcher(s).replaceAll(replRepl[k]); if (sNew.equals(s)) break; s = sNew; } } sb.append(s); sb.append("<br>"); } sb.append("</body></html>"); String text = sb.toString(); File df = new File(docDirPrefix + "/" + docId + ".html"); // Don't overwrite docs! if (!df.exists()) { try { FileUtils.write(df, text); } catch (IOException e) { throw new Exception("Cannot write to file: " + df.getAbsolutePath() + " reason: " + e); } } else { System.out.println( String.format( "WARNING: ignoring already created document for topic %s docId %s", topicId, docId)); } } } }
public browse_jsp() { myUtil = new ewebeditor.server.util(); sFileSeparator = System.getProperty("file.separator"); }
/** * SplitterJavaSource writes the splitter Java file's contents to a string buffer for a given * condition, Ppt, and StatementReplacer. */ class SplitterJavaSource implements jtb.JavaParserConstants { /** The text contents of the splitter file, a java class. */ private StringBuffer fileText = new StringBuffer(); /** The name of the class from which this Ppt is from. */ private String className; /** The name of the class that is being written. */ private String fileName; /** * A data structure defined in an inner-class that contains information about all the variables to * be defined in fileText. */ private VariableManager[] vars; /** A StatementReplacer for the .spinfo from which this file is being created. */ private StatementReplacer statementReplacer; /** Java reserved words that are replaced by replaceReservedWords. */ private static final String[] reservedWords = new String[] {"return"}; private static final String lineSep = System.getProperty("line.separator"); /** * Creates a new instance of SplitterJavaSource. * * @param splitObj the SplitterObject for which this splitter java file is be written. * @param pptName the name of the Ppt to which splitObj belongs. * @param fileName the name of the file that should be written by the new SplitterJavaSource. * @param varInfos the varInfos for this the Ppt to which splitObj belongs. * @param statementReplacer a statementReplacer for the .spinfo file from which splitObj is being * created from. */ public SplitterJavaSource( SplitterObject splitObj, String pptName, String fileName, VarInfo[] varInfos, StatementReplacer statementReplacer) throws ParseException { className = getClassName(pptName); this.fileName = fileName; this.statementReplacer = statementReplacer; varInfos = filterNonVars(varInfos); String originalCondition = splitObj.condition(); String condition = replaceReservedWords(originalCondition); condition = this.statementReplacer.makeReplacements(condition); condition = convertVariableNames(condition, className, varInfos); vars = makeVariableManagerArray(varInfos, condition, className); // extra white space at the end of lines used only to increase readability. add("import daikon.*; "); add("import daikon.inv.*; "); add("import daikon.split.*; "); skipLine(); add("public final class " + fileName + " extends Splitter { "); skipLine(); add(" public String condition() { "); add(" return \"" + protectQuotations(originalCondition) + "\"; "); add(" } "); skipLine(); writeFields(); skipLine(); add(" static DummyInvariant dummyInvFactory;"); add(" DummyInvariant dummyInv;"); skipLine(); add(" public " + fileName + "() { } "); add(" public " + fileName + "(Ppt ppt) { "); writeConstructorBody(); add(" }"); skipLine(); add(" public Splitter instantiate(Ppt ppt) { "); add(" return new " + fileName + "(ppt); "); add(" } "); skipLine(); add(" public boolean valid() { "); writeValidBody(); add(" } "); skipLine(); add(" public boolean test(ValueTuple vt) { "); writeTestBody(); add(" return(" + NullReplacer.replaceNull(condition) + "); "); add(" } "); skipLine(); add(" public String repr() { "); writeReprBody(); add(" } "); skipLine(); add(" public void makeDummyInvariant(DummyInvariant inv) { "); add(" dummyInvFactory = inv; "); add(" } "); skipLine(); add(" public void instantiateDummy(PptTopLevel ppt) { "); add(" dummyInv = null; "); writeInstantiateDummyBody(); add(" } "); skipLine(); add(" public DummyInvariant getDummyInvariant() { "); add(" return dummyInv; "); add(" } "); skipLine(); add(" public int[] getIntArray(long[] longArray) { "); add(" int[] intArray = new int[longArray.length]; "); add(" for (int i = 0; i < intArray.length; i++) { "); add(" intArray[i] = (int) longArray[i]; "); add(" } "); add(" return intArray; "); add(" } "); skipLine(); add("} "); } /** Returns a StringBuffer with the file text for the java file written by this. */ public StringBuffer getFileText() { return fileText; } /** Writes the field declarations of the class to fileText. */ private void writeFields() { for (int i = 0; i < vars.length; i++) { add(" VarInfo " + vars[i].getFieldName() + "; // " + vars[i].getNormalName()); } } /** Writes the body of the of constructor which takes a Ppt in as an argument. */ private void writeConstructorBody() { for (int i = 0; i < vars.length; i++) { add( " " + vars[i].getFieldName() + " = ppt.find_var_by_name(\"" + vars[i].getNormalName() + "\");"); } } /** Writes the body of the valid method to fileText. */ private void writeValidBody() { if (vars.length > 0) { fileText.append(" return (" + vars[0].getFieldName() + " != null)"); for (int i = 1; i < vars.length; i++) { fileText.append(" && (" + vars[0].getFieldName() + " != null)"); } add(";"); } else { add(" /* no variables were found */"); add(" return false;"); } } /** Writes the body of the test method to fileText. */ private void writeTestBody() { add(" " + "/* writeTestBody: " + vars.length + " declarations */"); for (int i = 0; i < vars.length; i++) { String type = vars[i].getType(); String get_expr; if (type.equals("int_index")) { type = "int"; get_expr = "getIndexValue(vt)"; } else if (type.equals("boolean")) { get_expr = "getIntValue(vt) > 0"; } else if (type.equals("int")) { type = "long"; get_expr = "getIntValue(vt)"; } else if (type.equals("int[]")) { type = "long[]"; get_expr = "getIntArrayValue(vt)"; } else if (type.equals("double")) { get_expr = "getDoubleValue(vt)"; } else if (type.equals("double[]")) { get_expr = "getDoubleArrayValue(vt)"; } else if (type.equals("String") || type.equals("java.lang.String") || type.equals("char[]")) { type = "String"; get_expr = "getStringValue(vt)"; } else if (type.equals("String[]") || type.equals("java.lang.String[]")) { get_expr = "getStringArrayValue(vt)"; } else if (type.equals("index[]")) { type = "int[]"; get_expr = "getIntArrayValue(vt)"; } else { debugPrintln("Can't deal with this type " + type + " declared in Splitter File"); throw new Error("Can't deal with this type " + type + " declared in Splitter File"); } if (type.equals("int[]")) { add( " " + type + " " + vars[i].getCompilableName() + " = " + "getIntArray(" + vars[i].getFieldName() + "." + get_expr + ");"); } else { add( " " + type + " " + vars[i].getCompilableName() + " = " + vars[i].getFieldName() + "." + get_expr + ";"); } } } /** Writes the body of the repr method to fileText. */ private void writeReprBody() { add(" return " + "\"" + fileName + ": \""); for (int i = 0; i < vars.length; i++) { add( " + \"" + vars[i].getFieldName() + " = \" + " + vars[i].getFieldName() + ".repr() + \" \""); } add(" ;"); } /** Writes the body of the instantiateDummy method to fileText. */ private void writeInstantiateDummyBody() { if (vars.length >= 1 && vars.length <= 3) { for (int i = 0; i < vars.length; i++) { add( " VarInfo " + vars[i].getVarName() + " = ppt.find_var_by_name(\"" + vars[i].getNormalName() + "\");"); } fileText.append(" if ("); fileText.append(vars[0].getVarName() + " != null"); for (int i = 1; i < vars.length; i++) { fileText.append(" && " + vars[i].getVarName() + " != null"); } add(") {"); fileText.append(" dummyInv = dummyInvFactory.instantiate(ppt, new VarInfo[] {"); fileText.append(vars[0].getVarName()); for (int i = 1; i < vars.length; i++) { fileText.append(", " + vars[i].getVarName()); } add("});"); add(" }"); } } /** * Appends st to fileText and then ends that line with lineSep. * * @param st the string to added to fileText. */ private void add(String st) { fileText.append(st + lineSep); } /** Skips a line in fileText by adding a black line to fileText. */ private void skipLine() { fileText.append(lineSep); } /** * Replaces instances of Java reserved words that could not appear in a valid Java condition or * Java variable name that are being used as variable names in string. * * @param string the string in which the Java reserved words should be replaced. * @return string with the Java reserved words replaced with a substitute names. */ private static String replaceReservedWords(String string) { // cheap hack so that pattern never need to look for a key word at // the beginning or end of string. That way one may simplify the pattern // to looking for a reserved word that is not prefixed or suffix with a // letter or number. string = "(" + string + ")"; for (int i = 0; i < reservedWords.length; i++) { String reservedWord = reservedWords[i]; Pattern p = Pattern.compile("([\\W])(" + reservedWord + ")([\\W])"); Matcher m = p.matcher(string); while (m.find()) { string = m.replaceFirst(m.group(1) + "daikon" + reservedWord + m.group(3)); m = p.matcher(string); } } return string.substring(1, string.length() - 1); } /** * Returns a version of this condition in which the variable names are converted to the names that * will be used by the java class written to fileText. Instances of "this." are removed. Instances * of the package and class names prefixing variable names are removed and appended to the * variable name with a "_" separating the two parts. Instance of public field name suffixing a * variable name are removed and appended to the end of variable name with a "_" separating the * two parts. Instances of "orig(variableName)" are replaced by instances of "orig_variableName". * For example "orig(varName.publicField)" would yield "orig_varName_publicField". * * @param condition a string representation of a conditional statement. * @return a version of the conditional with the variable names converted. */ private static String convertVariableNames(String condition, String className, VarInfo[] varInfos) throws ParseException { // These methods keep converting between strings and jtb syntax trees // because the visitor cause the trees to become invalid. Therefore, // it is needed to re-parse the condition in a new jtb syntax tree each // time. (All the parsing is hidden in the static methods.) condition = ThisRemover.removeThisDot(condition); StringTokenizer classNameTokens = new StringTokenizer(className, "."); while (classNameTokens.hasMoreTokens()) { String nextToken = classNameTokens.nextToken(); condition = PrefixRemover.removePrefix(condition, nextToken); } condition = OrigFixer.fixOrig(condition); condition = PrefixFixer.fixPrefix(condition); String[] baseNames = getBaseNames(varInfos, className); condition = ArrayFixer.fixArrays(condition, baseNames, varInfos); return condition; } /** Eliminates all non-normal variables from varInfos. See isNormalVar() for details. */ private static VarInfo[] filterNonVars(VarInfo[] varInfos) { List<VarInfo> filteredList = new ArrayList<VarInfo>(); for (int i = 0; i < varInfos.length; i++) { if (isNormalVar(varInfos[i])) { filteredList.add(varInfos[i]); } else { // System.out.println("filterNonVars removed " + varInfos[i].name.name()); } } return filteredList.toArray(new VarInfo[0]); } /** * Determines if the variable represented by varInfo may appear in the splitting condition. * * @param varInfo the VarInfo for the variable that may be use in the condition. * @return true iff the variable represented by varInfo may appear in the splitting condition. */ private static boolean isNormalVar(VarInfo varInfo) { return ((!isTypeOfVar(varInfo)) && (!isSizeVar(varInfo)) && (!isThisVar(varInfo))); } /** * Determines if the variable represented by varInfo is a ".getClass()" variable. * * @param varInfo the VarInfo of the variable being tested. * @return true iff varInfo is a ".getClass()" variable. */ private static boolean isTypeOfVar(VarInfo varInfo) { return varInfo.has_typeof(); } /** * Determines if the variable represented by varInfo is a "size" variable. * * @param varInfo the VarInfo of the variable being tested. * @return true iff varInfo is a "size" variable. */ private static boolean isSizeVar(VarInfo varInfo) { return varInfo.is_size(); } /** Determines if the variable represented by varInfo is a "this" variable. */ private static boolean isThisVar(VarInfo varInfo) { return varInfo.isThis(); } /** * Protects quotations that appear in fileText by placing "\" in front of quotation marks. * * @return condition with a backslash placed in front of every quotation mark. */ private static String protectQuotations(String condition) { for (int i = 0; i < condition.length(); i++) { if (condition.charAt(i) == '"') { condition = condition.substring(0, i) + "\\" + condition.substring(i, condition.length()); i = i + 2; } } return condition; } /** Returns the name of the class from which pptName is from. */ private static String getClassName(String pptName) { int lastIndex = pptName.lastIndexOf('.'); if (lastIndex != -1) { return pptName.substring(0, lastIndex); } else { return pptName; } } /** Print out a message if the debugPptSplit variable is set to "true". */ private static void debugPrintln(String s) { Global.debugSplit.fine(s); } /** * Return str with the char at index removed. This method requires: 0 <= index < str.length * * @param str the String from which the char at index should be removed. * @param index the index of the char that should be removed from str. * @return str with the char at index removed. */ private static String removeCharAt(String str, int index) { return str.substring(0, index) + str.substring(index + 1); } /** * Returns str with chr inserted at index. This method requires: 0 <= index <= str.length * * @param str the String in which chr should be inserted. * @param chr the char that should be inserted into str. * @param index the index of the position where chr should be inserted in to str. * @return str with chr inserted at index */ private static String insertCharAt(String str, char chr, int index) { return str.substring(0, index) + chr + str.substring(index); } /** * Calculates the name of the variable represented by varInfo in a compilable form. Name are the * same as base names (see getBaseName) except that the names of arrays are suffixed with * "_identity" if it is a variable representing the array for equality tests or "_array" if it is * a variable representing the elements of the array. * * @param varInfo the VarInfo of the variable whose compilable name is desired. * @return the name of the variable represented by varInfo in a compilable form. */ private static String compilableName(VarInfo varInfo, String className) { String name = getBaseName(varInfo, className); if (varInfo.type.isArray()) { if (varInfo.file_rep_type == ProglangType.HASHCODE) { name += "_identity"; } else { name += "_array"; } } return name; } /** * Calculates the base name of a variable. The base name of a variable is the part of the variable * with prefixes "this." and className removed, and "orig()" replaced by "orig_". For example * orig(this.x) goes to orig_x. If className is "Class" then "Class.x" would yield "x" and * "someOtherClass.x" would yield "someOtherClass_x". Finally, Java Reserved words are replaced * with appropriate substitutes. * * @param varInfo the VarInfo for the variable whose base name is desired. * @return the base name of the variable represented by varInfo. */ private static String getBaseName(VarInfo varInfo, String className) { String name = varInfo.name(); name = replaceReservedWords(name); if (name.length() > 5 && name.substring(0, 5).equals("orig(") && name.endsWith(")")) { name = name.substring(5, name.length() - 1); name = fixPrefixes(name, className); name = "orig_" + name; } else { name = fixPrefixes(name, className); } name = name.replace('.', '_'); name = remove(name, ']'); name = remove(name, '['); return name; } /** * Returns an array of the base names of the variable in varInfos. The returned array is in the * same order as varInfos. */ private static String[] getBaseNames(VarInfo[] varInfos, String className) { String[] baseNames = new String[varInfos.length]; for (int i = 0; i < varInfos.length; i++) { baseNames[i] = getBaseName(varInfos[i], className); } return baseNames; } /** * Returns name with "this." or any part of className prefixing it removed. For example if * className is "package1.package2.Class" then "package1.package2.Class.x", "package2.Class.x", * and "Class.x" would all yield "x". However, "package3.package2.package1.Class.x" would yield no * change. */ private static String fixPrefixes(String name, String className) { if (name.startsWith("this.")) { return name.substring("this.".length()); } int dotIndex = 0; while (dotIndex != -1) { if (name.startsWith(className.substring(dotIndex) + ".")) { name = name.substring(className.substring(dotIndex).length() + 1); break; } dotIndex = className.indexOf('.', dotIndex + 1); } return name; } /** * Returns st with all instances of ch removed. * * @param st the string from which ch should be removed. * @param ch the character that should be removed from st. * @return st with all instances of ch removed. */ private static String remove(String st, char ch) { int index = st.indexOf(ch); while (index != -1) { st = st.substring(0, index) + st.substring(index + 1, st.length()); index = st.indexOf(ch); } return st; } /** * Returns the name of the variable represented by varInfo as it would appear in the field * declaration of a java splitter file. * * @param varInfo the VarInfo representing the variable for which the field name is desired. * @return the name of the variable represented by varInfo as it would appear in the field * declaration of a java splitter file. */ private static String fieldName(VarInfo varInfo, String className) throws ParseException { return compilableName(varInfo, className) + "_varinfo"; } /** * Returns the name of the variable used to hold this varInfo in a java splitter file. * * @param varInfo the VarInfo for which the name of the variable is desired. * @return the name of the variable used to hold this varInfo in a java splitter file. */ private static String varName(VarInfo varInfo, String className) throws ParseException { return compilableName(varInfo, className) + "_vi"; } /** * Returns the type of the variable represented by varInfo. * * @param varInfo the VarInfo for the variable whose type is desired. * @return the type of the variable represented by varInfo. */ private static String getVarType(VarInfo varInfo) { if (varInfo.file_rep_type == ProglangType.HASHCODE) { return "int"; } else if ((varInfo.type == ProglangType.CHAR_ARRAY) || (varInfo.type == ProglangType.BOOLEAN) || (varInfo.type == ProglangType.DOUBLE) || (varInfo.type == ProglangType.DOUBLE_ARRAY)) { return varInfo.type.format(); } else { return varInfo.rep_type.format(); } } /** VariableManager is a data structure for containing information about a variable. */ private static class VariableManager { /** VarInfo for the variable. */ private VarInfo varInfo; /** Name of variable as how it appears in the original file. */ private String name; /** Name of variable in a compilable format. */ private String compilableName; /** Name of the variable as it appears in the fields of the splitter file. */ private String fieldName; /** Name of the variable that holds the varInfo in the splitter file. */ private String varName; /** The type of the variable. */ private String type; private VariableManager(VarInfo varInfo, String condition, String className) throws ParseException { this.varInfo = varInfo; name = varInfo.name(); compilableName = compilableName(varInfo, className); fieldName = fieldName(varInfo, className); varName = varName(varInfo, className); type = makeIndexIfNeeded(getVarType(varInfo), compilableName, varInfo, condition); } /** Returns the VarInfo of the variable. */ private VarInfo getVarInfo() { return varInfo; } /** Returns the name of the variable */ private String getNormalName() { return name; } /** * Returns the compilable name of the variable. Compilable names are formed as follows: * Instances of "this.", "className." and "packageName.ClassName." are removed, instances of * "orig(variableName)" are replace by instance of "orig_variableName". The names of arrays are * suffix with "_identity" if it is a variable representing the array for equality tests or * "_array" if it is a variable representing the elements of the array. * * @return the compilable name of the variable */ private String getCompilableName() { return compilableName; } /** * Returns the field name of the variable. The field name is the name of the variable as it * would appear in the field declaration of a java splitter file. * * @return the field name of the variable. */ private String getFieldName() { return fieldName; } /** * Returns the VarInfo name of the variable. The VarInfo name of a variable is the name of the * variable used to hold this varInfo in a java splitter file. * * @return the VarInfo name of the variable. */ private String getVarName() { return varName; } /** Returns the type of the variable. */ private String getType() { return type; } } /** * Creates a new instance of VariableManager. * * @param varInfos the varInfos for the variables to be managed. * @param condition the condition in which the variables are used. */ private static VariableManager[] makeVariableManagerArray( VarInfo[] varInfos, String condition, String className) throws ParseException { List<VariableManager> variableManagerList = new ArrayList<VariableManager>(); List<String> classVars = findPossibleClassVariables(condition); for (int i = 0; i < varInfos.length; i++) { VarInfo varInfo = varInfos[i]; try { String compilableName = compilableName(varInfo, className); // System.out.println("varInfo " + varInfo.name.name() + ", compilableName=" + // compilableName + ", isNeeded=" + isNeeded(compilableName, classVars)); if (isNeeded(compilableName, classVars)) { variableManagerList.add(new VariableManager(varInfo, condition, className)); } } catch (ParseException e) { System.out.println("ParseException: " + e.toString()); } } return variableManagerList.toArray(new VariableManager[0]); } /** Returns true if the variable represented by varInfo is used in this splitting condition. */ private static boolean isNeeded(String name, List<String> vars) { return vars.contains(name); } /** * requires: condition is a string representation of a conditional * * @return a list of all possible variable variable names in condition. arrays appear with "[]" at * the end if their elements or accessed in the condition. */ private static List<String> findPossibleClassVariables(String condition) throws ParseException { NodeToken[] tokens = TokenExtractor.extractTokens(condition); // System.out.println("TokenExtractor.extractTokens(" + condition + ") ==> " + // ArraysMDE.toString(tokens)); List<String> variables = new ArrayList<String>(); if (tokens.length >= 1) { if (tokens[0].kind == IDENTIFIER && (tokens.length <= 1 || tokens[1].kind != LPAREN)) { variables.add(tokens[0].tokenImage); } } if (tokens.length >= 2) { if (tokens[1].kind == IDENTIFIER && (tokens.length <= 2 || tokens[2].kind != LPAREN) && (!variables.contains(tokens[1].tokenImage))) { variables.add(tokens[1].tokenImage); } } for (int i = 2; i < tokens.length - 1; i++) { NodeToken token = tokens[i]; if (token.kind == IDENTIFIER && tokens[i - 1].kind != DOT && tokens[i + 1].kind != LPAREN && (!variables.contains(token.tokenImage))) { variables.add(token.tokenImage); } } if (tokens.length >= 3) { int lastIndex = tokens.length - 1; if (tokens[lastIndex].kind == IDENTIFIER && tokens[lastIndex - 1].kind != DOT && (!variables.contains(tokens[lastIndex].tokenImage))) { variables.add(tokens[lastIndex].tokenImage); } } // System.out.println("findPossibleClassVariables(" + condition + ") ==> " + // variables.toString()); return variables; } /** * Returns type converted to index type if needed. A index type variable in java splitter file has * type "int" or "int[]" instead of "long" or "long[]". This is needed if the variable or the an * element of the variable is used as an index to an array. This method converts the type of the * variable to "int_index" or "index[]" if it is used as an index to an array or an element of it * is used as an index to an array. * * @param type the original type of the variable. * @param name the name of the variable. * @param varInfo the VarInfo of the variable. * @param condition the condition in which the variable occurs. * @return the type converted to index type if needed. */ private static String makeIndexIfNeeded( String type, String name, VarInfo varInfo, String condition) throws ParseException { if ((type.equals("int") || varInfo.type.isArray()) && varInfo.file_rep_type != ProglangType.HASHCODE) { int LPAREN = 74; int RPAREN = 75; int LBRACKET = 78; int RBRACKET = 79; Stack<Boolean> inArrayIndex = new Stack<Boolean>(); inArrayIndex.push(Boolean.FALSE); NodeToken[] tokens = TokenExtractor.extractTokens(condition); for (int i = 0; i < tokens.length; i++) { if (tokens[i].kind == LBRACKET) { inArrayIndex.push(Boolean.TRUE); } else if (tokens[i].kind == RBRACKET) { inArrayIndex.pop(); } else if (tokens[i].kind == LPAREN) { inArrayIndex.push(Boolean.FALSE); } else if (tokens[i].kind == RPAREN) { inArrayIndex.pop(); } else if (inArrayIndex.peek().booleanValue() && tokens[i].tokenImage.equals(name)) { if (type.equals("int") || type.equals("int_index")) { // Note the type can only equal "int_index" if the variable // was already visited by this if statement since it appears // more than once in the condition. type = "int_index"; } else { type = "index[]"; } } } return type; } return type; } }