text
stringlengths
14
410k
label
int32
0
9
private static ArrayList<Long> readNumbersArrayFromFile() { ArrayList<Long> longArray = new ArrayList<Long>(); FileInputStream fstream = null; try { fstream = new FileInputStream("algo1-programming_prob-2sum.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null){ longArray.add(Long.valueOf(line)); } br.close(); }catch (FileNotFoundException ex) { Logger.getLogger(Question1.class.getName()).log(Level.SEVERE, null, ex); }catch (IOException ex) { Logger.getLogger(Question1.class.getName()).log(Level.SEVERE, null, ex); }finally { try { fstream.close(); } catch (IOException ex) { Logger.getLogger(Question1.class.getName()).log(Level.SEVERE, null, ex); } } return longArray; }
4
public void createNextGeneration(ArrayList<BuildOrder> orders) { Gson gson = new Gson(); System.out.println("The following build orders will survive in the gene pool: "); for (BuildOrder order : orders) { System.out.println(gson.toJson(order)); } try { File knowledgeBase = new File(knowledgeBasePath); BufferedWriter writer = new BufferedWriter(new FileWriter( knowledgeBase, false)); KnowledgeBaseObject kb = new KnowledgeBaseObject(); kb.index = 0; kb.iterationNum = iterNum + 1; kb.readyToMutate = false; kb.orders = new ArrayList<BuildOrder>(); // Keep the original 3 winners, but update their index for (BuildOrder order : orders) { order.score = -1; kb.orders.add(order); } System.out.println("Cross Breeding..."); for (BuildOrder first : orders) { for (BuildOrder second : orders) { if (first == second) { continue; } System.out.println(first + " mating " + second); BuildOrder newOrder = new BuildOrder(); newOrder.score = -1; newOrder.order = crossBreed(first.order, second.order); kb.orders.add(newOrder); } } BuildOrder one = orders.get(0); one.order = mutate(one.order); one.score = -1; kb.orders.add(one); BuildOrder two = orders.get(1); two.order = mutate(two.order); two.score = -1; kb.orders.add(two); BuildOrder three = orders.get(2); three.order = mutate(two.order); three.score = -1; kb.orders.add(three); // Flip 2 random moves in the original 3 to add some mutation to // the mix writer.write(gson.toJson(kb)); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
6
public void printViterbi(boolean getBest) { Iterator<String> myIt=ViterbiEndpoint.keySet().iterator(); String myStr; boolean entered=false; double bestVal=2; String bestStr=""; while (myIt.hasNext()) { myStr=myIt.next(); if (!entered || bestVal< ViterbiEndpoint.get(myStr)) {bestVal=ViterbiEndpoint.get(myStr);bestStr=myStr;entered=true;} if (getBest) {continue;} System.out.println("SCORE("+myStr+")="+ViterbiEndpoint.get(myStr)); System.out.println("\t"+ViterbiPath.get(myStr)); } if (getBest) { System.out.println("SCORE("+bestStr+")="+ViterbiEndpoint.get(bestStr)); System.out.println("\t"+ViterbiPath.get(bestStr)); } }
5
public boolean equals(DisplayState other) { if(other == null) return false; return other.getCurrState() == this.getCurrState() && this.getImageIndex() == other.getImageIndex() && this.commands.equals(other.getCommands()); }
3
void sendBytes ( final Socket sock ) throws IOException { @SuppressWarnings ( "resource" ) OutputStream out = sock.getOutputStream(); byte[] buf = new byte[this.bytesSent]; for ( int i = 0; i < this.bytesSent; i++ ) { buf[ i ] = (byte) ( i + 'A' ); } out.write(buf); out.flush(); }
1
static String getQudrantXY(String v, String h) { int hor = Integer.valueOf(h); int vert = 1; if (v.equals("b")) { vert = 2; } else if (v.equals("c")) { vert = 3; } else if (v.equals("d")) { vert = 4; } else if (v.equals("e")) { vert = 5; } else if (v.equals("f")) { vert = 6; } else if (v.equals("g")) { vert = 7; } else if (v.equals("h")) { vert = 8; } else if (v.equals("i")) { vert = 9; } return v + h + ":(" + (vert - 1) * 64 + "px; " + (hor - 1) * 64 + "px)"; }
8
public void updateFont(List<Font> fonts, int startFrom, int endAt) { int i, j; for (i = startFrom, j = 0; i <= endAt; i++, j++) { this.children.get(i).setFont(fonts.get(j)); } this.modelChanged(); }
1
private void processSendButton() { // // make sure the the specified file exits // String fileName = fFileFullPathname.getText(); File file = null; String[] recipients = null; WarningUI warning = null; if (fileName.length() == 0) { warning = new WarningUI( fParentFrame, StringDefs.ERROR, StringDefs.FILE_NOT_SPECIFIED); } else { file = new File(fileName); recipients = StringUtil.parseToArray(fToList.getText()); if (!file.exists()) { warning = new WarningUI( fParentFrame, StringDefs.ERROR, StringDefs.FILE_NOT_FOUND); } else if (!file.canRead()) { warning = new WarningUI( fParentFrame, StringDefs.ERROR, StringDefs.FILE_NOT_READABLE); } else if (!file.isFile()) { warning = new WarningUI( fParentFrame, StringDefs.ERROR, StringDefs.FILE_NOT_FILE); } else if (recipients == null) { warning = new WarningUI( fParentFrame, StringDefs.ERROR, StringDefs.RECIPIENT_NOT_SPECIFIED); } } if (warning != null) { warning.setVisible(true); } else { setVisible(false); FileSendThread fileSendThread = new FileSendThread(file, recipients); fileSendThread.start(); } }
6
private static void lisaaAveceja(int aveceja, ArrayList<Sitsaaja> sitsaajat) { int i = 0; do { Sitsaaja sitsaaja = Yhteydet.annaRandomSitsaaja(sitsaajat);; do { sitsaaja = Yhteydet.annaRandomSitsaaja(sitsaajat); } while (sitsaaja.puolisoIsSet() == true || sitsaaja.avecIsSet() == true); Sitsaaja kohdeSitsaaja = Yhteydet.annaRandomSitsaaja(sitsaajat); do { kohdeSitsaaja = Yhteydet.annaRandomSitsaaja(sitsaajat); } while (kohdeSitsaaja.puolisoIsSet() == true || kohdeSitsaaja.avecIsSet() == true); sitsaaja.setAvec(kohdeSitsaaja); kohdeSitsaaja.setAvec(sitsaaja); i++; } while (i < aveceja); }
5
@Test public void testSetFood() throws IOException { System.out.println("setFood"); AntBrain b = new AntBrain("cleverbrain1.brain"); Ant instance = new Ant(b,true,0); boolean expResult = false; boolean result = instance.getFood(); assertEquals(expResult, result); instance.setFood(true); expResult = true; result = instance.getFood(); assertEquals(expResult, result); }
0
public boolean containsValue(Object value) { if (value == null) { for (int i = 0, isize = data.length; i < isize; i++) { HashEntry entry = data[i]; while (entry != null) { if (entry.getValue() == null) { return true; } entry = entry.next; } } } else { for (int i = 0, isize = data.length; i < isize; i++) { HashEntry entry = data[i]; while (entry != null) { if (isEqualValue(value, entry.getValue())) { return true; } entry = entry.next; } } } return false; }
7
public static void main(String[] args){ Application app = new Application(); app.run(); System.exit(0); }
0
public boolean modelTypeCached(int modelType) { if (modelTypes == null) { if (modelIds == null) return true; if (modelType != 10) return true; boolean cached = true; for (int id = 0; id < modelIds.length; id++) cached &= Model.isCached(modelIds[id] & 0xffff); return cached; } for (int type = 0; type < modelTypes.length; type++) if (modelTypes[type] == modelType) return Model.isCached(modelIds[type] & 0xffff); return true; }
6
public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) { String value = null; Annotation annotation = classType.getAnnotation(annotationType); if (annotation != null) { try { value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation); } catch (Exception ex) {} } return value; }
2
@Test(groups = { "Character-Sorting", "Fast Sort" }) public void testHeapSortChar() { Reporter.log("[ ** Heap Sort ** ]\n"); try { testSortCharacters = new HeapSort<>( fastShuffledArrayChar.clone()); Reporter.log("1. Unsorted Random Array\n"); timeKeeper = System.currentTimeMillis(); testSortCharacters.sortArray(); if (testSortCharacters.isSorted()) Reporter.log("Test Passed : "); else throw new TestException("Array was not sorted!!!"); Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n"); Reporter.log("2. Sorted Random Array\n"); timeKeeper = System.currentTimeMillis(); testSortCharacters.sortArray(); if (testSortCharacters.isSorted()) Reporter.log("Test Passed : "); else throw new TestException("Array was not sorted!!!"); Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n"); Reporter.log("3. Reversed Sorted Array\n"); ShuffleArray.reverseArray(testSortCharacters.getArray()); timeKeeper = System.currentTimeMillis(); testSortCharacters.sortArray(); if (testSortCharacters.isSorted()) Reporter.log("Test Passed : "); else throw new TestException("Array was not sorted!!!"); Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n"); } catch (Exception x) { System.err.println(x); throw x; } }
4
public void remotePlayerPutCard(Player p, Card c) { TurnContext cx = p.getCurrentContext(); CardRange r = getCorrespondingCardRange(cx.currentPlayable, p); CardEntity ent = null; boolean found = false; cardsReadLock.lock(); try { int remaining = r.getLength(); for (Iterator<CardEntity> iter = cards.listIterator(r.getStart()); !found && remaining > 0; remaining--) { ent = iter.next(); if (ent.getValue() == c) found = true; } } finally { cardsReadLock.unlock(); } if (found) { ent.setShow(true); if (cx.choosingFaceUp) { removeCardFromHandAndPutOnFaceUp(p, ent); //playerIndices[p.getPlayerId()].getFaceUpRange().getLength() would work as well as p.getFaceUp().size() //but this way doesn't need cardsReadLock to be locked (remember, we're in the game loop thread) ent.mark(getFaceUpCardLocation(p, p.getFaceUp().size() - 1), getRotation(p), 1); } else { removeCardFromPlayerAndPutOnDiscardPile(cx, p, ent); //discardPileEntitiesRange.getLength() would work as well as model.discardPileSize() //but this way doesn't need cardsReadLock to be locked (remember, we're in the game loop thread) ent.mark(getDiscardPileLocation(model.discardPileSize() - 1), 0, 1); } ent.reset(); } }
5
public void setTargetPoint( EndPoint targetPoint ) { ConnectionArray array = null; if( this.targetPoint != null ){ removeChild( this.targetPoint ); array = this.targetPoint.getArray(); if( array != null ){ array.remove( this.targetPoint ); } this.targetPoint.setConnection( null ); } this.targetPoint = targetPoint; if( this.targetPoint != null ){ this.targetPoint.setConnection( this ); addChild( targetPoint ); if( array != null ){ array.add( this.targetPoint ); } } }
4
public NodeSetTransferable(NodeSet nodeSet) { super(nodeSet.toString()); this.nodeSet = nodeSet; }
0
public AsetInterface shortestPath() { VertexInterface r, pivot; for (VertexInterface x : gi.getGraph()) { pi.setPoids(x, (int) Integer.MAX_VALUE / 2); // je divise par 2 parce que Integer.MAX_VALUE+1=Integer.MIN_VALUE } r = gi.getDeparture(); pivot = r; int n = gi.getGraph().size(); for (int j = 1; j < n; j++) { for (VertexInterface y : this.removeNonPreviousVertex(asi,pivot)){ // le poids de l'arc p(pivot,y) est forcement 1 puisaue le test de parente a deja ete fait int futurPoidsY = pi.getPoids(y) + 1; if(futurPoidsY < pi.getPoids(y)){ pi.setPoids(y, futurPoidsY); //instruction du pere de y... machin... } pivot = asi.getMin(gi); asi.add(pivot); } } return asi; }
4
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaDificuldade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaDificuldade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaDificuldade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaDificuldade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaDificuldade().setVisible(true); } }); }
6
private Font updateFont() { String fontStr = (String) jlFont.getSelectedValue(); String styleStr = (String) jlFontStyle.getSelectedValue(); int style; int size = sizeValue[jlFontSize.getSelectedIndex()]; if (styleStr.equals("常规")) { style = Font.PLAIN; } else if (styleStr.equals("斜体")) { style = Font.ITALIC; } else if (styleStr.equals("粗体")) { style = Font.BOLD; } else { style = Font.ITALIC | Font.BOLD; } Font f = new Font(fontStr, style, size); // 删除线与下划线 String temp = (String) jlFont.getSelectedValue(); if (jcDelLine.isSelected()) { if (jcDownLine.isSelected()) { showJLabel.setText("<html><s><u>" + temp + "</u></s><html>"); } else if (!jcDownLine.isSelected()) { showJLabel.setText("<html><s>" + temp + "</s><html>"); } } else if (!jcDelLine.isSelected()) { if (jcDownLine.isSelected()) { showJLabel.setText("<html><u>" + temp + "</u><html>"); } else if (!jcDownLine.isSelected()) { showJLabel.setText(temp); } } // 颜色 int select = jComboBox.getSelectedIndex(); showJLabel.setForeground(colorValue[select]); return f; }
9
public void run() { while (thread != null && state == STATE_PLAYING && read != -1) { if (written >= read) { try { read = audioInputStream.read(buffer, 0, buffer.length); written = 0; } catch (IOException e) { e.printStackTrace(); } } if (read > written) { int temp = line.write(buffer, written, read-written); written += temp; } } if (state == STATE_PLAYING) { /* Wait until all data are played. This is only necessary because of the bug noted below. (If we do not wait, we would interrupt the playback by prematurely closing the line and exiting the VM.) */ line.drain(); // All data are played. We can close the shop. line.close(); stopButton.doClick(); } }
7
public void setName(String name) { this.name = name; }
0
public MP3Filter(boolean title, boolean artist, boolean caseSensitive, String searchString) { super(); filterList = new Vector<MP3Filter.BasicFilter>(); if (caseSensitive) { this.searchString = searchString; if (title) { filterList.add(new TitleFilter()); } if (artist) { filterList.add(new ArtistFilter()); } } else { this.searchString = searchString.toLowerCase(); if (title) { filterList.add(new TitleNcsFilter()); } if (artist) { filterList.add(new ArtistNcsFilter()); } } }
5
private void CancelTicketButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelTicketButtonActionPerformed int selRow = ViewHistoryTable.getSelectedRow(); if (selRow == -1) { jLabel1.setText("Please select a ticket to continue"); return; } jLabel1.setText("Ticket History"); String message = "Are you sure you want to delete? "; int reply = javax.swing.JOptionPane.showConfirmDialog(this, message, "Warning", javax.swing.JOptionPane.YES_NO_OPTION); if (reply == javax.swing.JOptionPane.YES_OPTION) { String ticketno = (String) ViewHistoryTable.getModel().getValueAt(selRow, 0); try { Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "oracle"); PreparedStatement ps = con.prepareStatement("select dfid,afid,ddate,adate,pid,seatingclass " + "from ticket where tid=?"); ps.setString(1, ticketno); ResultSet rs = ps.executeQuery(); if (rs.next()) { String fromTimeStamp = rs.getString(3).substring(0, 19); String toTimeStamp = rs.getString(4).substring(0, 19); Statement s = con.createStatement(); ResultSet r1 = s.executeQuery("select sysdate from dual"); r1.next(); if (rs.getDate(3).compareTo(r1.getDate(1)) < 0) { javax.swing.JOptionPane.showMessageDialog(this, "Cannot cancel ticket. Travel date is over!"); // con.close(); // return; } s = con.createStatement(); r1 = s.executeQuery("select flightno from flight where fid=" + rs.getString(1)); r1.next(); String FlightNo = r1.getString(1); s = con.createStatement(); if (rs.getInt(6) == 0) { s.executeUpdate("update particularflight set availeco=availeco+1 " + "where fid IN (select fid from flight where Flightno='" + FlightNo + "')" + "and to_char(depdate,'yyyy-mm-dd hh24:mi:ss')>='" + fromTimeStamp + "' " + "and to_char(arrdate,'yyyy-mm-dd hh24:mi:ss')<='" + toTimeStamp + "'"); } else if (rs.getInt(6) == 1) { s.executeUpdate("update particularflight set availbus=availbus+1 " + "where fid IN (select fid from flight where Flightno='" + FlightNo + "')" + "and to_char(depdate,'yyyy-mm-dd hh24:mi:ss')>='" + fromTimeStamp + "' " + "and to_char(arrdate,'yyyy-mm-dd hh24:mi:ss')<='" + toTimeStamp + "'"); } } Statement s = con.createStatement(); s.executeUpdate("delete from userticket where tid=" + ticketno); s.executeUpdate("delete from ticket where tid=" + ticketno); s.executeUpdate("delete from passenger where pid=" + rs.getInt(5)); javax.swing.JOptionPane.showMessageDialog(this, "Deleted"); con.close(); TicketHistoryButtonActionPerformed(evt); } catch (SQLException se) { System.out.println(se); } } }//GEN-LAST:event_CancelTicketButtonActionPerformed
7
static String nextBlackMove(){ if(!blackOpening.isEmpty()) return blackOpening.remove(0); else return null; }
1
public Game(List<User> u) { users = u; start = System.currentTimeMillis(); System.out.println("Game has been created."); System.out.println("Team 1: "); int sumaBlue = 0; float sredniaBlue = 0; int sumaPurple = 0; float sredniaPurple = 0; for(User user: users) { if(user.team == Teams.BLUE) { System.out.println(user.username+": "+user.mmr); sumaBlue += user.mmr; } } sredniaBlue = sumaBlue / (users.size()/2); System.out.println("Srednia: "+sredniaBlue); System.out.println("Team 2: "); for(User user: users) { if(user.team == Teams.PURPLE) { System.out.println(user.username+": "+user.mmr); sumaPurple += user.mmr; } } sredniaPurple = sumaPurple / (users.size()/2); System.out.println("Srednia: "+sredniaPurple); }
4
private static void mergeWithPrevVisibleNode(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) { Node currentNode = textArea.node; Node prevNode = tree.getPrevNode(currentNode); if (prevNode == null) { return; } // Abort if prevNode is not editable if (!prevNode.isEditable()) { return; } Node parent = currentNode.getParent(); // Get Text for nodes. String prevNodeText = prevNode.getValue(); String currentNodeText = currentNode.getValue(); String newPrevNodeText = prevNodeText + currentNodeText; // Put the Undoable onto the UndoQueue UndoableEdit undoableEdit = new UndoableEdit( prevNode, prevNodeText, newPrevNodeText, 0, prevNodeText.length(), 0, prevNodeText.length() ); CompoundUndoableReplace undoableReplace = new CompoundUndoableReplace(parent); undoableReplace.addPrimitive(new PrimitiveUndoableReplace(parent, currentNode, null)); CompoundUndoableImpl undoable = new CompoundUndoableImpl(true); undoable.addPrimitive(undoableReplace); undoable.addPrimitive(undoableEdit); undoable.setName("Merge with Previous Node"); tree.getDocument().getUndoQueue().add(undoable); undoable.redo(); }
2
private boolean getFilmography(int start, int end, StringBuilder sourceCode, String pattern) { boolean flag = true; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(sourceCode); m.region(start, end); while (m.find() && (end < sourceCode.indexOf("id=\"External_links\">") || sourceCode.indexOf("id=\"External_links\">") < 0)) { flag = false; int index = m.group().indexOf("<a href="); String address = "http://en.wikipedia.org"; for (int i = index + 9; m.group().charAt(i) != '\"' && m.group().charAt(i) != '&'; i++) { address += m.group().charAt(i); } filmography.push(address); System.out.println(address); } return flag; }
5
public PermissionRcon getRcon() throws DataLoadFailedException { return dataHolder.getRcon(); }
0
public void Loadfile(String xmlfile) { File file = new File(xmlfile); if (!file.exists()) return; Document doc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(file); doc.getDocumentElement().normalize(); } catch (Exception e) { throw new RuntimeException(e); } NodeList nodeLst = doc.getChildNodes(); List<Node> roots = new ArrayList<Node>(); for (int i = 0; i < nodeLst.getLength(); i++) { Node n = nodeLst.item(i); if(n.getNodeType()==Node.ELEMENT_NODE) { roots.add(n); } } if(roots.size()==0) { throw new RuntimeException("Found No top net in this file"); } else if(roots.size()>1) { throw new RuntimeException("Found multiple top net in this file"); } this.root = new XmlNode(roots.get(0)); vistDFS(root); }
6
public static boolean addNewDrug(NewDrugPage newDrug){ Drug newd = new Drug(); String quantity = newDrug.getdQuantity().getText(); int quant = Integer.parseInt(quantity); String cont = newDrug.getdControlled().getText(); String t= "true"; boolean controlledt=false; controlledt=cont.equals(t); newd.setDrugName(newDrug.getdName().getText()); newd.setDescription(newDrug.getdGeneral().getText()); newd.setQuantity(quant); newd.setControlFlag(controlledt); newd.setSideEffect(newDrug.getdSide().getText()); newd.setInterACtion("?"); if(DatabaseProcess.insert(newd)){ Gui.setCurrentDrug(newd); return true; } return false;}
1
@Override public void initialize(Vertex start) { }
0
private final AbstractTrack getTrack(int trackNr) { if(trackNr >= 0) this.trackNr = trackNr; switch(this.trackNr) { default: case 0: return this.testtrack; case 1: return this.otrack; case 2: break; case 3: break; case 4: break; } // return null; return this.testtrack; }
6
protected static Map<DeltaSQLStatementSnapshot, List<WaitEventForStatementTuple>> loadWaitEventsForStatements( List<DeltaSQLStatementSnapshot> worstStatements, Calendar startTime, Calendar stopTime, ProgressListener progressListener) { Map<DeltaSQLStatementSnapshot, List<WaitEventForStatementTuple>> result = new HashMap<>(); if (progressListener != null) { progressListener.setStartValue(0); progressListener.setEndValue(worstStatements.size()); progressListener.setCurrentValue(0); } int progressCounter = 0; List<DeltaSQLStatementSnapshot> missingWaitEventSqlStatements = new ArrayList<>(worstStatements); List<DeltaSQLStatementSnapshot> sqlStatementsToLoad = new ArrayList<>(); int numberStatements; while (missingWaitEventSqlStatements.size() > 0) { sqlStatementsToLoad.clear(); numberStatements = 0; Iterator<DeltaSQLStatementSnapshot> iterator = missingWaitEventSqlStatements.iterator(); while (iterator.hasNext() && numberStatements <= NUMBER_BIND_VARIABLES_SELECT_WAIT_EVENTS_SQL) { sqlStatementsToLoad.add(iterator.next()); numberStatements++; } // remove those statements from the initial for which the loading is // going on for (DeltaSQLStatementSnapshot statement : sqlStatementsToLoad) { missingWaitEventSqlStatements.remove(statement); } loadWaitEventsForSQLStatements(sqlStatementsToLoad, startTime, stopTime, result); progressCounter += sqlStatementsToLoad.size(); if (progressListener != null) { progressListener.setCurrentValue(progressCounter); } // sleep for 0.1 seconds so all the other tasks can do their // work try { Thread.sleep(100); } catch (InterruptedException e) { // we don't care for being interrupted } } if (progressListener != null) { progressListener.informFinished(); } return result; }
8
public long getLong(String key) throws JSONException { Object o = get(key); if(o==null) return 0; if(o instanceof String){ if(o.toString().length()>0){ return Long.valueOf((o.toString())); }else return 0; } return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(key); }
4
private GamePosition blockSeriesOfFourOrMoreInCheckMode(GameBoardMark playerMark) { int zero = 0; int upToSquaresPerSide, upToFive, upToSix; GamePosition position = new GamePosition(); GamePosition position2 = new GamePosition(); for (upToSix = 0; upToSix < 6; upToSix++) { for (upToSquaresPerSide = 0; upToSquaresPerSide < GameBoard.SQUARES_PER_SIDE; upToSquaresPerSide++) { gameBoard.resetAllMarksAlongAxesForFirstHalfOfBoard(marksByAxis); position = checkFor5AlongHorizAxis(playerMark, zero, upToSquaresPerSide, upToSix, position); if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 4), new MarksByAxisPositionPair(1, 1))) { return position; } position = checkFor5AlongVertAxis(playerMark, zero, upToSquaresPerSide, upToSix, position); if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 4), new MarksByAxisPositionPair(3, 1))) { return position; } } for (upToSquaresPerSide = 0; upToSquaresPerSide < 6; upToSquaresPerSide++) { gameBoard.resetAllMarksAlongAxesForFirstHalfOfBoard(marksByAxis); for (upToFive = 0; upToFive < 5; upToFive++) { position = checkFor5AlongDiagDownRightAxis(playerMark, zero, upToSquaresPerSide, upToFive, upToSix, position); position2 = checkFor5AlongDiagUpRightAxis(playerMark, zero, upToSquaresPerSide, upToFive, upToSix, position2); } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 4), new MarksByAxisPositionPair(1, 1))) { return position; } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 4), new MarksByAxisPositionPair(3, 1))) { return position2; } } } return GamePosition.nonePosition(); }
8
public Object match(PathPattern<ServletAction> pattern, PathInput input, MapHttpServletRequest request) { if (type == Type.DEPLOY) { try { Page page = pageClass.newInstance(); input.bind(page); pattern.match(input); request.setAttribute(AttributeNames.EXTRA_PATH, input.getRemaining()); return page; } catch (Exception ex) { throw new PatternException("Exception during invocation of page `" + pageClass + "`", ex); } } else { input.bind(request.getMutableMap()); pattern.match(input); request.setAttribute(AttributeNames.EXTRA_PATH, input.getRemaining()); return this; } }
2
public void handle(String line) { String[] message = line.split(" "); String command = message[0].toLowerCase(); for(int x = 0; x < message.length; x++) { // Misc.println(message[x]); } if(command.startsWith("oper")) { UserOper oper = new UserOper(server); oper.handleCommand(line); } else if(command.startsWith("QUIT")) { TextHandler th = new TextHandler(null); String reason = th.append(message, " "); UserQuit userQuit = new UserQuit(server, reason); } else if(command.startsWith("join")) { oper.sendWallop(message[1], "join"); } else if(command.startsWith("privmsg")) { UserPM userPm = new UserPM(server); userPm.handleCommand(line); } else if(command.startsWith("mode")) { UserMode uMode = new UserMode(server); uMode.handleCommand(line); } else if(command.startsWith("user")) { } }
7
public List<Booking> getStudentBookingsByDate(Student student, Calendar date) { List<Booking> b = new ArrayList<Booking>(); Iterator<Booking> iter; iter = bookings.iterator(); while (iter.hasNext()) { Booking booking = iter.next(); if ((booking.getDate().get(Calendar.DAY_OF_MONTH) == date .get(Calendar.DAY_OF_MONTH)) && booking.getDate().get(Calendar.MONTH) == date .get(Calendar.MONTH) && booking.getDate().get(Calendar.YEAR) == date .get(Calendar.YEAR) && (booking.getStudent().equals(student))) { b.add(booking); } } return b; }
5
public Label newLabel() { if (this.isDeleted) { final String s = "Cannot change a field once it has been marked " + "for deletion"; throw new IllegalStateException(s); } this.setDirty(true); return new Label(maxLabel++); }
1
private void cleanUpImports() { Integer dummyVote = new Integer(Integer.MAX_VALUE); SortedMap newImports = new TreeMap(comparator); List classImports = new LinkedList(); Iterator iter = imports.keySet().iterator(); while (iter.hasNext()) { String importName = (String) iter.next(); Integer vote = (Integer) imports.get(importName); if (!importName.endsWith(".*")) { if (vote.intValue() < importClassLimit) continue; int delim = importName.lastIndexOf("."); if (delim != -1) { /* * Since the imports are sorted, newImports already contains * the package if it should be imported. */ if (newImports.containsKey(importName.substring(0, delim) + ".*")) continue; /* * This is a single Class import, that is not superseeded by * a package import. Mark it for importation, but don't put * it in newImports, yet. */ classImports.add(importName); } else if (pkg.length() != 0) { /* * This is a Class import from the unnamed package. It must * always be imported. */ newImports.put(importName, dummyVote); } } else { if (vote.intValue() < importPackageLimit) continue; newImports.put(importName, dummyVote); } } imports = newImports; cachedClassNames = new Hashtable(); /* * Now check if the class import conflict with any of the package * imports. */ iter = classImports.iterator(); while (iter.hasNext()) { /* * If there are more than one single class imports with the same * name, exactly the first (in sorted order) will be imported. */ String classFQName = (String) iter.next(); if (!conflictsImport(classFQName)) { imports.put(classFQName, dummyVote); String name = classFQName.substring(classFQName .lastIndexOf('.') + 1); cachedClassNames.put(classFQName, name); } } }
9
public static void calculateSimilarities() { double sim; for (Integer user1 : userCommunity.keySet()) { for (Integer user2 : userCommunity.tailMap(user1, false).keySet()) { sim = computeSimilarity(user1, user2); // this is for user1's list if (userSimilarities.containsKey(user1)) { userSimilarities.get(user1).put(user2, sim); } else { LinkedHashMap<Integer, Double> s = new LinkedHashMap<Integer, Double>(); s.put(user2, sim); userSimilarities.put(user1, s); } // this is for user2's list if (userSimilarities.containsKey(user2)) { userSimilarities.get(user2).put(user1, sim); } else { LinkedHashMap<Integer, Double> s = new LinkedHashMap<Integer, Double>(); s.put(user1, sim); userSimilarities.put(user2, s); } } } }
4
public void init(PolicyFinder finder) { // now that we have the PolicyFinder, we can load the policies PolicyReader reader = new PolicyReader(finder, logger, schemaFile); Iterator it = policyList.iterator(); while (it.hasNext()) { String str = (String)(it.next()); AbstractPolicy policy = null; try { try { // first try to load it as a URL URL url = new URL(str); policy = reader.readPolicy(url); } catch (MalformedURLException murle) { // assume that this is a filename, and try again policy = reader.readPolicy(new File(str)); } // we loaded the policy, so try putting it in the collection if (! policies.addPolicy(policy)) if (logger.isLoggable(Level.WARNING)) logger.log(Level.WARNING, "tried to load the same " + "policy multiple times: " + str); } catch (ParsingException pe) { if (logger.isLoggable(Level.WARNING)) logger.log(Level.WARNING, "Error reading policy: " + str, pe); } } }
6
public void processEvent(Event event) { if (event.getType() == Event.COMPLETION_EVENT) { System.out.println(_className + ": Receive a COMPLETION_EVENT, " + event.getHandle()); return; } System.out.println(_className + ".processEvent: Received Login Response... "); if (event.getType() != Event.OMM_ITEM_EVENT) { System.out.println("ERROR: " + _className + " Received an unsupported Event type."); _mainApp.cleanup(-1); return; } OMMItemEvent ie = (OMMItemEvent)event; OMMMsg respMsg = ie.getMsg(); if (respMsg.getMsgModelType() != RDMMsgTypes.LOGIN) { System.out.println("ERROR: " + _className + " Received a non-LOGIN model type."); _mainApp.cleanup(-1); return; } if (respMsg.isFinal()) { System.out.println(_className + ": Login Response message is final."); GenericOMMParser.parse(respMsg); _mainApp.processLogin(false); return; } if ((respMsg.getMsgType() == OMMMsg.MsgType.STATUS_RESP) && (respMsg.has(OMMMsg.HAS_STATE)) && (respMsg.getState().getStreamState() == OMMState.Stream.OPEN) && (respMsg.getState().getDataState() == OMMState.Data.OK)) { System.out.println(_className + ": Received Login STATUS OK Response"); GenericOMMParser.parse(respMsg); _mainApp.processLogin(true); } else { System.out.println(_className + ": Received Login Response - " + OMMMsg.MsgType.toString(respMsg.getMsgType())); GenericOMMParser.parse(respMsg); } }
8
private BufferedImage putIntoImageCache(BufferedImage bim, int width, int height, boolean allowScaling) { // create new Image cache if needed. if (image == null) { image = new ImageCache(library); } boolean setIsScaledOnImageCache = false; if (allowScaling && scaleImages && !image.isScaled()) { boolean canScale = checkMemory( Math.max(width, bim.getWidth()) * Math.max(height, bim.getHeight()) * Math.max(4, bim.getColorModel().getPixelSize())); if (canScale) { // To limit the number of image file cache writes this scaling // algorithem works with the buffered image in memory bim = ImageCache.scaleBufferedImage(bim, width, height); setIsScaledOnImageCache = true; } } // The checkMemory call above can make us lose our ImageCache synchronized (imageLock) { if (image == null) { image = new ImageCache(library); } // cache the new image if (setIsScaledOnImageCache) image.setIsScaled(true); image.setImage(bim); // read the image from the cache and return to caller bim = image.readImage(); } return bim; }
7
private static List<List<Integer>> Bucketize(List<Integer> candidates, List<Long> primes, int primeSet) { ArrayList<List<Integer>> result = new ArrayList<List<Integer>>(); for (int i = 0; i < candidates.size(); i++) { Integer n1 = candidates.get(i); System.out.print("Candidate=" + n1); ArrayList<Integer> bucket = new ArrayList<Integer>(); for (int j = i + 1; j < candidates.size(); j++) { Integer n2 = candidates.get(j); if (IsConcatenablePrime(n1, n2, primes)) { bucket.add(n2); } } System.out.println(", Bucket size=" + bucket.size()); if (primeSet <= bucket.size()) { List<List<Integer>> partialResult = Bucketize(bucket, primes, primeSet - 1); for (Iterator<List<Integer>> it = partialResult.iterator(); it.hasNext();) { List<Integer> list = it.next(); list.add(0, n1); result.add(list); } } } if (result.isEmpty()) { result.add(new ArrayList<Integer>()); } return result; }
6
CPGreyBmp makeVertLinesTexture(int lineSize, int size) { CPGreyBmp texture = new CPGreyBmp(size, size); for (int i = 0; i < size * size; i++) { if (i % size >= lineSize) { texture.data[i] = (byte) 255; } } return texture; }
2
@Override public void reactOnCollision(ElementField element, CollisionMan.TYPE type) { if (_faced == null || !_faced.equals(element)) { if (element.mass() == MASS.INF_MASS) { collideWithUnmovableElement(element, type); } else { collideWithMovableElement(element, type); } _faced = element; } }
3
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_SPACE) { fire(); } if (key == KeyEvent.VK_LEFT) { dx = -1; } if (key == KeyEvent.VK_RIGHT) { dx = 1; } if (key == KeyEvent.VK_UP) { dy = -1; } if (key == KeyEvent.VK_DOWN) { dy = 1; } }
5
protected void generateClassFiles(ClassDoc[] arr, ClassTree classtree) { Arrays.sort(arr); for(int i = 0; i < arr.length; i++) { if (!(configuration.isGeneratedDoc(arr[i]) && arr[i].isIncluded())) { continue; } ClassDoc prev = (i == 0)? null: arr[i-1]; ClassDoc curr = arr[i]; ClassDoc next = (i+1 == arr.length)? null: arr[i+1]; try { if (curr.isAnnotationType()) { AbstractBuilder annotationTypeBuilder = configuration.getBuilderFactory() .getAnnotationTypeBuilder((AnnotationTypeDoc) curr, prev, next); annotationTypeBuilder.build(); } else { AbstractBuilder classBuilder = configuration.getBuilderFactory() .getClassBuilder(curr, prev, next, classtree); classBuilder.build(); } } catch (IOException e) { throw new DocletAbortException(e); } catch (DocletAbortException de) { throw de; } catch (Exception e) { e.printStackTrace(); throw new DocletAbortException(e); } } }
9
public static Cursor getCursor(int id) { Integer key = Integer.valueOf(id); Cursor cursor = m_idToCursorMap.get(key); if (cursor == null) { cursor = new Cursor(Display.getDefault(), id); m_idToCursorMap.put(key, cursor); } return cursor; }
1
private static int method516(char arg0[], int arg1) { for (int k = arg1; k < arg0.length && k >= 0; k++) { if (arg0[k] < '0' || arg0[k] > '9') { return k; } } return arg0.length; }
4
@Override public void keyPressed(KeyEvent e) { final int key = e.getKeyCode(); if (userName.isFocusOwner()) if (key == KeyEvent.VK_ENTER || key == KeyEvent.VK_TAB) { password.requestFocus(); return; } if (password.isFocusOwner()) if (key == KeyEvent.VK_ENTER || key == KeyEvent.VK_TAB) { login.doClick(); return; } }
6
@Override public void actionPerformed(ActionEvent ae) { if(ae.getSource() == btnSubmit){ CustomerDataSource cusDS = new CustomerDataSource(); if(!tfFName.getText().isEmpty() && !tfLName.getText().isEmpty() && !tfPhone.getText().isEmpty() && !cusDS.checkCustomerByPhone(tfPhone.getText())) { Customer c = new Customer(); c.setFirstName(tfFName.getText()); c.setLastName(tfLName.getText()); c.setAddress_one(tfAddress1.getText()); c.setAddress_two(tfAddress2.getText()); c.setCity(tfCity.getText()); c.setState(tfState.getText()); c.setZipCode(tfZipCode.getText()); c.setPhoneNumber(tfPhone.getText()); cusDS.createCustomer(c); if(c.getId()!=0) JOptionPane.showMessageDialog(this, "Adding " + c.getFirstName() + " " + c.getLastName() + " successful!"); else JOptionPane.showMessageDialog(this, "Adding " + c.getFirstName() + " " + c.getLastName() + " failed!"); tfFName.setText(""); tfLName.setText(""); tfAddress1.setText(""); tfAddress2.setText(""); tfCity.setText(""); tfState.setText(""); tfZipCode.setText(""); tfPhone.setText(""); }else if( !tfFName.getText().isEmpty() && !tfLName.getText().isEmpty() && cusDS.checkCustomerByPhone(tfPhone.getText())){ JOptionPane.showMessageDialog(this, "Phone \""+ tfPhone.getText() +"\" is already existed "); tfFName.setText(""); tfLName.setText(""); tfAddress1.setText(""); tfAddress2.setText(""); tfCity.setText(""); tfState.setText(""); tfZipCode.setText(""); tfPhone.setText(""); }else JOptionPane.showMessageDialog(this, "\"First Name\" or \"Last Name\" or \"Phone\" cannot be empty "); cusDS.close(); } }
9
@Test public void runTestButton1() throws IOException { InfoflowResults res = analyzeAPKFile("Callbacks_Button1.apk"); Assert.assertNotNull(res); Assert.assertEquals(1, res.size()); }
0
public static void readConfigDB() throws Exception { try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); InputStream in = new FileInputStream(configFile); if (in.available() == 0) { throw(new Exception("File not found or empty")); } XMLEventReader eventReader = inputFactory.createXMLEventReader(in); Map<String, String> newConfig = new HashMap<String, String>(); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { String ConfigSetting = ""; if (event.asStartElement().getName().getLocalPart() == ("config") || event.asStartElement().getName().getLocalPart() == ("root")) { event = eventReader.nextTag(); } String ConfigKey = event.asStartElement().getName().getLocalPart(); event = eventReader.nextEvent(); if (event.isEndElement()) { newConfig.put(ConfigKey, null); logger.info("Config: " + ConfigKey + " (not set)"); } else { try { ConfigSetting = event.asCharacters().getData(); newConfig.put(ConfigKey, ConfigSetting); logger.info("Config: " + ConfigKey + "=" + ConfigSetting); } catch (Exception ex) { logger.warn("Parse error", ex); } } } } setConfigDB(newConfig); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XMLStreamException e) { e.printStackTrace(); } }
9
public void paintComponent(Graphics g) { //хз, прокатит ли с 2 параметрами super.paintComponent(g); x_centr = this.getWidth() / 2; y_centr = this.getHeight() / 2; Graphics2D g2d = (Graphics2D) g; this.setBackground(Color.WHITE); g2d.setColor(Color.BLACK); // тестовая отрисовочка /* g2d.drawLine(m.details[0].x[0]*10, m.details[0].y[0]*10, m.details[0].x[1]*10, m.details[0].y[1]*10); g2d.drawLine(0, y_centr, this.getWidth(), y_centr); g2d.drawLine(x_centr, 0, x_centr, this.getHeight());*/ if(paintMode == -1) { for (int i = 0; i < m.numDetails; i++) { for (int j = 0; j < m.details[i].numPoints; j++) { if (j != m.details[i].numPoints - 1) { g2d.drawLine(x_centr + m.details[i].x[j] * mxy, y_centr - m.details[i].y[j] * mxy, x_centr + m.details[i].x[j + 1] * mxy, y_centr - m.details[i].y[j + 1] * mxy); } else { g2d.drawLine(x_centr + m.details[i].x[j] * mxy, y_centr - m.details[i].y[j] * mxy, x_centr + m.details[i].x[0] * mxy, y_centr - m.details[i].y[0] * mxy); } } } } else if(paintMode >= 0) { for (int j = 0; j < m.details[paintMode].numPoints; j++) { if (j != m.details[paintMode].numPoints - 1) { g2d.drawLine(x_centr + m.details[paintMode].x[j] * mxy, y_centr - m.details[paintMode].y[j] * mxy, x_centr + m.details[paintMode].x[j + 1] * mxy, y_centr - m.details[paintMode].y[j + 1] * mxy); } else { g2d.drawLine(x_centr + m.details[paintMode].x[j] * mxy, y_centr - m.details[paintMode].y[j] * mxy, x_centr + m.details[paintMode].x[0] * mxy, y_centr - m.details[paintMode].y[0] * mxy); } } } }
7
private boolean checkLinesAndColums(String curBoard) { for (int i = 0; i < 3; ++i) { if (curBoard.charAt(i * boardSize) == curBoard.charAt(boardSize * i + 1) && curBoard.charAt(i * boardSize) == curBoard.charAt(boardSize * i + 2) && curBoard.charAt(i * boardSize) != ' ') { return true; } if (curBoard.charAt(i) == curBoard.charAt(boardSize + i) && curBoard.charAt(i) == curBoard.charAt(boardSize * 2 + i) && curBoard.charAt(i) != ' ') { return true; } } return false; }
7
public void updateLevel(Game game) { this.game = game; for (Tile t : tiles) { t.tick(game); if (game.getInput().rightButton && t.isContainsMouse()) rightClick(t); if (game.getInput().leftButton && t.isContainsMouse()) leftClick(t); } } // End update
5
@Override public int compareTo(Object o) { if (this == o) return 0; if (o instanceof CommandBase) { CommandBase cmd = (CommandBase) o; int c = (name.compareTo(cmd.name)); if (c != 0) return c; if (options.size() != cmd.options.size()) return options.size() - cmd.options.size(); for (CommandOption commandOption : options) { if (!cmd.options.contains(commandOption)) return Integer.MAX_VALUE; } return 0; } return toString().compareTo(o.toString()); }
6
public Node selectRandomNode(Node nodeIn) { List<Node> selectCollection = new ArrayList<Node>(); if (nodeIn.getType() == NodeType.INPUT) { selectCollection.addAll(outNodes); selectCollection.addAll(hiddenNodes); } else if (nodeIn.getType() == NodeType.OUTPUT) { selectCollection.addAll(inNodes); selectCollection.addAll(hiddenNodes); } else if (nodeIn.getType() == NodeType.HIDDEN) { //selectCollection.addAll(inNodes); selectCollection.addAll(hiddenNodes); selectCollection.remove(nodeIn); selectCollection.addAll(outNodes); } int choosenIndex = -1; while (choosenIndex == -1 & !selectCollection.isEmpty()) { choosenIndex = getIndex4RandomOutNode(selectCollection, nodeIn); } if (choosenIndex == -1) { return nodeIn; } else { return selectCollection.get(choosenIndex); } }
5
private void initCheckSavingReq() { if (theWorker == null) { state = UIState.CHECKSAVINGREQUIREMENT; lblStatus.setText("Checking files on disk"); theWorker = new MyWorker(rootPage, JobType.CHECKSAVINGREQUIREMENT, true); theWorker.execute(); } }
1
public void println(String text) { if(frame == null) buildGUI(); area.append("\n" + text); }
1
public void gen() { for (int i = 0; i < tiles.length; i++) { for (int j = 0; j < tiles[0].length; j++) { if (r.nextInt(10) > 1) { tiles[i][j] = new Grass(i * 64, j * 64); } else { tiles[i][j] = new Stone(i * 64, j * 64, this); } } } }
3
@SuppressWarnings("unchecked") public static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) { if (isEmpty(source) || isEmpty(candidates)) { return null; } for (Object candidate : candidates) { if (source.contains(candidate)) { return (E) candidate; } } return null; }
5
public IVPNumber add(IVPNumber number, Context context, DataFactory factory, HashMap map) { IVPNumber result = factory.createIVPNumber(); map.put(result.getUniqueID(), result); if(getValueType().equals(IVPValue.INTEGER_TYPE) && number.getValueType().equals(IVPValue.INTEGER_TYPE)){ int resultInt = context.getInt(getUniqueID()) + context.getInt(number.getUniqueID()); result.setValueType(IVPValue.INTEGER_TYPE); context.addInt(result.getUniqueID(), resultInt); }else{ double resultDouble = 0.0; if(getValueType().equals(IVPValue.DOUBLE_TYPE) && number.getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultDouble = context.getDouble(getUniqueID()) + context.getDouble(number.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultDouble = context.getDouble(getUniqueID()) + context.getInt(number.getUniqueID()); }else{ resultDouble = context.getInt(getUniqueID()) + context.getDouble(number.getUniqueID()); } } context.addDouble(result.getUniqueID(), resultDouble); result.setValueType(IVPValue.DOUBLE_TYPE); } return result; }
5
private void dropElement() throws Exception { Session s = HibernateUtil.getSessionFactory().getCurrentSession(); try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Object obj = ois.readObject(); if(obj instanceof NetworkHardware) { s.beginTransaction(); s.delete(obj); s.getTransaction().commit(); out.writeBytes(acceptCmd + "\n"); toLog("Element deleted."); } } catch(ConstraintViolationException e) { out.writeBytes(failCmd + "\n"); s.getTransaction().rollback(); } catch(Exception e) { throw new Exception("Data transfer error." ); } }
3
public static void main(String[] args){ // Example of creating a set and partitioning it: System.out.println("Starting by creating a partitioned set of 4 elements:"); PartitionListElement<String> list = new PartitionListElement<String>(); list.add("one"); list.add("two"); list.add("three"); list.add("four"); // Call the make partition function to put into all possible partitions PartitionList<String> results = OrderConstrainedPartitionList.makePartitions( list); // Display results for(PartitionListItem<String> newPartition : results){ System.out.println("Partition: " + newPartition.toString()); } System.out.println("Now creating a second partitioned set of 3 elements."); // Next we create a second partitioned set PartitionListElement<String> list2 = new PartitionListElement<String>(); list2.add("A"); list2.add("B"); list2.add("C"); PartitionList<String> results2 = OrderConstrainedPartitionList.makePartitions( list2); // Display results for(PartitionListItem<String> newPartition : results2){ System.out.println("Partition: " + newPartition); } // Join both sets PartitionList<String> results3 = OrderConstrainedPartitionList.joinSets(results, results2); System.out.println("Showing all merged sets:"); for(PartitionListItem<String> newPartition: results3){ System.out.println("Partition: " + newPartition); } System.out.println("Now creating a Third partitioned set of 3 elements."); // Next we create a second partitioned set PartitionListElement<String> list3 = new PartitionListElement<String>(); list3.add("z"); list3.add("y"); list3.add("x"); PartitionList<String> results4 = OrderConstrainedPartitionList.makePartitions( list3); // Display results for(PartitionListItem<String> newPartition : results4){ System.out.println("Partition: " + newPartition); } try{ // Create file FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); // Join all sets PartitionList<String> results6 = OrderConstrainedPartitionList.joinPartitionedSets(results3, results4); System.out.println("Saving all merged sets to out.txt"); for(PartitionListItem<String> newPartition: results6){ //System.out.println("Partition: " + newPartition); out.write("Partition: " + newPartition + "\n"); } out.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } System.out.println("Save is complete. "); }
6
public void close() throws XmlRpcException { if (xmlRpcClient != null) { xmlRpcClient.close(); } }
1
public void Partition(int[] a, int k, int begin, int end) { int left = begin; int right = end; int temp = a[left]; while (left < right) { while (left < right && a[right] >= temp) right--; if (left < right) a[left] = a[right]; while (left < right && a[left] < temp) left++; if (left < right) a[right] = a[left]; } a[left] = temp; if (k < left) Partition(a, k, begin, left - 1); else if (k > left) Partition(a, k, left + 1, end); }
9
private void process(File aFile) { if(aFile.isFile()){ String name = aFile.getName(); if (name.substring(name.length()-4).equals("java")){ try { if (!name.equals("Command.java") && !name.equals("CommandFactory.java")){ String pack = aFile.getPath().replaceAll("\\\\", "."); pack = pack.substring(6, pack.lastIndexOf('.')); Class<?> cl = Class.forName(pack); Command command = (Command) cl.newInstance(); String description = command.getDescription(); String code = command.getCode(); boolean enabled = command.isEnabled(); client.send("69aR~" + code + "~" + description + "~" + enabled + "~\n"); } } catch (Exception e) { e.printStackTrace(); } } } else if (aFile.isDirectory()) { File[] listOfFiles = aFile.listFiles(); if(listOfFiles!=null) { for (int i = 0; i < listOfFiles.length; i++) process(listOfFiles[i]); } } }
9
public void addSlower(double x, double y){ Slower t = new Slower(new Vertex2D(x, y), getGos()); if (!touchesAnything(t)) if (y >= .5 * Tower.HEIGHT && y <= TDPanel.HEIGHT - .5 * Tower.HEIGHT && (y < TDPanel.HEIGHT / 3 - .5 * Tower.HEIGHT || y > 2 * TDPanel.HEIGHT / 3 + .5 * Tower.HEIGHT) && x > .5 * Tower.WIDTH && x < TDPanel.WIDTH - .5 * Tower.WIDTH) if (wallet.changeBananas(-Slower.PRIZE)) getGos().add(t); }
8
@Override public double[] intersect(Ray ray) { // Algorithm: http://www.ray-tracing.ru/articles213.html Vector3 T = ray.getFrom().subtract(v0); Vector3 Q = T.crossProduct(e1); Vector3 P = ray.getDirection().crossProduct(e2); double pDotE1 = P.dotProduct(e1); if (pDotE1 >= MathUtils.GEOMETRY_THRESHOLD || pDotE1 <= -MathUtils.GEOMETRY_THRESHOLD) { double u = P.dotProduct(T) / pDotE1; double v = Q.dotProduct(ray.getDirection()) / pDotE1; if (u >= 0 && v >= 0 && u + v <= 1) { double distance = Q.dotProduct(e2) / pDotE1; return new double[] {distance}; } } return EMPTY; }
5
private void dropAlarm() throws Exception { Session s = HibernateUtil.getSessionFactory().getCurrentSession(); try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Object obj = ois.readObject(); if(obj instanceof Alarm) { s.beginTransaction(); s.delete(obj); s.getTransaction().commit(); out.writeBytes(acceptCmd + "\n"); toLog("Alarm deleted."); } } catch(ConstraintViolationException e) { out.writeBytes(failCmd + "\n"); s.getTransaction().rollback(); } catch(Exception e) { throw new Exception("Data transfer error." ); } }
3
List<Position> getNeighbours() { List<Position> list = new ArrayList<Position>(); if(this.north != null && this.north.data != '*') { list.add(this.north); } if(this.south != null && this.south.data != '*') { list.add(this.south); } if(this.east != null && this.east.data != '*') { list.add(this.east); } if(this.west != null && this.west.data != '*') { list.add(this.west); } return list; }
8
@Override public boolean equals(Object other) { if (other == null || !(other instanceof Word)) return false; else { Word otherWord = (Word) other; return Arrays.equals(stresses, otherWord.stresses) && Arrays.equals(units, otherWord.units); } }
3
public void playSound(String path){ try { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(path).getAbsoluteFile()); if (path == "TurretPurchase.wav"){ Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } else{ Clip bgm = AudioSystem.getClip(); bgm.open(audioInputStream); bgm.start(); bgm.loop(bgm.LOOP_CONTINUOUSLY); } } catch(Exception ex) { System.out.println("Error with playing sound."); ex.printStackTrace(); } }
2
public void setPheromoneLevel(int pheromone) { amtPheromone = pheromone; pheromoneLabel.setText("Ph: " + pheromone); if (pheromone >= 1000) setBackground(PHEROMONE_1000); else if (pheromone >= 800) setBackground(PHEROMONE_800); else if (pheromone >= 600) setBackground(PHEROMONE_600); else if (pheromone >= 400) setBackground(PHEROMONE_400); else if (pheromone >= 200) setBackground(PHEROMONE_200); else if (pheromone > 0) setBackground(PHEROMONE_0); else if (getBackground().equals(QUEEN_NODE_COLOR)) setBackground(QUEEN_NODE_COLOR); else setBackground(OPEN_NODE_COLOR); }
7
public String getType() { return "mealy"; }
0
private SensorSingleData process(List<Double> measurementValues) { if (isInitialised) { List<Double> correctedValues = new ArrayList<Double>(); for (int i = 0; i < measurementValues.size(); i++) { // compute the Kalman gain double kalmanGain = predictedVariances.get(i) / (predictedVariances.get(i) + noiseVariances.get(i)); // update the sensor prediction with the measurement double correctedValue = Constants.FILTER_GAIN * predictedValues.get(i) + (1.0 - Constants.FILTER_GAIN) * measurementValues.get(i) + kalmanGain * (measurementValues.get(i) - predictedValues.get(i)); // predict next variance and value predictedVariances.add(i, predictedVariances.get(i) * (1.0 - kalmanGain)); predictedValues.add(i, correctedValue); correctedValues.add(i, correctedValue); } sensorSingleData .setAccX(correctedValues.get(0)) .setAccY(correctedValues.get(1)) .setAccZ(correctedValues.get(2)); return sensorSingleData; } else { return init(measurementValues); } }
2
public final void actionPerformed(ActionEvent e) { JTextComponent textComponent = getTextComponent(e); if (textComponent instanceof RTextArea) { RTextArea textArea = (RTextArea)textComponent; //System.err.println("Recordable action: " + getMacroID()); if (RTextArea.isRecordingMacro() && isRecordable()) { int mod = e.getModifiers(); // We ignore keypresses involving ctrl/alt/meta if they are // "default" keypresses - i.e., they aren't some special // action like paste (e.g., paste would return Ctrl+V, but // its action would be "paste-action"). String macroID = getMacroID(); //System.err.println(macroID); //System.err.println("... " + (mod&ActionEvent.ALT_MASK)); //System.err.println("... " + (mod&ActionEvent.CTRL_MASK)); //System.err.println("... " + (mod&ActionEvent.META_MASK)); if (!DefaultEditorKit.defaultKeyTypedAction.equals(macroID) || ( (mod&ActionEvent.ALT_MASK)==0 && (mod&ActionEvent.CTRL_MASK)==0 && (mod&ActionEvent.META_MASK)==0) ) { String command = e.getActionCommand(); RTextArea.addToCurrentMacro(macroID, command); //System.err.println("... recording it!"); } } actionPerformedImpl(e, textArea); } }
7
@Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((loc == null) ? 0 : loc.hashCode()); return result; }
1
public void buildAssociations(Instances instances) throws Exception { Frame valuesFrame = null; /* Frame to display the current values. */ /* Initialization of the search. */ if (m_parts == null) { m_instances = new Instances(instances); } else { m_instances = new IndividualInstances(new Instances(instances), m_parts); } m_results = new SimpleLinkedList(); m_hypotheses = 0; m_explored = 0; m_status = NORMAL; if (m_classIndex == -1) m_instances.setClassIndex(m_instances.numAttributes()-1); else if (m_classIndex < m_instances.numAttributes() && m_classIndex >= 0) m_instances.setClassIndex(m_classIndex); else throw new Exception("Invalid class index."); // can associator handle the data? getCapabilities().testWithFail(m_instances); /* Initialization of the window for current values. */ if (m_printValues == WINDOW) { m_valuesText = new TextField(37); m_valuesText.setEditable(false); m_valuesText.setFont(new Font("Monospaced", Font.PLAIN, 12)); Label valuesLabel = new Label("Best and worst current values:"); Button stop = new Button("Stop search"); stop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { /* Signal the interruption to the search. */ m_status = STOP; } }); valuesFrame = new Frame("Tertius status"); valuesFrame.setResizable(false); valuesFrame.add(m_valuesText, BorderLayout.CENTER); valuesFrame.add(stop, BorderLayout.SOUTH); valuesFrame.add(valuesLabel, BorderLayout.NORTH); valuesFrame.pack(); valuesFrame.setVisible(true); } else if (m_printValues == OUT) { System.out.println("Best and worst current values:"); } Date start = new Date(); /* Build the predicates and launch the search. */ m_predicates = buildPredicates(); beginSearch(); Date end = new Date(); if (m_printValues == WINDOW) { valuesFrame.dispose(); } m_time = new Date(end.getTime() - start.getTime()); }
7
public boolean isObstacle(Coordinate coord) { if (getCell(coord).getElementType() == ElementType.WATER || getCell(coord).getElementType() == ElementType.LEAFWATER || getCell(coord).getElementType() == ElementType.TRUNK || getCell(coord).getElementType() == ElementType.WALL) return true; else return false; }
4
static final int method2960(boolean bool, int i) { if (i >= -16) aFloatArray6865 = null; anInt6870++; int i_0_ = ByteBuffer.anInt7207; while_128_: do { do { if ((i_0_ ^ 0xffffffff) != -1) { if (i_0_ != 1) { if (i_0_ == 2) break; break while_128_; } } else { if (bool) return 0; return Class348_Sub40_Sub8.anInt9157; } return Class348_Sub40_Sub8.anInt9157; } while (false); return 0; } while (false); return 0; }
7
public ArrayList<ArrayList<String>> partition(String s) { int length = s.length(); //initial a indicator: boolean[][] indicator = new boolean[length][]; for(int i = 0; i < length; ++i){ indicator[i] = new boolean[length]; for(int j = 0; j < length; ++j){ indicator[i][j] = false; } } for(int i = length - 1; i >= 0; --i){ for(int j = i; j < length; ++j){ indicator[i][j] = (s.charAt(i) == s.charAt(j)) && ((j - i) < 2 || (indicator[i+1][j-1])); } } ArrayList<ArrayList<String>> result = helper1(s, indicator, 0); for(int i = 0; i < result.size(); ++i){ Collections.reverse(result.get(i)); } // printMatrix(indicator); return result; }
7
public static boolean canAfford(CostType cost) { if(wood >= cost.wood && stone >= cost.stone && gold >= cost.gold && food >= cost.food) { return true; } return false; }
4
public void submit(Integer partId) { System.out.println(String.format("==\n== [nlp] Submitting Solutions" + " | Programming Exercise %s\n==", homework_id())); partId = promptPart(); List<String> partNames = validParts(); if(!isValidPartId(partId)) { System.err.println("!! Invalid homework part selected."); System.err.println(String.format("!! Expected an integer from 1 to %d.", partNames.size() + 1)); System.err.println("!! Submission Cancelled"); return; } String [] loginPassword = loginPrompt(); String login = loginPassword[0]; String password = loginPassword[1]; if(login == null || login.equals("")) { System.out.println("!! Submission Cancelled"); return; } System.out.print("\n== Connecting to Coursera ... "); // Setup submit list List<Integer> submitParts = new ArrayList<Integer>(); if(partId == partNames.size() + 1) { for(int i = 1; i < partNames.size() + 1; i++) { submitParts.add(new Integer(i)); } } else { submitParts.add(new Integer(partId)); } for(Integer part : submitParts) { // Get Challenge String [] loginChSignature = getChallenge(login, part); if(loginChSignature == null) { return; } login = loginChSignature[0]; String ch = loginChSignature[1]; String signature = loginChSignature[2]; String ch_aux = loginChSignature[3]; // Attempt Submission with Challenge String ch_resp = challengeResponse(login, password, ch); String result = submitSolution(login, ch_resp, part.intValue(), output(part, ch_aux), source(part), signature); if(result == null) { result = "NULL RESPONSE"; } if (result.trim().equals("Exception: We could not verify your username / password, please try again. (Note that your password is case-sensitive.)")) { System.out.println("== The password is not your login, but a 10 character alphanumeric string displayed on the top of the Assignments page."); } else { System.out.println(String.format( "\n== [nlp] Submitted Homework %s - Part %d - %s", homework_id(), part, partNames.get(part - 1))); System.out.println("== " + result.trim()); } } }
9
public void saveAnimation() { BufferedReader reader; try { reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/sprites")); String line; StringBuilder fileContent = new StringBuilder(); String newLine = null; while((line = reader.readLine()) != null) { String[] temp = line.split(";"); if(temp[0].matches(sprite.getName())) { newLine = sprite.getName() + ";" + textField_11.getText() + ";" + textField_12.getText(); fileContent.append(newLine); fileContent.append(System.getProperty("line.separator")); } else { fileContent.append(line); fileContent.append(System.getProperty("line.separator")); } } if(newLine == null) { newLine = sprite.getName() + ";" + textField_11.getText() + ";" + textField_12.getText(); fileContent.append(newLine); fileContent.append(System.getProperty("line.separator")); } BufferedWriter out = new BufferedWriter(new FileWriter(System.getProperty("resources") + "/database/sprites")); out.write(fileContent.toString()); out.close(); reader.close(); } catch (FileNotFoundException e) { System.out.println("The sprite database has been misplaced!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Sprite database failed to load!"); e.printStackTrace(); } }
5
public static void main(String[] args) { if(args.length == 0){ System.out.println("Specification and assembly filenames not given."); System.exit(0); } else if(args.length == 1){ System.out.println("Assembly file not given."); System.out.println("Specification file: " + args[0]); System.exit(0); } else if(args.length > 2){ System.out.println("Too many arguments provided."); System.exit(0); } if(!(args[0].endsWith(".txt") && args[1].endsWith(".txt"))){ System.out.println("Input is limited to two .txt files."); System.exit(0); } FileParser file = new FileParser(args[0], args[1]); DataSource data = file.getData(); new Assembler(data); }
5
private void updateJson() { //Worlds List<DynmapWorld> dynmapWorlds = new ArrayList<>(); List<Component> components = new ArrayList<>(); ArrayList<String> addedComponents = new ArrayList<>(); config.setConfighash(0); String temp = gson.toJson(config); for (DynmapServer dynmapServer : net.cubespace.dynmap.multiserver.Main.getDynmapServers()) { dynmapWorlds.addAll(dynmapServer.getWorlds()); for (Component component : dynmapServer.getComponents()) { if (component != null) { if (!addedComponents.contains(component.type)) { addedComponents.add(component.type); components.add(component); } } } } config.setWorlds(dynmapWorlds); config.setComponents(components); config.setCoreversion(net.cubespace.dynmap.multiserver.Main.getCoreVersion()); config.setDynmapversion(net.cubespace.dynmap.multiserver.Main.getDynmapVersion()); if (!responseStr.equals(temp)) { config.setConfighash(0); responseStr = gson.toJson(config); start = System.currentTimeMillis(); } }
5
public AdaptedRandomDoubles(int count) { this.count = count; }
0
public BladesSword(){ this.name = Constants.BLADES_SWORD; this.attackScore = 11; this.attackSpeed = 10; this.money = 300; }
0
static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
9
public static int cal(int i, int j, int cur) { if (min[i][j] != 0) return min[i][j]; int up, down, left, right; up = down = left = right = 0; if (i - 1 >= 0 && m[i][j] < m[i - 1][j]) up = cal(i - 1, j, cur + 1); if (j - 1 >= 0 && m[i][j] < m[i][j - 1]) left = cal(i, j - 1, cur + 1); if (i + 1 < rows && m[i][j] < m[i + 1][j]) down = cal(i + 1, j, cur + 1); if (j + 1 < cols && m[i][j] < m[i][j + 1]) right = cal(i, j + 1, cur + 1); return (min[i][j] = 1+max(up, down, left, right)); }
9
private boolean isValid(String head) { if( head.length() > 3 ) return false; int n = Integer.valueOf( head ); int length = head.length(); if( n >= 100 && n <= 255 ) return true; if( n >= 10 && n < 100 && length == 2 ) return true; if( n >= 0 && n <= 9 && length == 1 ) return true; return false; }
9
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((sourceName == null) ? 0 : sourceName.hashCode()); return result; }
1
public UpgradeType getType() { return type; }
0
@Override public double evaluate(int[][] board) { int max = 0; int diffCnt = 0; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { max = Math.max(max, board[i][j]); if (cnt[board[i][j]] == 0) { diffCnt++; } cnt[board[i][j]]++; } } int target = -1; int order = 0; for (int i = max; i >= 2; i >>= 1) { if (cnt[i] >= 2) { target = i; break; } if(cnt[i] > 0) { order++; } } for (int i = max; i >= 2; i >>= 1) { cnt[i] = 0; } if (target == -1) { return 0; } return diffCnt - order; }
8