text
stringlengths
14
410k
label
int32
0
9
public static void deleteQuizCreatedHistory(Quiz quiz) { try { String statement = new String("DELETE FROM " + DBTable + " WHERE qid=?"); PreparedStatement stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, quiz.quizID); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
1
private void scan() { if (currentBlock >= 0) { return; } if (maxDistance != 0 && currentDistance > maxDistanceInt) { end = true; return; } if (end) { return; } currentDistance++; secondError += secondStep; thirdError += thirdStep; if (secondError > 0 && thirdError > 0) { blockQueue[2] = blockQueue[0].getRelative(mainFace); if (((long) secondStep) * ((long) thirdError) < ((long) thirdStep) * ((long) secondError)) { blockQueue[1] = blockQueue[2].getRelative(secondFace); blockQueue[0] = blockQueue[1].getRelative(thirdFace); } else { blockQueue[1] = blockQueue[2].getRelative(thirdFace); blockQueue[0] = blockQueue[1].getRelative(secondFace); } thirdError -= gridSize; secondError -= gridSize; currentBlock = 2; return; } else if (secondError > 0) { blockQueue[1] = blockQueue[0].getRelative(mainFace); blockQueue[0] = blockQueue[1].getRelative(secondFace); secondError -= gridSize; currentBlock = 1; return; } else if (thirdError > 0) { blockQueue[1] = blockQueue[0].getRelative(mainFace); blockQueue[0] = blockQueue[1].getRelative(thirdFace); thirdError -= gridSize; currentBlock = 1; return; } else { blockQueue[0] = blockQueue[0].getRelative(mainFace); currentBlock = 0; return; } }
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Usuario other = (Usuario) obj; if (login == null) { if (other.login != null) return false; } else if (!login.equals(other.login)) return false; if (senha == null) { if (other.senha != null) return false; } else if (!senha.equals(other.senha)) return false; return true; }
9
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) { return; } char[] upper = str.toCharArray(); for (int i = 0; i < upper.length; i++) { upper[i] = Character.toUpperCase(upper[i]); } super.insertString(offs, new String(upper), a); }
2
public void changeStage(String ref, float x, float y) { //Ensemble.get().setFading(backgroundTrack, 3); if(!map.isTown()) { Save.get().saveTempField(this); } scene = ref; loadStage(ref); player.setX(x); player.setY(y); player.updateBox(); if(map.isTown()) Save.get().clearField(); //addScenery(); Theater.get().getScreen().setFocus(player); Theater.get().getScreen().centerOn(); }
2
private boolean fileIsAudiofileName(String fileName) { if(fileName.endsWith(".MP3") || fileName.endsWith(".mp3") || fileName.endsWith(".wav") || fileName.endsWith(".WAV")){ System.out.println("Sound found " + fileName); return true; } return false; }
4
public void login(ActionEvent actionEvent) { if (("test".equalsIgnoreCase(getUsername()) && "test".equals(getPassword())) || ("aslan".equalsIgnoreCase(getUsername()) && "aslan".equals(getPassword())) || ("fat".equalsIgnoreCase(getUsername()) && "fat".equals(getPassword())) ) { try { FacesContext.getCurrentInstance().getExternalContext().redirect("home.xhtml?username=" +getUsername()); } catch (IOException e) { e.printStackTrace(); } } else { FacesContext context = FacesContext.getCurrentInstance(); context.addMessage("username", new FacesMessage( "Invalid UserName and Password")); } }
7
public void start() { String line = null; StringBuffer sb = new StringBuffer(); try { while ((line = br.readLine()) != null) { if (cb != null) cb.onLine(line); sb.append(line); } } catch (IOException e) { } }
3
private DefaultMutableTreeNode findDescendantNode(DefaultMutableTreeNode node, Region region) { // GO THROUGH ALL OF node's CHILDREN for (int i = 0; i < node.getChildCount(); i++) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)node.getChildAt(i); Region testRegion = (Region)childNode.getUserObject(); if (testRegion.getId().equals(region.getId())) { return childNode; } else if (!childNode.isLeaf()) { // RECURSIVE CALL HERE DefaultMutableTreeNode foundNode = findDescendantNode(childNode, region); if (foundNode != null) { return foundNode; } } } return null; }
4
public Holdable removeStackedItem(Character itemID, int count) throws InvalidKeyException { Holdable item; Holdable returnItem; if(weapons.containsKey(itemID)) { item = weapons.get(itemID); // If the item is stackable then just reduce the stack count returnItem = item.reduceStack(count); // Only if the stack has hit 0 do we actually remove the item if (item.stackSize() == 0) { weapons.remove(itemID); size--; } } else if (armours.containsKey(itemID)) { item = armours.get(itemID); returnItem = item.reduceStack(count); if (item.stackSize() == 0) { armours.remove(itemID); size--; } } else if (foods.containsKey(itemID)) { item = foods.get(itemID); returnItem = item.reduceStack(count); if (item.stackSize() == 0) { foods.remove(itemID); size--; } } else if (misc.containsKey(itemID)) { item = misc.get(itemID); returnItem = item.reduceStack(count); if (item.stackSize() == 0) { misc.remove(itemID); size--; } } else { throw new InvalidKeyException(); } return returnItem; }
8
public void subsample(int numberOfPoints, boolean averageY) { int xx[] = new int[numberOfPoints]; int count[] = new int[numberOfPoints]; int yy[] = new int[numberOfPoints]; for( int i = 0; i < x.length; i++ ) { int j = i * numberOfPoints / x.length; xx[j] += x[i]; yy[j] += y[i]; count[j]++; } for( int j = 0; j < xx.length; j++ ) { if( count[j] > 1 ) { xx[j] /= count[j]; if( averageY ) yy[j] /= count[j]; } } x = xx; y = yy; }
4
private boolean writePlane(int[] src, byte[] tmp, int width, int height) { try { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { tmp[x] = (byte)src[y * width + x]; } dos.write(tmp); } return true; } catch (Exception e) { e.printStackTrace(); return false; } }
3
@Override public void init (AbstractQueue<QueueElement> docq, Properties props) { this.docq = docq; this.props = props; outputProperties.setProperty(OutputKeys.INDENT, "yes"); outputProperties.setProperty(OutputKeys.METHOD, "xml"); outputProperties.setProperty(OutputKeys.STANDALONE, "no"); outputProperties.setProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "caption copyright person title country kick content h1 h2 video abstract byline hyperlink"); outputProperties.setProperty("{http://xml.apache.org/xsl}indent-amount", "4"); try { // Prepare the URL. String strUrl = null; String strOutputOption = null; if (props.containsKey("outputOption")) { strOutputOption = props.getProperty("outputOption").trim(); } if (strOutputOption != null && !strOutputOption.isEmpty()) { strUrl = props.getProperty("destinationURL" + strOutputOption); // specific dest URL } else { strUrl = props.getProperty("destinationURL"); // default dest URL } if (strUrl == null) { throw new RuntimeException("Required property destinationURL not found."); } logger.fine("Destination URL=" + strUrl); url = new URL(strUrl); } catch (Exception e) { throw new RuntimeException(e); } }
5
public EatAction(Being eater, Being victim) { this.victim = victim; this.eater = eater; }
0
public static void startupHttpServer() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/HTTP", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupHttpServer.helpStartupHttpServer1(); } if (Stella.currentStartupTimePhaseP(4)) { Http.$HTTP_RESPONSE_CODES$ = Cons.list$(Cons.cons(Cons.list$(Cons.cons(Http.KWD_OK, Cons.cons(IntegerWrapper.wrapInteger(200), Cons.cons(StringWrapper.wrapString("OK"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_REDIRECT, Cons.cons(IntegerWrapper.wrapInteger(301), Cons.cons(StringWrapper.wrapString("Moved Permanently"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_FORBIDDEN, Cons.cons(IntegerWrapper.wrapInteger(403), Cons.cons(StringWrapper.wrapString("Forbidden"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_NOT_FOUND, Cons.cons(IntegerWrapper.wrapInteger(404), Cons.cons(StringWrapper.wrapString("Not Found"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_BAD_REQUEST, Cons.cons(IntegerWrapper.wrapInteger(400), Cons.cons(StringWrapper.wrapString("Bad Request"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_INTERNAL_ERROR, Cons.cons(IntegerWrapper.wrapInteger(500), Cons.cons(StringWrapper.wrapString("Internal Server Error"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_NOT_IMPLEMENTED, Cons.cons(IntegerWrapper.wrapInteger(501), Cons.cons(StringWrapper.wrapString("Not Implemented"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Stella.NIL, Stella.NIL))))))))); Http.$HTTP_MIME_TYPES$ = Cons.list$(Cons.cons(Cons.list$(Cons.cons(Http.KWD_PLAIN_TEXT, Cons.cons(StringWrapper.wrapString("text/plain"), Cons.cons(StringWrapper.wrapString("txt"), Cons.cons(StringWrapper.wrapString("text"), Cons.cons(StringWrapper.wrapString("asc"), Cons.cons(Stella.NIL, Stella.NIL))))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_HTML, Cons.cons(StringWrapper.wrapString("text/html"), Cons.cons(StringWrapper.wrapString("htm"), Cons.cons(StringWrapper.wrapString("html"), Cons.cons(Stella.NIL, Stella.NIL)))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_XML, Cons.cons(StringWrapper.wrapString("text/xml"), Cons.cons(StringWrapper.wrapString("xml"), Cons.cons(StringWrapper.wrapString("rdf"), Cons.cons(StringWrapper.wrapString("owl"), Cons.cons(Stella.NIL, Stella.NIL))))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_BINARY, Cons.cons(StringWrapper.wrapString("application/octet-stream"), Cons.cons(StringWrapper.wrapString("zip"), Cons.cons(StringWrapper.wrapString("exe"), Cons.cons(StringWrapper.wrapString("class"), Cons.cons(Stella.NIL, Stella.NIL))))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_IMAGE_GIF, Cons.cons(StringWrapper.wrapString("image/gif"), Cons.cons(StringWrapper.wrapString("gif"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_IMAGE_JPG, Cons.cons(StringWrapper.wrapString("image/jpeg"), Cons.cons(StringWrapper.wrapString("jpg"), Cons.cons(StringWrapper.wrapString("jpeg"), Cons.cons(Stella.NIL, Stella.NIL)))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_IMAGE_PNG, Cons.cons(StringWrapper.wrapString("image/png"), Cons.cons(StringWrapper.wrapString("png"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_AUDIO_MPEG, Cons.cons(StringWrapper.wrapString("audio/mpeg"), Cons.cons(StringWrapper.wrapString("mp3"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_PDF, Cons.cons(StringWrapper.wrapString("application/pdf"), Cons.cons(StringWrapper.wrapString("pdf"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Cons.list$(Cons.cons(Http.KWD_MSWORD, Cons.cons(StringWrapper.wrapString("application/msword"), Cons.cons(StringWrapper.wrapString("doc"), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(Stella.NIL, Stella.NIL)))))))))))); Http.$HTTP_DOCUMENT_ROOT$ = ((Http.$HTTP_DOCUMENT_ROOT$ != null) ? Http.$HTTP_DOCUMENT_ROOT$ : ((Stella.probeFileP("PL:htdocs;powerloom.html") ? Stella.translateLogicalPathname("PL:htdocs;") : Stella.translateLogicalPathname("PL:")))); Http.$HTTP_HANDLER_REGISTRY$ = KeyValueMap.newKeyValueMap(); Http.$HTTP_SERVER_COPYRIGHT_TRAILER$ = Stella.$STELLA_VERSION_STRING$ + " HTTP Server" + "<BR>" + "Copyright 1996-" + Native.integerToString(((long)(CalendarDate.makeCurrentDateTime().getCalendarDate(Stella.getLocalTimeZone(), new Object[3])))) + " University of Southern California Information Sciences Institute"; } if (Stella.currentStartupTimePhaseP(5)) { Stella.defineClassFromStringifiedSource("HTTP-SERVER", "(DEFCLASS HTTP-SERVER (STANDARD-OBJECT) :DOCUMENTATION \"Abstract class that will be implemented by specific server implementations\nand instantiated with a single instance used to dispatch all API methods.\" :ABSTRACT? TRUE :PUBLIC? TRUE)"); Stella.defineClassFromStringifiedSource("HTTP-EXCHANGE", "(DEFCLASS HTTP-EXCHANGE (STANDARD-OBJECT) :DOCUMENTATION \"Abstract class that represents exchange objects that encapsulate all necessary\nstate needed by a http handler function to understand the request and generate the\nappropriate response. This is mirrored somewhat after Sun's basic HTTP server\nimplementation in com.sun.net.httpserver.\" :ABSTRACT? TRUE :PUBLIC? TRUE)"); } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { _StartupHttpServer.helpStartupHttpServer2(); } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("HTTP"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTTP-SERVER-IMPLEMENTATION* HTTP-SERVER NULL :DOCUMENTATION \"Server instance used for method dispatch - not to be confused\nwith an actual native server object.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DEFAULT-HTTP-SERVER-PORT* INTEGER 9090)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTTP-RESPONSE-CODES* (CONS OF CONS) (BQUOTE ((:OK 200 \"OK\") (:REDIRECT 301 \"Moved Permanently\") (:FORBIDDEN 403 \"Forbidden\") (:NOT-FOUND 404 \"Not Found\") (:BAD-REQUEST 400 \"Bad Request\") (:INTERNAL-ERROR 500 \"Internal Server Error\") (:NOT-IMPLEMENTED 501 \"Not Implemented\"))))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTTP-MIME-TYPES* (CONS OF CONS) (BQUOTE ((:PLAIN-TEXT \"text/plain\" \"txt\" \"text\" \"asc\") (:HTML \"text/html\" \"htm\" \"html\") (:XML \"text/xml\" \"xml\" \"rdf\" \"owl\") (:BINARY \"application/octet-stream\" \"zip\" \"exe\" \"class\") (:IMAGE-GIF \"image/gif\" \"gif\") (:IMAGE-JPG \"image/jpeg\" \"jpg\" \"jpeg\") (:IMAGE-PNG \"image/png\" \"png\") (:AUDIO-MPEG \"audio/mpeg\" \"mp3\") (:PDF \"application/pdf\" \"pdf\") (:MSWORD \"application/msword\" \"doc\"))))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTTP-DOCUMENT-ROOT* STRING (FIRST-DEFINED *HTTP-DOCUMENT-ROOT* (CHOOSE (PROBE-FILE? \"PL:htdocs;powerloom.html\") (TRANSLATE-LOGICAL-PATHNAME \"PL:htdocs;\") (TRANSLATE-LOGICAL-PATHNAME \"PL:\"))))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTTP-HANDLER-REGISTRY* (KEY-VALUE-MAP OF STRING-WRAPPER PROPERTY-LIST) (NEW KEY-VALUE-MAP))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *HTTP-SERVER-COPYRIGHT-TRAILER* STRING (CONCATENATE *STELLA-VERSION-STRING* \" HTTP Server\" \"<BR>\" \"Copyright 1996-\" (INTEGER-TO-STRING (GET-CALENDAR-DATE (MAKE-CURRENT-DATE-TIME) (GET-LOCAL-TIME-ZONE))) \" University of Southern California Information Sciences Institute\"))"); Http.publishDirectory("/ploom/", Http.getHttpDocumentRoot(), Cons.cons(Http.KWD_DOCUMENTATION, Cons.cons(StringWrapper.wrapString("Top-level htdocs directory."), Stella.NIL))); Http.publishHandler("/ploom/load-system", Native.find_java_method("edu.isi.webtools.http.HttpExchange", "loadSystemHandler", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), Cons.cons(Http.KWD_CONTENT_TYPE, Cons.cons(StringWrapper.wrapString(Http.getHttpMimeType(Http.KWD_HTML, null)), Cons.cons(Http.KWD_DOCUMENTATION, Cons.cons(StringWrapper.wrapString("Triggers a load-system operation at the server for the argument system."), Stella.NIL))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TEST-HTTP-API-HANDLER-LAST-XCHG* HTTP-EXCHANGE NULL)"); Http.publishHandler("/ploom/test-http-api", Native.find_java_method("edu.isi.webtools.http.HttpExchange", "testHttpApiHandler", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.http.HttpExchange")}), Cons.cons(Http.KWD_CONTENT_TYPE, Cons.cons(StringWrapper.wrapString(Http.getHttpMimeType(Http.KWD_HTML, null)), Cons.cons(Http.KWD_DOCUMENTATION, Cons.cons(StringWrapper.wrapString("Useful for comparing different HTTP API implementations."), Stella.NIL))))); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
9
public boolean canJump(int[] A) { if (A.length == 1) return true; if (A[0] >= (A.length - 1)) return true; int maxlength = A[0]; for (int i = 0; i < A.length - 1; i++) { if (maxlength >= i && (i + A[i]) >= A.length - 1) return true; if (maxlength <= i && A[i] == 0) return false; if ((i + A[i]) > maxlength) maxlength = i + A[i]; } return false; }
8
public void buildTreePane() { if (tree != null && treePane != null) { rebuildTreeList(); return; } try { getTreeList(); createTree(); treeScroll = new JScrollPane(tree); treePane = new JInternalFrame("Children", false, false, false, false); treePane.setVisible(true); treePane.setSize(225, viewport.getHeight()); treePane.setLocation(viewport.getWidth(), 0); treePane.add(treeScroll); desktop.add(treePane); } catch (Exception e) { e.printStackTrace(); } }
3
@Override public void delete(Joueur obj) { PreparedStatement pst = null; try { pst = this.connect().prepareStatement("DELETE FROM Joueur where id=?;"); pst.setInt(1, obj.getIdJoueur()); pst.executeUpdate(); System.out.println("suppression effectuer"); } catch (SQLException ex) { Logger.getLogger(JoueurDao.class.getName()).log(Level.SEVERE, "suppression echoué", ex); }finally{ try { if(pst != null) pst.close(); } catch (SQLException ex) { Logger.getLogger(JoueurDao.class.getName()).log(Level.SEVERE, "liberation preparedstatement echoué", ex); } } }
3
public static void main(final String[] args) throws Exception { int i = 0; int flags = ClassReader.SKIP_DEBUG; boolean ok = true; if (args.length < 1 || args.length > 2) { ok = false; } if (ok && "-debug".equals(args[0])) { i = 1; flags = 0; if (args.length != 2) { ok = false; } } if (!ok) { System.err .println("Prints a disassembled view of the given class."); System.err.println("Usage: TraceClassVisitor [-debug] " + "<fully qualified class name or class file name>"); return; } ClassReader cr; if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1 || args[i].indexOf('/') > -1) { cr = new ClassReader(new FileInputStream(args[i])); } else { cr = new ClassReader(args[i]); } cr.accept(new TraceClassVisitor(new PrintWriter(System.out)), getDefaultAttributes(), flags); }
9
@SuppressWarnings("unchecked") List<Operation> getFeedbackOperationVerify(String coderId, String guesserId, String feedback, Map<String, Object> lastState) { List<Operation> guessMove = new ArrayList<Operation>(); guessMove.add(new SetTurn(coderId)); guessMove.add(new Set(CURRENTMOVE,VERIFY)); List<String> feedbackHistory = new ArrayList<String>(); List<String> lastFeedbackHistory = (List<String>)(lastState.get(FEEDBACKHISTORY)); for (Iterator<String> it = lastFeedbackHistory.iterator(); it.hasNext();){ feedbackHistory.add(it.next()); } feedbackHistory.add(feedback); guessMove.add(new Set(FEEDBACKHISTORY,feedbackHistory)); //SetVisibleToAll guessMove.add(new SetVisibility(CODE)); return guessMove; }
1
public SudokuBoard getBoardSize(String sizeParameter) { if (sizeParameter.equals(Arguments.SIZE_4x4)) {return new SudokuBoard(SudokuBoard.SMALL); } if (sizeParameter.equals(Arguments.SIZE_9x9)) {return new SudokuBoard(SudokuBoard.REGULAR); } if (sizeParameter.equals(Arguments.SIZE_16x16)) {return new SudokuBoard(SudokuBoard.LARGE); } if (sizeParameter.equals(Arguments.SIZE_25x25)) {return new SudokuBoard(SudokuBoard.EXTRA_LARGE); } System.out.println(sizeParameter + " is an invalid option. Setting default size of 9x9"); return new SudokuBoard(SudokuBoard.REGULAR); }
4
public List<String> findItinerary(String[][] tickets) { if(tickets==null || tickets.length==0) return new ArrayList<String>(); Map<String,List<String>> reachablePoints=new HashMap<String, List<String>>(); Map<String,Integer> reachableCnt=new HashMap<String, Integer>(); for(int i=0;i<tickets.length;++i){ List<String> list=reachablePoints.get(tickets[i][0]); if(list==null) list=new ArrayList<String>(); list.add(tickets[i][1]); reachablePoints.put(tickets[i][0],list); } for(String root: reachablePoints.keySet()){ reachableCnt.put(root,getReachableCnt(root,reachablePoints)); } System.out.println(reachableCnt); return null; }
5
protected void installListeners() { super.installListeners(); if (AbstractLookAndFeel.getTheme().doShowFocusFrame()) { focusListener = new FocusListener() { public void focusGained(FocusEvent e) { if (getComponent() != null) { orgBorder = getComponent().getBorder(); LookAndFeel laf = UIManager.getLookAndFeel(); if (laf instanceof AbstractLookAndFeel && orgBorder instanceof UIResource) { Border focusBorder = ((AbstractLookAndFeel)laf).getBorderFactory().getFocusFrameBorder(); getComponent().setBorder(focusBorder); } getComponent().invalidate(); getComponent().repaint(); } } public void focusLost(FocusEvent e) { if (getComponent() != null) { if (orgBorder instanceof UIResource) { getComponent().setBorder(orgBorder); } getComponent().invalidate(); getComponent().repaint(); } } }; getComponent().addFocusListener(focusListener); } }
6
public void Start() { if(m_isRunning) return; Run(); }
1
public void addField(Column c) { // Check if the column pk is already exist if(c.getName().equals(this.getNamePK())){ int i=0; while(!this.setNamePK(this.getNamePK() + String.valueOf(i))){ i++; } } // Check if any name is repeated List<Column> fields = this.getFields(); for(Column col: fields){ int i = 0; while(col.getName().equals(c.getName())){ c.setName(col.getName() + String.valueOf(i)); addField(c); i++; return; } } fields.add(c); }
4
public ConsoleData getConsoleData() { ConsoleData cd = (ConsoleData)extra.get(ConsoleData.signature); if (cd == null) { cd = new ConsoleData(); extra.put(ConsoleData.signature, cd); } return cd; }
1
public void ImprimirImp(){ NodosListaProceso aux = PrimerNodo; System.out.println("Nombre de laimpresora\n__\t__________________\n"); while (aux!=null) { System.out.println(aux.nombreProceso+" "); aux = aux.siguiente; } }
1
private static void compilerTest(File file) throws Exception { // Compile to .java try { JavaCompiler.compile(file, new PrintWriter(new BufferedWriter(new FileWriter("temp/Main.java")))); } catch (Exception ex) { System.err.println("Failed to compile to Java: " + file.getName()); ex.printStackTrace(System.err); return; } // Compile to .class String s; BufferedReader stdInput; Process compiler = new ProcessBuilder("javac", "-cp", "temp", "temp/Main.java").redirectErrorStream(true).start(); stdInput = new BufferedReader(new InputStreamReader(compiler.getInputStream())); s = null; boolean compileFailed = false; StringBuilder compileMessages = new StringBuilder(); while ((s = stdInput.readLine()) != null) { compileMessages.append(s + "\n"); if (s.startsWith("Note: ")) { continue; } else { compileFailed = true; } } compiler.waitFor(); if (compileFailed) { System.err.println("javac failed for " + file.getName()); System.err.println(compileMessages); return; } // Execute the .class Process executor = new ProcessBuilder("java", "-cp", "temp;temp", "Main").redirectErrorStream(true).start(); stdInput = new BufferedReader(new InputStreamReader(executor.getInputStream())); s = null; StringBuilder compiledOutputStrBuilder = new StringBuilder(); while ((s = stdInput.readLine()) != null) { compiledOutputStrBuilder.append(s + "\n"); } executor.waitFor(); // Interpret the original script boolean hadError = false; StringBuilder interpretedOutputStrBuilder = null; try { interpretedOutputStrBuilder = interpreterExecute(file); } catch (AmbroscumError ex) { // NOTE: Not sure if this is actually necessary hadError = true; } if (interpretedOutputStrBuilder == null) { // Something went horribly wrong System.err.println("Something bad happened when interpreting " + file.getName()); return; } // Compare the two results Scanner compiledOutputScanner = new Scanner(fixNewlines(compiledOutputStrBuilder.toString())); Scanner interpretedOutputScanner = new Scanner(fixNewlines(interpretedOutputStrBuilder.toString())); Object[] result = compare(compiledOutputScanner, interpretedOutputScanner, hadError); // Output the comparison boolean correct = (boolean) result[0]; String testOutputStr = (String) result[1]; String correctOutputStr = (String) result[2]; if (correct) { System.err.println("Tests passed for " + file.getName()); } else { System.err.println("Incorrect output for " + file.getName()); System.err.println("-----------"); System.err.println(testOutputStr); System.err.println("-----------"); System.err.println(correctOutputStr); } }
8
public int getGreen(){ return _green; }
0
public static void transform(Op opNew) { List<Op> redo = new ArrayList<Op>(); StateVector vecNew = opNew.getStateVec(); for (int i = hBuffer.size() - 1; i >= 0; i--) { Op op = hBuffer.get(i); StateVector vecTmp = op.getStateVec(); if (!isTotalOrdering(vecTmp, vecNew)) { redo.add(op); // undo the operations Op inverse = op.inverse(); apply(inverse); } else { break; } } int m = hBuffer.size() - 1 - redo.size(); // remove the last $count operations Op eopNew = GOT(opNew); List<Op> eolPrime = new ArrayList<Op>(); eolPrime.add(eopNew); if (!redo.isEmpty()) { eolPrime.add(IT(redo.get(0), eopNew)); for (int i = 1; i < redo.size(); i++) { List<Op> his = new ArrayList<Op>(hBuffer.subList(m + 1, m + i)); Collections.reverse(his); Op opTmp = LET(redo.get(i), his); eolPrime.add(LIT(opTmp, eolPrime)); } for (int i = 0; i < redo.size(); i++) hBuffer.remove(hBuffer.size() - 1); } // apply to the doc for (Op tmp : eolPrime) apply(tmp); // redo eol Prime hBuffer.addAll(eolPrime); }
6
@Override public void keyPressed( KeyEvent e ) { for( KeyListener listener : listeners( KeyListener.class )){ listener.keyPressed( e ); } }
1
public Image arithmetic(Image im1, Image im2, int width, int height, int op, boolean r, boolean g, boolean b, boolean clip) { /* im1 = source image 1. im2 = source image 2. width = width of images (they are the same size) height = height of images op = operation. See top of class for definitions. NOTE: In subtraction, the result is im1 - im2. in Division, the result is im1/im2. r, g, b = affected channels clip = X < 0 X > 255 ------------------------- true X = 0 X = 255 false X = 256 +X X = X -256 */ int pix1[] = JIPTUtilities.getPixelArray(im1); int pix2[] = JIPTUtilities.getPixelArray(im2); // Get the sizes. Size1 and Size2 SHOULD BE the same, but this will catch Array exceptions // in case on is slightly longer than another. int size1 = pix1.length; int size2 = pix2.length; int size = 0; if(size1 > size2) size = size2; else size = size1; int new_pix[] = new int[size]; ///////////////////////////////////////// ////////////// Main Loop //////////////// ///////////////////////////////////////// for(int i = 0; i < size; i++) { ///////////////// /// Source 1 //// ///////////////// int alpha1 = (pix1[i] >> 24) & 0xff; int red1 = (pix1[i] >> 16) & 0xff; int green1 = (pix1[i] >> 8) & 0xff; int blue1 = (pix1[i] ) & 0xff; ///////////////// /// Source 2 //// ///////////////// int alpha2 = (pix2[i] >> 24) & 0xff; int red2 = (pix2[i] >> 16) & 0xff; int green2 = (pix2[i] >> 8) & 0xff; int blue2 = (pix2[i] ) & 0xff; ///////////////// /// Result //// ///////////////// int alpha3 = 255; int red3 = 0; int green3 = 0; int blue3 = 0; if(r) red3 = performOperation(red1, red2, op, clip); if(g) green3 = performOperation(green1, green2, op, clip); if(b) blue3 = performOperation(blue1, blue2, op, clip); new_pix[i] = 0; new_pix[i] += (alpha3 << 24); // alpha new_pix[i] += (red3 << 16); // r new_pix[i] += (green3 << 8); // g new_pix[i] += (blue3 ); // b } Image new_im = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, new_pix, 0, width)); return new_im; }
5
public String pad(Object obj, int len){ String str = obj.toString(); // if(len < str.length()){ StringBuilder sb = new StringBuilder(str); if(len > sb.length()){ while(len > sb.length()){ sb.append(asciiChar); } str = sb.toString(); // System.out.println(str); } else{ str = sb.substring(0, len); // System.out.println(str); } str = sb.toString(); return str; }
2
public E delMin() { final E returnValue = (E) heap.get(0); heapSize--; heap.set(0, heap.get(heapSize)); heap.delete(heapSize); heapify(0); return returnValue; }
0
private String cleanFact(String catfact) { StringBuilder sb = new StringBuilder(); boolean escaping = false; boolean unicodeSeq = false; char[] unicodeDigits = new char[4]; int unicodeSeqCount = 0; for (int i = 0; i < catfact.length(); i++) { char c = catfact.charAt(i); if (!escaping) { if (c == '\\') { escaping = true; } else { sb.append(c); } } else { if (unicodeSeq) { if (unicodeSeqCount < 4) { unicodeDigits[unicodeSeqCount] = c; unicodeSeqCount++; } else { char uni = translateUnicodeSequence(unicodeDigits); sb.append(uni); unicodeSeq = false; escaping = false; } } else { escaping = false; if (c == 'u') { escaping = true; unicodeSeq = true; unicodeSeqCount = 0; } else if (c == '\\') { sb.append(c); } else if (c == '"') { sb.append(c); } } } } return sb.toString(); }
8
void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) { if (accum.length() > 0 && out.prettyPrint() && (tag.formatAsBlock() || (parent() != null && parent().tag().formatAsBlock()) || out.outline()) ) //换行并调整缩进 indent(accum, depth, out); accum .append("<") .append(tagName()); attributes.html(accum, out); if (childNodes.isEmpty() && tag.isSelfClosing()) accum.append(" />"); else accum.append(">"); }
8
private void setResponse() { try{ ButtonModel bm = AnswerButtons.getSelection(); String selectedind = bm.getActionCommand(); selectedAnswers.put(quiz.questionList.get(qIndex).dbId, Integer.parseInt(selectedind)); } catch (NullPointerException npe) { //If no answer was selected, this gets thrown!! Catching it stops it breaking really. } }
1
public void run() throws CantRunRaidException { if (this.raidSettings.getDestination() == null) throw new CantRunRaidException(CantRunRaidBecause.DESTINATION_NULL); if (this.raidSettings.getTeam() == null || this.raidSettings.getTeam().isEmpty()) throw new CantRunRaidException(CantRunRaidBecause.NO_SURVIVORS); final int TOO_MANY_ZOMBIES = 10;//TODO parameter that can be changed by the user int zombiesKilled, zombiesInWholeZoneAtFirst = this.raidSettings.getDestination().getZombiesLeft(); this.messagesToDisplayOnceRaidIsOver = new LinkedList<String>(); this.survivorsHurtDuringRaid = new LinkedList<Survivor>(); this.newSurvivorsFound = new LinkedList<Survivor>(); int zombiesAboutToEncouter = someOfThem(zombiesInWholeZoneAtFirst); if (zombiesAboutToEncouter >= TOO_MANY_ZOMBIES) { nopeNopeNope(zombiesAboutToEncouter); } else { zombiesKilled = this.clearArea(zombiesAboutToEncouter); this.loot = this.lootArea(); this.addLootRelatedMessages(); this.addZombieRelatedMessages(zombiesAboutToEncouter, zombiesKilled); encouterNPCs(); improveSkills(zombiesKilled); } }
4
private Hotelier createHotelier(HttpServletRequest request) throws Exception{ String email = request.getParameter("email"), motDePasse = request.getParameter("motdepasse"), motDePasse2 = request.getParameter("motdepasse2"), siteweb = request.getParameter("siteweb"), nomEntreprise = request.getParameter("nomentreprise"); //Verification qu'aucun parametre est a nul. for (String parametre: new String[]{ email.trim(), motDePasse2, motDePasse, siteweb, nomEntreprise, } ) if (parametre==null) throw new Exception("Un parametre obligatoire n'est pas définit."); if(!motDePasse.equals(motDePasse2)) throw new Exception("Le mot de passe de confirmation est différent du mot de passe."); Hotelier hotelier = new Hotelier(email.trim(), motDePasse, siteweb.trim(), nomEntreprise); HotelierDAO hotelierDAO = new HotelierDAO(); if(!hotelierDAO.create(hotelier)) throw new Exception("Une erreur inconnue empeche la création du compte."); return hotelier; }
4
@Override public void actionPerformed(ActionEvent e) { String kp = e.getActionCommand(); switch (kp) { case "Host": System.out.println("Host Game"); InetAddress address = null; try { address = InetAddress.getLocalHost(); } catch (UnknownHostException e1) { e1.printStackTrace(); } IP = "::1"; break; case "Join": JFrame frame = new JFrame("IP input"); IP = JOptionPane.showInputDialog(frame, "Enter IP"); System.out.println("Join Game"); break; } }
3
public static Direction selectDirection() { return Direction.values()[randomDirection()]; }
0
private static void registerSerializableClasses(ArrayList<Class<? extends ConfigurationSerializable>> serializable) { for(Class<? extends ConfigurationSerializable> clazz : serializable) { ConfigurationSerialization.registerClass(clazz); } }
3
public double[][] getGridD2ydx1dx2(){ double[][] ret = new double[this.nPoints][this.mPoints]; for(int i=0; i<this.nPoints; i++){ for(int j=0; j<this.mPoints; j++){ ret[this.x1indices[i]][this.x2indices[j]] = this.d2ydx1dx2[i][j]; } } return ret; }
2
public static void main(String[] args) { }
0
private String getReport(){ Factory f = new Factory(); StringBuilder sb = new StringBuilder(); try{ ArrayList<User> users = f.getUsers(); for(User u : users){ appendLine(sb, "User: " + u.toString()); if(u.isClient()){ ArrayList<WorkoutPlan> uPlans = f.getWorkoutPlansForUser(u); appendLine(sb, '\t' + "Plans{"); for(WorkoutPlan uPlan : uPlans){ appendLine(sb, "\t\t" + uPlan.toString()); appendLine(sb, "\t\t" + "Elements{"); ArrayList<PlanElement> elements = f.getPlanElements(uPlan); for(PlanElement e : elements){ appendLine(sb, "\t\t\t" + e.toString()); appendLine(sb, "\t\t\t" + "Logs{"); ArrayList<WorkoutLog> logs = f.getWorkoutLogs(e.getKey()); for(WorkoutLog l : logs){ appendLine(sb, "\t\t\t\t" + l.toString()); } appendLine(sb, "\t\t\t" + "}"); } appendLine(sb, "\t\t" + "}"); } appendLine(sb, '\t' + "}"); } } ArrayList<Activity> activities = f.getActivities(); appendLine(sb, "Activities{"); for(Activity a : activities){ appendLine(sb, '\t' + a.toString()); } appendLine(sb, "}"); ArrayList<EquipmentType> types = f.getEquipmentTypes(); appendLine(sb, "Equipment Types{"); for(EquipmentType type : types) appendLine(sb, '\t' + type.toString()); appendLine(sb, '\t' + "}"); ArrayList<Equipment> equipment = f.getEquipment(); appendLine(sb, "Equipment{"); for(Equipment e : equipment) appendLine(sb, '\t' + e.toString()); appendLine(sb, '\t' + "}"); }catch(SQLException e){ e.printStackTrace(); } return sb.toString(); }
9
@Override public void execute() { final NPC bearSeller = NPCs.getNearest(Constants.BEAR_FUR_SELLER); if (bearSeller != null) { if (!bearSeller.isOnScreen()) { MCamera.turnTo(bearSeller, 50); } else { bearSeller.interact("Talk-to"); } } }
2
protected void showMainScreen(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, UnsupportedEncodingException { // set the encoding, otherwise database is encoded wrongly request.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); AdminUnitReportVM formData = (AdminUnitReportVM) session .getAttribute("formData"); session.removeAttribute("errors"); // if no viewmodel in session, then normally this is first call through // get // so check get parameters and populate viewmodel with data from dao if (formData == null) { Integer adminUnitTypeID = processAndValidateID(request); if (adminUnitTypeID == null) { adminUnitTypeID = 1; } formData = populateViewModelWithData(request, response, adminUnitTypeID); } else { // now we are in post if (backButtonWasPressed(request, response)) { return; } // clear info about last unit "Vaata" was pressed at formData.setChosenSubordinate(null); // see if "Vaata" was pressed again handleLookButtons(formData, request); // if no "Vaata" was pressed see if was refresh button if (formData.getChosenSubordinate() == null && refreshButtonWasPressed(request)) { Boolean newDataNeeded = false; if (adminUnitTypeHasChanged(formData, request)) { Integer newAdminUnitTypeID = Integer.parseInt(request .getParameter("AdminUnitType_adminUnitTypeID")); formData.setAdminUnitType(new AdminUnitTypeDAO().getByID( newAdminUnitTypeID, "")); newDataNeeded = true; } if (searchDateHasChanged(formData, request)) { formData = setCustomDate(formData, request); newDataNeeded = true; } if (newDataNeeded) { formData = setUnitTypeSpecifics(formData); } } } // save the viewmodel for jsp dispatcher into session session.setAttribute("formData", formData); // call the dispatcher request.getRequestDispatcher("AdminUnitReportScreen.jsp").forward( request, response); }
8
public void projectileDie() { for (int i = 0; i < projectiles.size(); i++) { if (projectiles.get(i).x < 0 || projectiles.get(i).y < 0 || projectiles.get(i).x > 1260 || projectiles.get(i).y > 920) { projectiles.remove(i); } } }
5
private static int[] merge(int[] left, int[] right) { int[] merged = new int[left.length+right.length]; int leftHead =0; int rightHead = 0; for(int i=0; i<left.length+right.length; i++) { if(rightHead < right.length && leftHead<left.length && left[leftHead]<right[rightHead]) { merged[i] = left[leftHead]; leftHead++; } else if(rightHead < right.length && leftHead<left.length && left[leftHead]>right[rightHead]){ merged[i] = right[rightHead]; rightHead ++; } else if(leftHead>=left.length) { merged[i] = right[rightHead]; rightHead ++; } else if(rightHead >= right.length) { merged[i] = left[leftHead]; leftHead++; } } return merged; }
9
final private boolean jj_3R_19() { Token xsp; xsp = jj_scanpos; if (jj_3R_33()) { jj_scanpos = xsp; if (jj_3R_34()) { jj_scanpos = xsp; if (jj_3R_35()) { jj_scanpos = xsp; if (jj_3R_36()) { jj_scanpos = xsp; if (jj_3R_37()) { jj_scanpos = xsp; if (jj_3R_38()) { jj_scanpos = xsp; if (jj_3R_39()) { jj_scanpos = xsp; if (jj_3R_40()) { jj_scanpos = xsp; if (jj_3R_41()) return true; } } } } } } } } return false; }
9
public void onEnable(){ blacklistLocation=new File(getDataFolder().getAbsolutePath()+"/words.txt"); whitelistLocation=new File(getDataFolder().getAbsolutePath()+"/whitelist.txt"); userdataLocation=new File(getDataFolder().getAbsolutePath()+"/userData.yml"); initConfig(); initUserData(); copyWordList(); copyWhiteList(); switch(config.getString("swear.matchmode.filtertype")){ case "plaintext": blacklist=new StringList(); break; case "synon": blacklist=new SynonStringList(); break; case "phonetic": blacklist=new PhoneticStringList(); break; default: getLogger().info("Initializing phonetic filter, as no valid filter was provided."); blacklist=new PhoneticStringList(); break; } whitelist=new StringList(); if(loadFromFile(blacklistLocation,blacklist)){ getLogger().info("Wordlist: PASS"); }else{ getLogger().severe("Wordlist: FAIL"); getServer().getPluginManager().disablePlugin(this); return; } if(loadFromFile(whitelistLocation,whitelist)){ getLogger().info("Whitelist: PASS"); }else{ getLogger().severe("Whitelist: FAIL"); getServer().getPluginManager().disablePlugin(this); return; } if(setupEconomy()){ getLogger().info("Vault: PASS"); }else{ getLogger().info("Vault: FAIL"); } if(initMetrics()){ getLogger().info("Metrics: PASS"); }else{ getLogger().info("Metrics: FAIL"); } if (config.getBoolean("swear.sign.enabled")){ this.getServer().getPluginManager().registerEvents(new SignListener(blacklist,this), this); } this.getServer().getPluginManager().registerEvents(new ChatListener(blacklist,whitelist,this), this); if (config.getBoolean("swear.autopardon.enable")){ getLogger().info("Autopardon: PASS"); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Pardoner(playerlist, config.getInt("swear.autopardon.minimum")), 0, config.getLong("swear.autopardon.interval")*20L*60L); }else{ getLogger().info("Autopardon: FAIL"); } }
9
private Automaton readAutomaton(File file) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); // Read the automaton type. String line = reader.readLine().trim(); if (line.equals(FINITE_AUTOMATON_CODE)) return readFA(reader); if (line.equals(PUSHDOWN_AUTOMATON_CODE)) return readPDA(reader); if (line.equals(TURING_MACHINE_CODE)) return readTM(reader); throw new ParseException("Unknown machine type " + line + "!"); } catch (NullPointerException e) { throw new ParseException("Unexpected end of file!"); } catch (FileNotFoundException e) { throw new ParseException("Could not find file " + file.getName() + "!"); } catch (IOException e) { throw new ParseException("Error accessing file to write!"); } }
6
private Assertion assertAreEqual(Stack<Command> expected, Stack<Command> actual) { boolean passed = false; String info = "Assertion failed for unknown reasons"; if (expected != null && actual != null) { if (expected.size() != actual.size()) { passed = false; info = "The actual stack is not the same size as the expected stack"; } else { boolean allEqual = true; while (!expected.isEmpty()) { Command expectedValue = expected.pop(); Command actualValue = actual.pop(); if (!expectedValue.equals(actualValue)) { allEqual = false; passed = false; info = "Not all commands in the expected and actual stacks are identical"; break; } } if (allEqual) { passed = true; info = "The actual and expected stacks match"; } } } else { info = "At least one of the input stacks was null"; } return new Assertion(passed, info); }
6
static String HardwareLiteral (String toParse, String label, byte wordLength) { byte decimalValue = 0; byte labelLength; byte significance; String binary32; StringBuffer expression; labelLength = (byte)label.length(); if (toParse.startsWith(label)) { try { decimalValue = Byte.parseByte(toParse.substring(labelLength)); if (decimalValue > -1) //Not checking for upper bound 2^wordLength { expression = new StringBuffer (6); binary32 = Integer.toBinaryString(decimalValue); significance = (byte)binary32.length(); if (significance > wordLength) //Too big to be represented. { throw new IllegalArgumentException ("Integer overflow; Value does not fit "+wordLength+" bits."); } else { //Append wordLength - significance '0's to expression. for (int i = wordLength - significance; i > 0; i--) expression.append('0'); //Append binary32 to expression. expression.append(binary32); } //Append 6-wordLength 1's to expression. for (int i = wordLength; i < 6; i++) expression.append('1'); } else //Negative numbers cannot be handled. { ErrorLog.addError(toParse + ": Cannot parse a negative number"); expression = new StringBuffer ("Error!"); } } catch (NumberFormatException e) { ErrorLog.debug ("Parse error on " + toParse); ErrorLog.addError ("Parse error on " + toParse + e.toString()); expression = new StringBuffer ("Error!"); } } else { expression = new StringBuffer ("Error!"); ErrorLog.debug ("Invalid term label; " + label); ErrorLog.addError(toParse + " is not labelled " + label); } return expression.toString(); }
6
public Location getLocationAtDirection(Direction direction) { switch (direction) { case UP: return new Location(column, row - 1); case DOWN: return new Location(column, row + 1); case LEFT: return new Location(column - 1, row); case RIGHT: return new Location(column + 1, row); default: return new Location(column, row - 1); } }
4
static private int jjMoveStringLiteralDfa7_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(5, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(6, active0); return 7; } switch(curChar) { case 84: case 116: if ((active0 & 0x400L) != 0L) return jjStartNfaWithStates_0(7, 10, 12); break; default : break; } return jjStartNfa_0(6, active0); }
5
private void removeOld() throws FileStorageException { final FileSystemService fileSystemService = new FileSystemService(); final Properties expirationDates = systemInformation.getExpirationDates(); final Set<String> keys = expirationDates.stringPropertyNames(); for (String key : keys) { final String expirationDate = expirationDates.getProperty(key); if(expirationDate == null){ continue; } final long time = Long.parseLong(expirationDate); if (expirationDate != null && time != Item.WITHOUT_EXPIRATION) { Item item = systemInformation.get(key); if (item == null) { continue; } if ((item.getExpirationTime() + item.getCreationTime()) < System.currentTimeMillis()) { fileSystemService.removeFile(systemInformation.getRootPath() + item.getPath()); systemInformation.remove(item); } } } }
6
private String createDelete() { String param = ""; for(Column col : keyColumns){ param += col.getColName() + " = #{" + col.getFldName() + "} AND "; } param = param.substring( 0, param.length() - 5 ); StringBuilder sb = new StringBuilder(); sb.append( "\n" ); sb.append( "\n" + TAB + "<delete id=\"delete\" parameterType=\"map\">\n"); sb.append( TAB + TAB + "delete from " + table.getTableName().toUpperCase() + "\n" ); sb.append( TAB + TAB + "where " + param + "\n" ); sb.append( TAB + "</delete>" ); return sb.toString(); }
1
public static void handleEvent(int eventId) { // Do nothing because same screen is being selected if(eventId == 1) { System.out.println("Exit Ship Shop Thrusters to Main Ship Shop Menu selected"); Main.ShipShopThrustersMenu.setVisible(false); Main.ShipShopThrustersMenu.setEnabled(false); Main.ShipShopThrustersMenu.setFocusable(false); Main.mainFrame.remove(Main.ShipShopThrustersMenu); Main.mainFrame.add(Main.ShipShopMenu); Main.ShipShopMenu.setVisible(true); Main.ShipShopMenu.setEnabled(true); Main.ShipShopMenu.setFocusable(true); Main.ShipShopMenu.requestFocusInWindow(); } // Do nothing because same screen selected else if(eventId == 2) { System.out.println("Exit Ship Shop Thrusters to Engines Ship Shop Menu selected"); Main.ShipShopThrustersMenu.setVisible(false); Main.ShipShopThrustersMenu.setEnabled(false); Main.ShipShopThrustersMenu.setFocusable(false); Main.mainFrame.remove(Main.ShipShopThrustersMenu); Main.mainFrame.add(Main.ShipShopEnginesMenu); Main.ShipShopEnginesMenu.setVisible(true); Main.ShipShopEnginesMenu.setEnabled(true); Main.ShipShopEnginesMenu.setFocusable(true); Main.ShipShopEnginesMenu.requestFocusInWindow(); } else if(eventId == 3) { System.out.println("Exit Ship Shop Thrusters to Hulls Ship Shop Menu selected"); Main.ShipShopThrustersMenu.setVisible(false); Main.ShipShopThrustersMenu.setEnabled(false); Main.ShipShopThrustersMenu.setFocusable(false); Main.mainFrame.remove(Main.ShipShopThrustersMenu); Main.mainFrame.add(Main.ShipShopHullsMenu); Main.ShipShopHullsMenu.setVisible(true); Main.ShipShopHullsMenu.setEnabled(true); Main.ShipShopHullsMenu.setFocusable(true); Main.ShipShopHullsMenu.requestFocusInWindow(); } else if(eventId == 4) { } else if(eventId == 5) { System.out.println("Exit Ship Shop Thrusters to Weapons Ship Shop Menu selected"); Main.ShipShopThrustersMenu.setVisible(false); Main.ShipShopThrustersMenu.setEnabled(false); Main.ShipShopThrustersMenu.setFocusable(false); Main.mainFrame.remove(Main.ShipShopThrustersMenu); Main.mainFrame.add(Main.ShipShopWeaponsMenu); Main.ShipShopWeaponsMenu.setVisible(true); Main.ShipShopWeaponsMenu.setEnabled(true); Main.ShipShopWeaponsMenu.setFocusable(true); Main.ShipShopWeaponsMenu.requestFocusInWindow(); } else if(eventId == 6) { } else if(eventId == 7) { } else if(eventId == 8) { System.out.println("Exit Ship Shop Thrusters to Main Menu selected"); Main.ShipShopThrustersMenu.setVisible(false); Main.ShipShopThrustersMenu.setEnabled(false); Main.ShipShopThrustersMenu.setFocusable(false); Main.mainFrame.remove(Main.ShipShopThrustersMenu); Main.mainFrame.add(Main.mainMenu); Main.mainMenu.setVisible(true); Main.mainMenu.setEnabled(true); Main.mainMenu.setFocusable(true); Main.mainMenu.requestFocusInWindow(); } }
8
public String getColors(){ String output = ""; if(white){ output += "W"; } if(blue){ output += "U"; } if(black){ output += "B"; } if(red){ output += "R"; } if(green){ output += "G"; } return output; }
5
private void checkBrowserLoading() { // браузер терминала if (( (new File("/usr/local/bin/chrome_ps.sh").exists()) && this.getRuntime("/usr/local/bin/chrome_ps.sh").equals("0"))) { this.doRuntime("sh "+ terminalDir+"/browser.sh"); this.ok = false; } // браузер с рекламой if (adv.equals("1")) { // 5 sec. try{Thread.sleep(2000L);}catch(Exception e){} if (( (new File("/usr/local/bin/chromium_ps.sh").exists()) && this.getRuntime("/usr/local/bin/chromium_ps.sh").equals("0"))) { this.doRuntime("sh "+ terminalDir+"/adv_screen.sh"); this.ok = false; } } }
6
public void paintLists() { for (int i = 0; i < spaceJunk.size(); i++) { SpaceJunk a = spaceJunk.get(i); if (distanceToShip((int) a.xPosition, (int) a.yPosition) < Game.RESOLUTION_WIDTH) { a.paint(offg, cameraOffsetX, cameraOffsetY); } } for (int i = 0; i < planets.size(); i++) { Planet p = planets.get(i); if (distanceToShip((int) p.xPosition, (int) p.yPosition) < Game.RESOLUTION_WIDTH * 3) { p.paint(offg, cameraOffsetX, cameraOffsetY); } } for (int i = 0; i < bullets.size(); i++) { Bullet b = bullets.get(i); if (distanceToShip((int) b.xPosition, (int) b.yPosition) < Game.RESOLUTION_WIDTH) { b.paint(offg, cameraOffsetX, cameraOffsetY); } } for (int i = 0; i < debris.size(); i++) { debris.get(i).paint(offg, cameraOffsetX, cameraOffsetY); } }
7
public int getStatus() { return status; }
0
protected boolean step() { controller.step(); return true; }
0
Byte getToken( char tokenChar ) { switch ( tokenChar ) { case 'l': lineCount++; endLf = true; return TKN_ALF; case 'L': return TKN_AL; case 'r': lineCount++; endLf = true; return TKN_ARF; case 'R': return TKN_AR; case 'c': lineCount++; endLf = true; return TKN_ACF; case 'C': return TKN_AC; default: return TKN_NULL; } }
6
public void setTexture(String texturePath){ this.texturePath = texturePath; try { texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(texturePath)); } catch (IOException e) { e.printStackTrace(); } }
1
@Override public void doIt() { // hole Log-Dateien File path = new File(this.path + Output.DIR_LOG); final Pattern pattern = Pattern.compile(".+" + Pattern.quote(LogFile.FILE_EXTENSION) + "$"); File[] list = path.listFiles(new FileFilter() { @Override public boolean accept(File filename) { return pattern.matcher(filename.getName()).matches() && filename.isFile(); } }); Arrays.sort(list); StringBuffer content = new StringBuffer(getHeader("Überblick") + "<h1>Auswertung</h1>" + "<table id=\"example\">" + "<thead><tr>" + "<th style=\"min-width:150px\">Zeitpunkt</th>" + "<th style=\"min-width:250px\">Informationen</th>" + "<th style=\"min-width:100px\">Typ</th>" + "</tr></thead>"); for (File c : list) { content.append((new LogFile(c.getAbsolutePath())).getHtmlTr()); } content.append("</table>" + getFooter()); write(content.toString()); }
2
public static Reponse reponse(int id, Utilisateur utilisateur) { Reponse rep = ReponseRepo.get().un(id); if (rep != null && !rep.getSujet().peutConsulter(utilisateur)) throw new InterditException("Vous n'avez pas les droits requis pour consulter cette réponse"); return rep; }
2
public void generateChoiceKrit(int fahrplanID, String fahrplanName) { boolean szVorhanden = false; if (this.szenarienVerbergen.getOpacity() != 1) { FadeTransition fb = new FadeTransition(Duration.millis(1500), this.szenarienVerbergen); fb.setFromValue(0.0); fb.setToValue(1.0); fb.setAutoReverse(true); fb.play(); } ArrayList<Szenario> choice = new ArrayList<Szenario>(); for (int i = 0; i < this.szenarienListe.size(); i++) { if (this.szenarienListe.get(i).getFahrplanID() == fahrplanID) { choice.add(this.szenarienListe.get(i)); szVorhanden = true; } } if (szVorhanden == true) { if (this.mainApp.showSzenario(choice, fahrplanName)) { this.szenarienAktiv = true; refreshBothGraphics(); } } else { String fehlerA = "Zum Plan wurden keine zugehörigen Szenarien gefunden"; String fehlerB = "Szenarien anzeigen ?"; String fehlerC = "Fehler"; this.mainApp.fehlerMeldung(fehlerA, fehlerB, fehlerC); } }
5
public String getPassword() { return password; }
0
public static LinkedList<String> computeIntersection(LinkedList<String> A, LinkedList<String> B) { LinkedList<String> intersection = new LinkedList<String>(); for( int i = 0; i <A.size(); i++) { String item = A.get(i); if(B.contains(item)) { intersection.add(item); } } return intersection; }
2
public void recalculate(String IPkey, String IPComing, ArrayList<String> comingConnections){ ArrayList<String[]> tempArray = (ArrayList<String[]>)routingTable.get(IPkey); String[] tempStringArray = null; for(int i=0; i<tempArray.size(); i++){ tempStringArray = tempArray.get(i); if(tempStringArray[0].equals(IPComing)){ for(int j=0; j<comingConnections.size(); j++){ if(tempStringArray[1].equals(getAddress(comingConnections.get(j)))){ tempStringArray[2] = Integer.toString(Integer.parseInt(searchForCost(tempArray, IPComing)) + Integer.parseInt(getDistance(comingConnections.get(j)))); } } } } }
4
private void saveLinks(ArrayList<Link> linkMap) throws ForceErrorException { int iCounter = 0; for (Link link : linkMap) { if (iCounter > Bot.linksFromUrl) { break; } if (Bot.datamodel.saveLink(link.getUrl())) { iCounter++; } } }
3
public static void main(String[] args) throws InterruptedException { List<FutureTask<Integer>> list = new ArrayList<FutureTask<Integer>>( Arrays.asList(new FutureTask<Integer>(new WordLengthCallable()), new FutureTask<Integer>(new WordLengthCallable()), new FutureTask<Integer>(new WordLengthCallable()), new FutureTask<Integer>(new WordLengthCallable())) ); for (FutureTask<Integer> elem: list) { new Thread(elem).start(); } int sum = 0; for (FutureTask<Integer> elem: list) { try { sum += elem.get().intValue(); } catch (ExecutionException e) { e.printStackTrace(); } } System.out.println("Result = " + sum); System.exit(0); }
3
public static void detectPressedKey(){ int[] keys = {Keyboard.KEY_1, Keyboard.KEY_2, Keyboard.KEY_3,Keyboard.KEY_4,Keyboard.KEY_5,Keyboard.KEY_6,Keyboard.KEY_7,Keyboard.KEY_8,Keyboard.KEY_9}; boolean found = false; for(int i = 0; i < keys.length; i++){ if(Keyboard.isKeyDown(keys[i])){ selectedSlot = i; found = true; break; } } if(found == false) selectedSlot = -1; }
3
private void grow(int extra, int[] values, int[] max, boolean fill) { int count = 1 + (values.length - 1) / 2; int[] tv = new int[count]; int[] tm = new int[count]; for (int i = 0; i < count; i++) { tv[i] = values[i * 2]; tm[i] = max[i * 2]; } extra = distribute(extra, tv, tm); for (int i = 0; i < count; i++) { values[i * 2] = tv[i]; } if (extra > 0 && fill) { // None are accepting more space, so force them count = 1 + (values.length - 1) / 2; while (extra > 0) { int amt = extra / count; if (amt < 1) { amt = 1; } for (int i = 0; i <= values.length && extra > 0; i += 2) { values[i] += amt; max[i] += amt; extra -= amt; } } } }
8
@Override public void removeInheritence(String inher) { do { inheritence.remove(inher); } while (inheritence.contains(inher)); }
1
@Override public void init(boolean isServer) { if(!isServer) { PlayerEntity.loadResources(); PillarEntity.loadResources(); } tiles = new Tile[8][6]; for(int x = 0; x < tiles.length; x++) for(int y = 0; y < tiles[x].length; y++) tiles[x][y] = new Tile(this, x, y); entities = new ArrayList<Entity>(); entities.add(new PillarEntity(this, tiles[1][1])); entities.add(new PillarEntity(this, tiles[2][1])); entities.add(new PillarEntity(this, tiles[3][1])); player = new PlayerEntity(this, tiles[tiles.length/2][tiles[0].length/2]); entities.add(player); perspective = new EntityPerspective(this, player); }
3
public static <T extends IComponent> void getAllChildrenTComponents(Entity entity, Class<T> clazz, List<T> componentList) { Children childrenComponent = entity.getComponent(Children.class); // Our base test, stop recursion if we no longer have children if (childrenComponent == null) { return; } for (Entity child : childrenComponent.children) { // Add to the componentList any of the children's components that we // are searching for, and then call this function on the child (in // case that child also has children) T component = child.getComponent(clazz); if (component != null) { componentList.add(component); } getAllChildrenTComponents(child, clazz, componentList); } }
3
private int puolisonPaikallaToistaSukupuolta(boolean mies) { int pisteita = 0; try { if (paikka.getPuolisonPaikka() != null) { if (paikka.getPuolisonPaikka().getSitsaaja().isMies()) { if (mies == false) { pisteita += 500; } } else { if (mies == true) { pisteita += 500; } } } } catch (UnsupportedOperationException e) { } return pisteita; }
5
public static double getAtomicWeight(Atom currentAtom) { double atomWeight = 0; String atomType = Character.toString(currentAtom.getAtomType() .charAt(0)); String[] atomTypeArray = { "H", "N", "C", "O", "S" }; double[] atomWeightArray = { 1.00794, 14.0067, 12.0107, 15.9994, 32.065 }; for (int i = 0; i < atomTypeArray.length; ++i) { if (atomType.equals(atomTypeArray[i])) { atomWeight = atomWeightArray[i]; } } return atomWeight; }
2
public Node getViewWithoutRootContainer() { final ObservableList<Node> children = getView().getChildrenUnmodifiable(); if (children.isEmpty()) { return null; } return children.listIterator().next(); }
1
private final boolean cvc(int i) { if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; }
7
private void printChessBoard(int rows,int columns, Cell[] boardCells){ String errorMsg; for(int currentRow = 0; currentRow < rows; currentRow++){ for(int currentColumn = 0; currentColumn < columns; currentColumn++){ int position = currentRow * columns + currentColumn; char representationChar; if (position >= boardCells.length){ representationChar = '·'; } else{ Cell cell = boardCells[position]; if (cell == Cell.DEFAULT_EMPTY_CELL){ representationChar = ChessConstants.EMPTY_CELL_CHAR; }else{ if (cell == Cell.DEFAULT_TAKEN_CELL){ representationChar= ChessConstants.TAKEN_CELL_CHAR; }else{ PieceCell pieceCell = (PieceCell) cell; Piece piece = pieceCell.getPiece(); representationChar = ChessTools.getCharFromPiece(piece); } } } System.out.print(representationChar); } System.out.println(); } }
5
private void ParseElements(Node parentElement) { Node child = parentElement.getFirstChild(); while (child != null) { String nodeName = child.getNodeName(); if (nodeName == "condition") { conditions.add(new Condition(child)); } else if (nodeName == "print") { message = child.getFirstChild().getNodeValue(); } else if (nodeName == "action") { action = child.getFirstChild().getNodeValue(); } else if (nodeName == "type") { type = child.getFirstChild().getNodeValue(); } else if (nodeName == "command") { command = child.getFirstChild().getNodeValue(); } child = child.getNextSibling(); } }
6
public boolean canHaveAsBalance(BigInteger balance) { return (balance != null) && (balance.compareTo(this.getCreditLimit()) >= 0); }
1
public T borrow() { initPool(); T object = queue.poll(); if (object == null) { object = create(); } return object; }
1
@Override public void fatalError(SAXParseException e) { System.out.println("SAXParserException Fatal Error: " + e.getMessage()); this.errorOccurred = true; }
0
public void kasitteleLauseke() throws IllegalStateException, IllegalArgumentException { while (paikkaSisaltyySyotteeseen()) { kasitteleSeuraava(); } lauseke.suljeLohko(); }
1
public ArrayList<ArrayList<Integer>> combine(int n, int k) { ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>(); int[] tmp = new int[k]; for (int i =0; i< k ;i++) tmp[i] = i + 1; while (true) { ArrayList<Integer> ele = new ArrayList<Integer>(); for (int i : tmp) { ele.add(i); } rst.add(ele); int j = tmp.length -1; while (j >= 0 && tmp[j] == n - (tmp.length -j -1)) j--; if (j < 0) break; tmp[j] ++; for (int i = j + 1; i < tmp.length; i++) tmp[i] = tmp[i-1] + 1; } return rst; }
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already detecting weather.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> gain(s) sensitivity to the weather!"):L("^S<S-NAME> invoke(s) weather sensitivity!^?")); if(mob.location().okMessage(mob,msg)) { lastPrediction=""; mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else beneficialVisualFizzle(mob,null,L("<S-NAME> incant(s) into the sky, but the spell fizzles.")); return success; }
8
public synchronized void recordAndAddSequenceNumberToOutgoingPacket(Packet packet) { //ignore null packets if(packet == null) return; //add sequence number to packet lastSentPacketSequenceNumber = Packet.nextSequenceNumber(lastSentPacketSequenceNumber); packet.setSequenceNumber(lastSentPacketSequenceNumber); //add packet to array of sent packets lastSentPacketIndex++; if(lastSentPacketIndex == PacketRecorder.NUM_SENT_PACKETS_STORED) lastSentPacketIndex = 0; sentPackets[lastSentPacketIndex] = new PacketReceipt(packet); }
2
private static int findMax(boolean useX, ArrayList<Point> convexHull) { int max = 0; int index = -1; for (int i = 0; i < convexHull.size(); i++) { int val = useX ? convexHull.get(i).x : convexHull.get(i).y; if (max < val) { max = val; index = i; } } return index; }
3
public Items getItem() { return this.item; }
0
public void combat(Personnage heros, Personnage ennemi) { Random rand = new Random(); int randomDefensePercentage = rand.nextInt(50)+1; int defense = heros.getDef() - (heros.getDef()*randomDefensePercentage)/100; int degats = ennemi.getAtk(); int dommage = degats-defense; if(dommage>0) { heros.setVie(heros.getVie()-degats); } randomDefensePercentage = rand.nextInt(50)+1; defense = ennemi.getDef() - (ennemi.getDef()*randomDefensePercentage)/100; degats = heros.getAtk(); dommage = degats - defense; if(dommage>0) { ennemi.setVie(ennemi.getVie()-dommage); } }
2
public static void printByteArray(byte[] bytes) { for (byte b : bytes) { System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " "); } System.out.println(); }
1
public Transition getTransitionForProduction(Production production) { ProductionChecker pc = new ProductionChecker(); String lhs = production.getLHS(); State from = getStateForVariable(lhs); /** if of the form A->xB */ if (ProductionChecker.isRightLinearProductionWithVariable(production)) { String[] variables = production.getVariablesOnRHS(); String variable = variables[0]; State to = getStateForVariable(variable); String rhs = production.getRHS(); String label = rhs.substring(0, rhs.length() - 1); FSATransition trans = new FSATransition(from, to, label); return trans; } /** if of the form A->x */ else if (ProductionChecker.isLinearProductionWithNoVariable(production)) { String transLabel = production.getRHS(); State finalState = getStateForVariable(FINAL_STATE); FSATransition ftrans = new FSATransition(from, finalState, transLabel); return ftrans; } return null; }
2
public void checkfold() { for (Widget wdg = child; wdg != null; wdg = wdg.next) { if ((wdg == cbtn) || (wdg == fbtn)) continue; if (folded) { if (wdg.visible) { wdg.hide(); wfolded.add(wdg); } } else if (wfolded.contains(wdg)) { wdg.show(); } } Coord max = new Coord(ssz); if (folded) { max.y = 0; } else { wfolded.clear(); } if (this.cap.text.equals("Menu")) { if (folded) max.y = 18; else max = oldSize; recalcSize(max); } else recalcsz(max); }
9
public void run() { while(listening) { try { // listen on request as server // byte[] bufReceived = new byte[BUFFER_SIZE]; DatagramPacket serverPacket = new DatagramPacket(bufReceived, bufReceived.length); serverSocket.receive(serverPacket); // parse received info. String received = new String(serverPacket.getData(), 0, serverPacket.getLength()); // System.out.println("Received from " + serverPacket.getAddress().getHostName() + ":\n" + received); LinkedList<RoutingTable> receivedList = readReceived(received); // listen to get something new, update currentHost list // need lock somehow // LinkedList<DistanceVector[]> latest = currentHost; Hashtable<String, Vector<DistanceVector>> latest = currentHost; // current host source String[] hostFile = file.split("\\.dat"); String start = hostFile[0]; for(int i=0; i<receivedList.size(); i++) { RoutingTable rt = receivedList.get(i); // update cost if(latest.containsKey(start + "-" + rt.getDest())) { Vector<DistanceVector> dVector = latest.get(start + "-" + rt.getDest()); int index = neighbors.indexOf(rt.getSource()); double newCost = neighbor_pair.get(start + "-" + rt.getSource()) + rt.getCost(); if(dVector.get(index).getCost() > newCost) { dVector.get(index).setCost(newCost); // System.out.println("Cost change to currentHost"); } } else { if(start.equals(rt.getDest())) { // System.out.println("Nonsense same to same host"); continue; } // add new dest else { Vector<DistanceVector> newVector = new Vector<DistanceVector>(); for(int k=0; k<neighbors.size(); k++) { newVector.add(new DistanceVector(start, neighbors.get(k), rt.getDest(), INFINITY)); } int index = neighbors.indexOf(rt.getSource()); // in-place replace newVector.set(index, new DistanceVector(start, rt.getSource(), rt.getDest(), neighbor_pair.get(start + "-" + rt.getSource()) + rt.getCost())); currentHost.put(start + "-" + rt.getDest(), newVector); // System.out.println("Added newLine into currentHost"); } } } // figure out response and reuse buf as send carrier /* bufReceived = DVToRT(currentHost).getBytes(); // send the response to the client at "address" and "port" InetAddress address = serverPacket.getAddress(); int portNum = serverPacket.getPort(); serverPacket = new DatagramPacket(bufReceived, bufReceived.length, address, portNum); serverSocket.send(serverPacket); */ } catch(IOException e) { e.printStackTrace(); } } serverSocket.close(); }
7
@Override public void paintShape(mxGraphics2DCanvas canvas, String text, mxCellState state, Map<String, Object> style) { mxLightweightLabel textRenderer = mxLightweightLabel .getSharedInstance(); CellRendererPane rendererPane = canvas.getRendererPane(); Rectangle rect = state.getLabelBounds().getRectangle(); Graphics2D g = canvas.getGraphics(); if (textRenderer != null && rendererPane != null && (g.getClipBounds() == null || g.getClipBounds().intersects( rect))) { double scale = canvas.getScale(); int x = rect.x; int y = rect.y; int w = rect.width; int h = rect.height; if (!mxUtils.isTrue(style, mxConstants.STYLE_HORIZONTAL, true)) { g.rotate(-Math.PI / 2, x + w / 2, y + h / 2); g.translate(w / 2 - h / 2, h / 2 - w / 2); int tmp = w; w = h; h = tmp; } // Replaces the linefeeds with BR tags if (isReplaceHtmlLinefeeds()) { text = text.replaceAll("\n", "<br>"); } // Renders the scaled text textRenderer.setText(createHtmlDocument(style, text, (int) Math.round(w / state.getView().getScale()), (int) Math.round(h / state.getView().getScale()))); textRenderer.setFont(mxUtils.getFont(style, canvas.getScale())); g.scale(scale, scale); rendererPane.paintComponent(g, textRenderer, rendererPane, (int) (x / scale) + mxConstants.LABEL_INSET, (int) (y / scale) + mxConstants.LABEL_INSET, (int) (w / scale), (int) (h / scale), true); } }
6