text
stringlengths
14
410k
label
int32
0
9
private String introduceUser(String input) { String userQuestion = ""; if (getChatCount() < 4) { if (getChatCount() == 0) { myUser.setUserName(input); userQuestion = "How many girls have you kissed?"; } else if (getChatCount() == 1) { try { myUser.setGirlsKissed(Integer.parseInt(input)); } catch (NumberFormatException p) { return "Sorry, didn't catch that. How many girls have you kissed?"; } userQuestion = "Thats a lot! Do you like Soccer? (Yes/No)"; } else if (getChatCount() == 2) { myUser.setLikesSoccer(input.toLowerCase().startsWith("y") ? true : false); userQuestion = myUser.isLikesSoccer() ? "That's great me too! " : "That's too bad... "; userQuestion = userQuestion.concat("Do you like to make out with girls?"); } else if (getChatCount() == 3) { myUser.setLikesToMakeOut(input.toLowerCase().startsWith("y") ? true : false); userQuestion = "Very nice. Just be careful out there......"; } } return userQuestion; }
9
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed String text = txtBuscar.getText().toString(); LibrosCRUD libro = new LibrosCRUD(MyConnection.getConnection()); ArrayList<Libros> listado = new ArrayList<>(); Libros l = null; if(text.isEmpty()){ listado = libro.getAll(); }else{ String option = jComboBox1.getSelectedItem().toString(); switch(option){ case "Codigo": l = new Libros(text, null, null, null, 0); listado = libro.getById(l); break; case "Nombre": l = new Libros(null, text, null, null, 0); listado = libro.getByNombre(l); break; case "Titulo": l = new Libros(null, null, text, null, 0); listado = libro.getByTitulo(l); break; case "Autor": l = new Libros(null, null, null, text, 0); listado = libro.getByAutor(l); break; } } if(listado.isEmpty()){ JOptionPane.showMessageDialog(this, "No se encontraron coincidencias"); }else{ volcarDatos(listado); } }//GEN-LAST:event_btnBuscarActionPerformed
6
public SingleTreeNode treePolicy() { SingleTreeNode cur = this; while (!cur.state.isGameOver() && cur.m_depth < ROLLOUT_DEPTH) { if (cur.notFullyExpanded()) { return cur.expand(); } else { SingleTreeNode next = cur.uct(); //SingleTreeNode next = cur.egreedy(); cur = next; } } return cur; }
3
public static void createClusters(final PrintWriter writer, final PgSchema oldSchema, final PgSchema newSchema, final SearchPathHelper searchPathHelper) { for (final PgTable newTable : newSchema.getTables()) { final PgTable oldTable; if (oldSchema == null) { oldTable = null; } else { oldTable = oldSchema.getTable(newTable.getName()); } final String oldCluster; if (oldTable == null) { oldCluster = null; } else { oldCluster = oldTable.getClusterIndexName(); } final String newCluster = newTable.getClusterIndexName(); if ((oldCluster == null && newCluster != null) || (oldCluster != null && newCluster != null && newCluster.compareTo(oldCluster) != 0)) { searchPathHelper.outputSearchPath(writer); writer.println(); writer.print("ALTER TABLE "); writer.print(PgDiffUtils.getQuotedName(newTable.getName())); writer.print(" CLUSTER ON "); writer.print(PgDiffUtils.getQuotedName(newCluster)); writer.println(';'); } } }
8
@EventHandler(priority=EventPriority.MONITOR) void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().getTitle().equals(name)) { event.setCancelled(true); int slot = event.getRawSlot(); if (slot >= 0 && slot < size && optionNames[slot] != null) { Plugin plugin = this.plugin; OptionClickEvent e = new OptionClickEvent((Player)event.getWhoClicked(), slot, optionNames[slot]); handler.onOptionClick(e); if (e.willClose()) { final Player p = (Player)event.getWhoClicked(); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { p.closeInventory(); } }, 1); } if (e.willDestroy()) { destroy(); } } } }
6
private void createQuizSlide(Attributes attrs) { quizSlide = new QuizSlide(quizSlideDef); // loop through all attributes, setting appropriate values for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName(i).equals("id")) quizSlide.setId(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("backgroundcolor")) quizSlide.setBkCol(new Color(Integer.valueOf(attrs.getValue(i) .substring(1), 16))); else if (attrs.getQName(i).equals("duration")) quizSlide.setDuration(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("nextslideid")) quizSlide.setNext(Integer.valueOf(attrs.getValue(i))); } }
5
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(ConsultaArbitro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ConsultaArbitro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ConsultaArbitro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ConsultaArbitro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { try { new ConsultaArbitro().setVisible(true); } catch (IllegalAccessException | ClassNotFoundException | SQLException ex) { Logger.getLogger(ConsultaArbitro.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(ConsultaArbitro.class.getName()).log(Level.SEVERE, null, ex); } } }); }
8
public String nextToken() throws JSONException { char c; char q; StringBuilder sb = new StringBuilder(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
public void testStackArray(){ while(!stk.isEmpty()){ System.out.println(stk.pop()); } }
1
public void renderLayer(Graphics g, ArrayList<Task> lastLayer, ArrayList<Task> currentLayer, int currentX, int currentY) { // renders layers after the first layer; if (currentLayer.isEmpty()) { // this later is empty, this is the end // close it off for (Task current : lastLayer) { int[] currentCoords = getNodeLocation(current); // xCoord = currentCoords[0], y = cC[1] int x = currentCoords[0]; int y = currentCoords[1]; g.drawLine(x, y, x + 20, y); g.drawLine(x + 20, y, x + 20, currentY); } g.drawLine(currentX + 20, currentY, 700, currentY); } else { // this layer has tasks to render //cycle through nodes in this layer currentX += 20; // push forward ArrayList<Task> nextLayer = new ArrayList<Task>(); // tasks dependant on this layer ArrayList<Task> toRender = new ArrayList<Task>(); // to render this interation for (Task current : currentLayer) { // check is current is dependant on previous level ArrayList<Task> currentDependants = current.getDependentNodes(); boolean doesDepend = false; for (Task task : currentDependants) { if (lastLayer.contains(task)) { doesDepend = true; } // else stay false } if (doesDepend == false) { // doesn't depend on nodes that exist nextLayer.add(current); } else { toRender.add(current); } } int n = toRender.size(); int l = (n - 1) * (30 + 40); // box height = 80, gap = 30 int y = currentY - (l / 2); // set y pointer for (Task task : toRender) { // these tasks will be rendered g.drawLine(currentX, y, currentX + 20, y); drawNode(g, currentX + 20, y - 20, task); // render task if (n != 1) { y += (l / (n - 1)); // l is distance between tasks } // else no need to increase // link to old nodes ArrayList<Task> dependants = task.getDependentNodes(); for (Task currentDependant : dependants) { int[] currentCoords = getNodeLocation(currentDependant); // xCoord = currentCoords[0], y = cC[1] int xCoord = currentCoords[0]; int yCoord = currentCoords[1]; g.drawLine(xCoord, yCoord, xCoord + 20, yCoord); g.drawLine(xCoord + 20, yCoord, xCoord + 20, y); } } renderLayer(g, toRender, nextLayer, currentX + 140, currentY); } }
9
public ShapeConstru(SimpleFeature f, String tipo) { super(f, tipo); shapeId = "CONSTRU" + super.newShapeId(); // Para agrupar geometrias segun su codigo de masa codigoMasa = ((String) f.getAttribute("MASA")).replaceAll("[^\\p{L}\\p{N}]", "")+"-"; this.poligons = new ArrayList<LineString>(); // Constru.shp trae la geometria en formato MultiPolygon if ( f.getDefaultGeometry().getClass().getName().equals("com.vividsolutions.jts.geom.MultiPolygon")){ // Poligono, trae el primer punto de cada poligono repetido al final. Geometry geom = (Geometry) f.getDefaultGeometry(); // Cogemos cada poligono del shapefile (por lo general sera uno solo // que puede tener algun subpoligono) for (int x = 0; x < geom.getNumGeometries(); x++) { Polygon p = (Polygon) geom.getGeometryN(x); // Obtener el outer LineString outer = p.getExteriorRing(); poligons.add(outer); // Comprobar si tiene subpoligonos for (int y = 0; y < p.getNumInteriorRing(); y++) poligons.add(p.getInteriorRingN(y)); } } else System.out.println("["+new Timestamp(new Date().getTime())+"] Formato geometrico " + f.getDefaultGeometry().getClass().getName() +" desconocido del shapefile CONSTRU"); // Inicializamos las listas this.nodes = new ArrayList<List<Long>>(); this.ways = new ArrayList<List<Long>>(); for(int x = 0; x < poligons.size(); x++){ List<Long> lw = new ArrayList<Long>(); List<Long> ln = new ArrayList<Long>(); nodes.add(ln); ways.add(lw); } // Los demas atributos son metadatos y de ellos sacamos refCatastral = (String) f.getAttribute("REFCAT"); constru = (String) f.getAttribute("CONSTRU"); // Si queremos coger todos los atributos del .shp /*this.atributos = new ArrayList<ShapeAttribute>(); for (int x = 1; x < f.getAttributes().size(); x++){ atributos.add(new ShapeAttribute(f.getFeatureType().getDescriptor(x).getType(), f.getAttributes().get(x))); }*/ }
4
public void serialize(ByteBuffer buffer) { _LOGGER.log(Level.FINE, "Serializing response: " + _status + "/" + _errorCode); buffer.clear(); buffer.putInt(_status); if(_status != STATUS_OK) { buffer.putInt(_errorCode); return; } else if(_message != null) { buffer.putInt(_message.getSender()); buffer.putInt(_message.getReceiver()); buffer.putInt(_message.getMessage().getBytes().length); buffer.put(_message.getMessage().getBytes()); } else if (_waitingQueues != null) { int size = _waitingQueues.size(); buffer.putInt(size); for (int waitingQueueId : _waitingQueues) { buffer.putInt(waitingQueueId); } } }
4
public Praying getPraying(String name) { if(prayings.contains(name)) return null; for(Praying p : prayings) if(p.getName().equalsIgnoreCase(name)) return p; return null; }
3
public void arrange(int iterationCounter){ Collections.sort(books); BookNode bi, bj; float vx, vy, vLen; if(books.size()>1){ for(int i=0; i<books.size();i++){ bi=books.get(i); for(int j=i+1;j<books.size();j++){ if(i!=j){ bj = books.get(j); float dx = bj.getX() - bi.getX(); float dy = bj.getY() - bi.getY(); float r = bi.getPaddedRadius() + bj.getPaddedRadius(); float d = (dx*dx) + (dy*dy); if (d < (r * r) - 0.01 ) { vx = dx; vy = dy; vLen = (float)Math.sqrt(vx*vx + vy*vy); vx=vx/vLen; vy=vy/vLen; float temp=(float)((r-Math.sqrt(d))*0.5); vx=vx*temp; vy=vy*temp; bj.setX(bj.getX()+vx); bj.setY(bj.getY()+ vy); bi.setX(bi.getX()-vx); bi.setY(bi.getY()-vy); } books.set(j, bj); } } books.set(i,bi); } //Contract float damping = (float)0.1/(float)(iterationCounter); for (int i=0; i<books.size(); i++) { BookNode c = books.get(i); vx = c.getX(); vy = c.getY(); vx=vx*damping; vy=vy*damping; c.setX(c.getX() - vx); c.setY(c.getY() - vy); } }else if(books.size()>0){ books.get(0).setX(0); books.get(0).setY(0); } }
7
public void startAuction(){ if((super.getOutputPort() == null) || super.getAuctionID() == -1){ System.err.println(this.get_name() + "Error starting the auction. " + "The output port used by the auction is null or" + "the auctioneer's ID was not provided!"); return; } synchronized(syncStep){ // default values setClosed(false); // broadcast a message to all bidders informing about the auction MessageInformStart mia = new MessageInformStart(super.getAuctionID(), super.getAuctionProtocol()); broadcastMessage(mia); setStartingTime(GridSim.clock()); onStart(++this.currentRound); // creates events for timeout of the rounds for(int i=this.currentRound;i<=this.totalRound;i++){ super.send(super.get_id(), durationOfRounds * i, AuctionTags.AUCTION_TIMEOUT, new Integer(i)); } } }
3
private void writeIndexKeys() { String mapperName = table.getDomName() + "Dao"; StringBuilder sb = new StringBuilder(); for ( IndexNode node : table.getIndexList() ) { String methodName = "readByIndex" + toTitleCase( node.getIndexName()); String param = ""; for(Column col : node.getColumnList()){ param += col.getFldType() + " " + col.getFldName() + ", "; } param = param.substring( 0, param.length() - 2 ); sb.append( TAB + "public " + table.getDomName() + " " + methodName + "( " ); sb.append( param + " ) throws BoException" ); sb.append( "{\n" ); sb.append( TAB + TAB + "SqlSession session = null;\n" ); sb.append( TAB + TAB + table.getDomName() + " result;\n" ); sb.append( TAB + TAB + "try {\n" ); sb.append( TAB + TAB + TAB + "session = SessionFactory.getSession();\n" ); sb.append( TAB + TAB + TAB + mapperName ); sb.append( " mapper = session.getMapper( " + mapperName + ".class );\n" ); param = ""; for(Column col : node.getColumnList()){ param += col.getFldName() + ", "; } param = param.substring( 0, param.length() - 2 ); sb.append( TAB + TAB + TAB + "result = mapper." + methodName +"( " + param + " );\n" ); sb.append( TAB + TAB + TAB + "session.commit();\n\n" ); sb.append( TAB + TAB + "} catch ( Exception e ) {\n" ); sb.append( TAB + TAB + TAB + "session.rollback();\n" ); sb.append( TAB + TAB + TAB + "throw new BoException( e );\n\n" ); sb.append( TAB + TAB + "} finally { \n" ); sb.append( TAB + TAB + TAB + "if ( session != null )\n" ); sb.append( TAB + TAB + TAB + TAB + "session.close();\n" ); sb.append( TAB + TAB + "}\n\n" ); sb.append( TAB + TAB + "return result;\n" ); sb.append( TAB + "}\n" ); } write( sb.toString() ); }
3
public FastqBuilder withSequence(final String sequence) { if( sequence == null ) { throw new IllegalArgumentException("sequence must not be null"); } if( this.sequence == null ) { this.sequence = new StringBuilder(sequence.length()); } this.sequence.replace(0, this.sequence.length(), sequence); return this; }
2
final Interface18_Impl3 method3855(Class304 class304, int i, int i_54_, float[] fs, boolean bool, int i_55_, int i_56_, int i_57_) { try { anInt9890++; if (i_56_ != 2) ((NativeOpenGlToolkit) this).aMapBuffer9913 = null; if (!aBoolean9926 && (!Class192.method1436(60, i) || !Class192.method1436(-73, i_57_))) { if (aBoolean9919) return new Class14_Sub4(this, class304, i, i_57_, fs, i_54_, i_55_); Class14_Sub1 class14_sub1 = new Class14_Sub1(this, class304, Class68.aClass68_1187, Class33.method340(i, (byte) 108), Class33.method340(i_57_, (byte) 108)); class14_sub1.method240(i_55_, (byte) -126, fs, class304, 0, i_54_, 0, i, i_57_); return class14_sub1; } return new Class14_Sub1(this, class304, i, i_57_, bool, fs, i_54_, i_55_); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("bga.WC(" + (class304 != null ? "{...}" : "null") + ',' + i + ',' + i_54_ + ',' + (fs != null ? "{...}" : "null") + ',' + bool + ',' + i_55_ + ',' + i_56_ + ',' + i_57_ + ')')); } }
8
public static void main(String[] args){ int max = 0; for(int i=1;i<100;i++){ for(int j=1;j<100;j++){ int dSum = digitSum(power(i, j)); if(dSum>max) max = dSum; } } System.out.println(max); }
3
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TarifasParqueaderosPK)) { return false; } TarifasParqueaderosPK other = (TarifasParqueaderosPK) object; if ((this.codIdparqueadero == null && other.codIdparqueadero != null) || (this.codIdparqueadero != null && !this.codIdparqueadero.equals(other.codIdparqueadero))) { return false; } if ((this.codIdtarifa == null && other.codIdtarifa != null) || (this.codIdtarifa != null && !this.codIdtarifa.equals(other.codIdtarifa))) { return false; } return true; }
9
public static int getInt(byte[] b, int offset) { if (isBlank(b)) { throw new IllegalArgumentException("blank byte array."); } if (offset < 0) { throw new IllegalArgumentException("invalid array offset:" + offset + "."); } int out = b[0] < 0 ? -1 : 0; for (int l = b.length - offset, i = l < INTEGER_BYTE_LEN ? INTEGER_BYTE_LEN - l : 0, off = offset - i; i < INTEGER_BYTE_LEN; i++) { out <<= Byte.SIZE; out |= (b[off + i] & 0xff); } return out; }
5
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
@Override public TheaterSeatsReplyMessage seatsRequest(int clientID, int theaterID) throws RemoteException{ TheaterSeats seats = null; TheaterSeatsReplyMessage reply = null; seats = cache.getTheaterSeats(theaterID); if(seats == null){ //Creates a communication channel between this and the DBServer CommunicationController databaseCC; try { databaseCC = new CommunicationController(new Socket(this.dbAddress, this.dbPort)); } catch (UnknownHostException e) { return new TheaterSeatsReplyMessage(theaterID, null); } catch (IOException e) { return new TheaterSeatsReplyMessage(theaterID, null); } reply = Skeleton.getTheater(new TheaterSeatsRequestMessage(theaterID), databaseCC); databaseCC.closeConnection(); //If has not occurred an error it puts the theaters seats to cache. seats = reply.getTheaterSeats(); if(seats != null){ //Updates the seats so they are reserved int reservation = seats.getFirstFreeSeat(); if(reservation != -1) seats.setSeatStatus(reservation/40, reservation%40, 'R'); reply.setReservation(reservation); cache.addTheaterSeats(seats); cache.addReservedSeat(clientID, theaterID, reservation); } } else{ //Updates the seats so they are reserved int reservation = seats.getFirstFreeSeat(); if(reservation != -1){ seats.setSeatStatus(reservation/40, reservation%40, 'R'); cache.addReservedSeat(clientID, theaterID, reservation); } reply = new TheaterSeatsReplyMessage(theaterID, seats); reply.setReservation(reservation); } //If an error occurred the reply == null and it is returned return reply; }
6
public ArrayList<Cell> convert(String s){ //create the cell list to populate ArrayList<Cell> cellList = new ArrayList<Cell>(); //break the string into the words //for now force to lower case s.toLowerCase(); String [] words = s.split(" "); //for the words in for (int i=0 ; i < words.length; i++){ //curr is the current cell Cell curr = new Cell(); //first check the more advanced grade 2 scan grade2Scan(curr, words[i]); //not in grade 2 so split into grade 1 if (curr.isSpace()){ ArrayList<Cell> wordTranslate = new ArrayList<Cell>(); //for the letters in word for(int j=0; j<words[i].length(); j++){ //get the braille conversion Cell wCurr = new Cell(); grade1Scan(wCurr, words[i].charAt(j)); wordTranslate.add(wCurr); } for (int k=0; k<wordTranslate.size(); k++){ // add the results to the real list cellList.add(wordTranslate.get(k)); } } //analysis complete, add to the list if the cell is not a space if(!(curr.isSpace())){ cellList.add(curr); } //add a space after the word Cell spaceCell = new Cell(); cellList.add(spaceCell); } //return the cell list return cellList; }
5
void mesajGeldi(String mesaj) throws Exception, Throwable{ System.out.println(mesaj); JSONObject json = new JSONObject(mesaj); String tip = json.get(MESAJ_TIPI).toString(); switch (tip) { case MT_GUC_ACIK: gucAc(json); break; case MT_GUC_KAPALI: gucKapat(json); break; case MT_GIRIS_YAP: girisYap(json); break; case MT_MASA_AC: masaAcMaSorgusu(json); break; case MT_SIPARIS: siparisEkle(json); break; case MT_SOHBET: sohbetMesajGonder(json); break; } }
6
@Override public void execute() { Logger.getInstance().info("Executing method " + getMethod()); try { rawExecutionResult = Arietta.rpc.callMethod(getMethod(), getParams()); if (rawExecutionResult == null) { Logger.getInstance().error("Got null result for " + getMethod()); throw new InvalidResponseException("Got null result"); } Logger.getInstance().debug("Got result for " + getMethod()); runInNewThread(new Runnable() { @Override public void run() { try { handleResult(); } catch (InvalidRpcDataException e) { Arietta.handleRemoteException(e); } } }); } catch (InvalidResponseException e) { Arietta.handleRemoteException(e); } catch (ConnectionLostException e) { Arietta.handleConnectException(e); } /** * If handleResult here will add another task to queue, RPC thread may * be deadlocked by itself, so let's run this method in EventQueue * thread. * * EventQueue.invokeLater(new Runnable() { * * @Override public void run() { try { handleResult(rawExecutionResult); * } catch (ClassCastException e) { * Arietta.handleException(e); } } }); */ }
4
public void updateP2(String stats) { p2.setText(stats); }
0
public static boolean isNumber(int c) { return isDigit(c) || c == '-' || c == '+' || c == '.'; }
3
String createDotString(String... dotStrings) { final StringBuilder sb = new StringBuilder(); double nodesep = getHorizontalDzeta(); if (nodesep < getMinNodeSep()) { nodesep = getMinNodeSep(); } final String nodesepInches = SvekUtils.pixelToInches(nodesep); // System.err.println("nodesep=" + nodesepInches); double ranksep = getVerticalDzeta(); if (ranksep < getMinRankSep()) { ranksep = getMinRankSep(); } final String ranksepInches = SvekUtils.pixelToInches(ranksep); // System.err.println("ranksep=" + ranksepInches); sb.append("digraph unix {"); SvekUtils.println(sb); for (String s : dotStrings) { if (s.startsWith("ranksep")) { sb.append("ranksep=" + ranksepInches + ";"); } else if (s.startsWith("nodesep")) { sb.append("nodesep=" + nodesepInches + ";"); } else { sb.append(s); } SvekUtils.println(sb); } sb.append("remincross=true;"); SvekUtils.println(sb); sb.append("searchsize=500;"); SvekUtils.println(sb); sb.append("compound=true;"); SvekUtils.println(sb); if (dotData.getRankdir() == Rankdir.LEFT_TO_RIGHT) { sb.append("rankdir=LR;"); SvekUtils.println(sb); } root.printCluster1(sb, allLines); for (Line line : lines0) { line.appendLine(sb); } root.fillRankMin(rankMin); root.printCluster2(sb, allLines); printMinRanking(sb); for (Line line : lines1) { line.appendLine(sb); } SvekUtils.println(sb); sb.append("}"); return sb.toString(); }
8
public void draw(UShape ushape, double x, double y, ColorMapper mapper, UParam param, Graphics2D g2d) { final UEllipse shape = (UEllipse) ushape; g2d.setStroke(new BasicStroke((float) param.getStroke().getThickness())); if (shape.getStart() == 0 && shape.getExtend() == 0) { final Shape ellipse = new Ellipse2D.Double(x, y, shape.getWidth(), shape.getHeight()); // Shadow if (shape.getDeltaShadow() != 0) { drawShadow(g2d, ellipse, shape.getDeltaShadow(), dpiFactor); } if (param.getBackcolor() != null) { g2d.setColor(mapper.getMappedColor(param.getBackcolor())); g2d.fill(ellipse); } if (param.getColor() != null) { g2d.setColor(mapper.getMappedColor(param.getColor())); g2d.draw(ellipse); } } else { final Shape arc = new Arc2D.Double(x, y, shape.getWidth(), shape.getHeight(), shape.getStart(), shape .getExtend(), Arc2D.OPEN); if (param.getColor() != null) { g2d.setColor(mapper.getMappedColor(param.getBackcolor())); g2d.fill(arc); } if (param.getColor() != null) { g2d.setColor(mapper.getMappedColor(param.getColor())); g2d.draw(arc); } } }
7
@Override public void update(Observable o, Object arg) { if (arg instanceof WorldState) { WorldState worldState = (WorldState) arg; switch (worldState) { // When the timer hit 0 case TIME_OVER: timeOver(); break; // Set when the player has 0 health and 0 shield etc. IE, dead. case PLAYER_DIED: playerDied(); break; // Set when the player completes the level case LEVEL_COMPLETED: // etc logic here break; } } }
4
public void saveStats(BlackjackGui gui) { switch(gui.numPlayers) { case 1: p1wins = players.get(0).getWins(); p1losses = players.get(0).getLosses(); p1won = players.get(0).getMoneyWon(); p1lost = players.get(0).getMoneyLost(); p1money = players.get(0).getMoney(); try { File file1 = new File(gui.p1Name + ".txt"); FileWriter writer1 = new FileWriter(file1); writer1.write(p1wins + " " + p1losses + " " + p1won + " " + p1lost + " " + p1money + "\n"); writer1.close(); } catch(Exception ex) { } break; case 2: p1wins = players.get(0).getWins(); p1losses = players.get(0).getLosses(); p1won = players.get(0).getMoneyWon(); p1lost = players.get(0).getMoneyLost(); p2wins = players.get(1).getWins(); p2losses = players.get(1).getLosses(); p2won = players.get(1).getMoneyWon(); p2lost = players.get(1).getMoneyLost(); p1money = players.get(0).getMoney(); p2money = players.get(1).getMoney(); try { File file1 = new File(gui.p1Name + ".txt"); FileWriter writer1 = new FileWriter(file1); writer1.write(p1wins + " " + p1losses + " " + p1won + " " + p1lost + " " + p1money + "\n"); writer1.close(); File file2 = new File(gui.p2Name + ".txt"); FileWriter writer2 = new FileWriter(file2); writer2.write(p2wins + " " + p2losses + " " + p2won + " " + p2lost + " " + p2money + "\n"); writer2.close(); } catch(Exception ex) { } break; case 3: p1wins = players.get(0).getWins(); p1losses = players.get(0).getLosses(); p1won = players.get(0).getMoneyWon(); p1lost = players.get(0).getMoneyLost(); p2wins = players.get(1).getWins(); p2losses = players.get(1).getLosses(); p2won = players.get(1).getMoneyWon(); p2lost = players.get(1).getMoneyLost(); p3wins = players.get(2).getWins(); p3losses = players.get(2).getLosses(); p3won = players.get(2).getMoneyWon(); p3lost = players.get(2).getMoneyLost(); p1money = players.get(0).getMoney(); p2money = players.get(1).getMoney(); p3money = players.get(2).getMoney(); try { File file1 = new File(gui.p1Name + ".txt"); FileWriter writer1 = new FileWriter(file1); writer1.write(p1wins + " " + p1losses + " " + p1won + " " + p1lost + " " + p1money + "\n"); writer1.close(); File file2 = new File(gui.p2Name + ".txt"); FileWriter writer2 = new FileWriter(file2); writer2.write(p2wins + " " + p2losses + " " + p2won + " " + p2lost + " " + p2money + "\n"); writer2.close(); File file3 = new File(gui.p3Name + ".txt"); FileWriter writer3 = new FileWriter(file3); writer3.write(p3wins + " " + p3losses + " " + p3won + " " + p3lost + " " + p3money + "\n"); writer3.close(); } catch(Exception ex) { } break; } }
6
private void buyCompany(int id, HttpServletResponse response, RequestContext rc) throws IOException, SQLException { int requesterId = rc.getId(); int compNum = UserManager.countCompanies(requesterId); long reregTax = CompanyManager.companyCost(compNum + 1); if(reregTax != -1) { if(!CompanyManager.ownsCompany(id, requesterId)) { long curBalance = rc.getMoney(); long sellCost = CompanyManager.getSellCost(id); if(curBalance >= sellCost) { if(reregTax < curBalance - sellCost) { try { NotificationManager.generateBuy(id, requesterId); CompanyManager.buyCompany(id, requesterId); } catch(IllegalArgumentException e) { response.sendRedirect("teams.jsp?err=permdenied"); return; } response.sendRedirect("team.jsp?id=" + id); } else { response.sendRedirect("teams.jsp?err=poor"); } } else { response.sendRedirect("teams.jsp?err=poor"); } } else { response.sendRedirect("teams.jsp?err=permdenied"); } } else { response.sendRedirect("teams.jsp?err=full"); } }
5
public void newRandomConnection(Neuron neuron){ try{ for(int i=0;i<neurons.size();i++) neurons.get(i).findDepth(); }catch(StackOverflowError e){ System.out.println("There was a stack overflow because of findDepth :: SpeciationNeuralNetwork"); new CMDTester(this); System.exit(0); } if(neuron instanceof OutputNeuron){ mutate(); return; } neurons=Neuron.sortByDepth(neurons); int index=0; for(;index<neurons.size()&&neurons.get(index)!=neuron;index++){} int maxRan=(new Random()).nextInt(neurons.size()-index); if(maxRan==0){ // recurrent connection to self mutate(); return; } if(neuron.existsConnection(neurons.get(index+maxRan))){ // the connection already exists mutate(); return; } if(neurons.indexOf(neuron) >= index+maxRan){ System.out.println("ERROR :: SpeciationNeuralNetwork 211"); } makeConnection(neuron,neurons.get(index+maxRan)); }
8
public void Guerra() { General.Reclutar(exerc1, pantalla); General.Reclutar(exerc2, pantalla); Formacio(exerc1); Formacio(exerc2); while (exerc1.size() != 0 && exerc2.size() != 0) { if (General.Acorrer(exerc1, pantalla) == exerc1.size()) { Formacio(exerc1); } if (General.Acorrer(exerc2, pantalla) == exerc2.size()) { Formacio(exerc2); } comprovaMort(); } }
4
private static void register(Class<? extends Packet> packet) { try { short id = packet.getField("ID").getShort(null); if(id < 0) System.err.println("Packet ID undefined: " + packet.getSimpleName()); else if(packetTypes.containsKey(id)) System.err.println("Duplicate Packet ID: " + packet.getSimpleName() + " (0x" + Integer.toHexString(id) + " = " + packetTypes.get(id).getSimpleName() + ")"); else packetTypes.put(id, packet); } catch (Exception e) { e.printStackTrace(); } }
4
public boolean setINodeParam(String resource_id, String inode_id, String paramKey, String paramValue) { boolean isUpdated = false; int count = 0; try { while((!isUpdated) && (count != retryCount)) { if(count > 0) { //System.out.println("iNODEUPDATE RETRY : region=" + region + " agent=" + agent + " plugin" + plugin); Thread.sleep((long)(Math.random() * 1000)); //random wait to prevent sync error } isUpdated = IsetINodeParam(resource_id, inode_id, paramKey, paramValue); count++; } if((!isUpdated) && (count == retryCount)) { System.out.println("GraphDBEngine : setINodeParam : Failed to add node in " + count + " retrys"); } } catch(Exception ex) { System.out.println("GraphDBEngine : setINodeParam : Error " + ex.toString()); } return isUpdated; }
6
public static int insertMstxSort(String sort) { int result = 0; int sid = getMaxNumber("mstx_sort"); updateMaxNumber(8);// 将该字段值加1 Connection con = DBUtil.getConnection(); PreparedStatement pstmt = null; try { pstmt = con.prepareStatement("insert into mstx_sort(sid,info_sort) values(" + sid + ", '" + sort + "')"); result = pstmt.executeUpdate(); } catch (Exception e) {// 捕获异常 e.printStackTrace();// 打印异常信息 } finally { try { if (pstmt != null) { pstmt.close(); pstmt = null; } } catch (Exception e) { e.printStackTrace(); } try { if (con != null) { con.close(); con = null; } } catch (Exception e) { e.printStackTrace(); } } return result; }
5
private void connectTo(AbstractUnit next, int posConn){ if(selected instanceof IMultipuleOutputUnit){ Object result = JOptionPane.showInputDialog( tulip.Tulip.mainFrame, "Which connection?", PropagatorUnit.lastConnectedUnit ); if( result != null){ try{ int n = Integer.parseInt((String) result); PropagatorUnit.lastConnectedUnit = (PropagatorUnit.lastConnectedUnit+1 == n)?PropagatorUnit.lastConnectedUnit+1:n; PropagatorUnit.lastConnectedUnit++; if(n>-1 && n <((IMultipuleOutputUnit)selected).getNumberOfNext()){ ((IMultipuleOutputUnit)selected).setNextUnit(next, AbstractUnit.Operand.values()[posConn], n); tulip.Tulip.mainFrame.getGrapPanel().repaint(); } }catch(NumberFormatException e1){ } } }else{ ((IOutputUnit)selected).setNextUnit(next, AbstractUnit.Operand.values()[posConn]); tulip.Tulip.mainFrame.getGrapPanel().repaint(); } }
6
@Override public Class getColumnClass(int column) { Class returnValue; if ((column >= 0) && (column < getColumnCount())) { if (getValueAt(0, column) == null) { return String.class; } returnValue = getValueAt(0, column).getClass(); } else { returnValue = Object.class; } return returnValue; }
3
@Override public void messageReceived(Message msg) { /** * same as GridScheduler */ if(msg instanceof ControlMessage){ ControlMessage controlMessage = (ControlMessage)msg; // resource manager wants to join this grid scheduler // when a new RM is added, its load is set to Integer.MAX_VALUE to make sure // no jobs are scheduled to it until we know the actual load if (controlMessage.getType() == ControlMessageType.ResourceManagerJoin){ resourceManagerLoad.put(controlMessage.getUrl(), Integer.MAX_VALUE); } // resource manager wants to offload a job to us if (controlMessage.getType() == ControlMessageType.AddJob){ jobQueue.add(controlMessage.getJob()); } // resource manager wants to offload a job to us if (controlMessage.getType() == ControlMessageType.ReplyLoad){ resourceManagerLoad.put(controlMessage.getUrl(),controlMessage.getILoad()); } } /** * */ else{ //"normal message" //TODO } }
4
public void resume_ingress() { for (ConnectionProcessor pipe : pipes) { pipe.resume_ingress(); } }
1
public BrickFireplace(TextGame _game) { super("Brick Fireplace", ""); this.game = _game; this.addAction(new ActionInitial("hit") { @Override public Result execute(Actor actor) { if (((Player) actor).getLocation().hasOne("brick fireplace")) { return new ResultPartial(true, " -- With what? ", (ActionContinued) BrickFireplace.this.getAction("hit_with")); } else { return new ResultGeneric(false, "I don't see any "+game.getItem("fireplace").getName()); } } }); this.addAction(new ActionContinued("hit_with") { @Override public Result execute(Actor actor, String feedback) { if (((Player) actor).getLocation().hasOne("brick fireplace")) { if (game.matchItem(feedback) == game.getItem("sledge hammer") && ((Player) actor).hasOne("sledge hammer") && game.getItem("fireplace").getData("broken") == null) { game.getItem("fireplace").changeName("Broken Fireplace"); // the fireplace gets a new "look" game.getPlace("_fireplace").changeName("Broken Fireplace"); // the fireplace place name must be changed game.getItem("fireplace").setData("broken", new Boolean(true)); // mark the fireplace as broken game.getPlace("_fireplace").setConnection(game.getDirection("north"), game.getPlace("secret passage")); // new hole leads to secret passage! return new ResultGeneric(true, ((Player) actor).getLocation().getInitialAction("look").execute(actor).getMessage()); } return new ResultGeneric(false, "Nothing happened\n"); } else { return new ResultGeneric(false, "I don't see any "+game.getItem("fireplace").getName()); } } }); this.addAction(new ActionInitial("go") { @Override public Result execute(Actor actor) { if (((Player) actor).getLocation().hasOne("brick fireplace")) { if (game.getItem("_fire").getData("out") != null) { // go fireplace leads to broken fireplace place... ((Player) actor).setLocation(game.getPlace("_fireplace")); return new ResultGeneric(true, ((Player) actor).getLocation().getInitialAction("look").execute(actor).getMessage()); } else { // game over game.end(false); return new ResultGeneric(false, " You have Burned to Death"); } } else { return new ResultGeneric(false, "You can't go there"); } } }); }
7
public void setPass(String pass) { this.pass = pass; }
0
private void newFileInProject() { FileDialog dialog; if (isCurrentItemLocal()) dialog = new FileDialog(shell, FileDialog.Mode.SAVE, getCurrentTreeDir()); else dialog = new FileDialog(shell, FileDialog.Mode.SAVE, getCurrentTreeSym()); ArrayList<SymitarFile> files = dialog.open(); if (files.size() > 0) { SymitarFile file = files.get(0); TreeItem[] selection = tree.getSelection(); if (selection.length != 1) return; TreeItem cur = selection[0]; while (cur != null && !(cur.getData() instanceof Project)) cur = cur.getParentItem(); if (cur == null) return; Project proj = (Project) cur.getData(); SessionError error = file.saveFile(""); if (error == SessionError.NONE) { if (!proj.hasFile(file)) { proj.addFile(file); TreeItem item = new TreeItem(cur, SWT.NONE); item.setText(file.getName()); item.setData(file); item.setImage(getFileImage(file)); if (proj.isLocal()) ProjectManager.saveProjects(proj.getDir()); else ProjectManager.saveProjects(proj.getSym()); } openFile(file); tree.notifyListeners(SWT.Selection, null); } } }
9
public List<POMInfo> searchMatchingPOMsIgnoreVersion(Dependency dependency) { List<POMInfo> result = new ArrayList<POMInfo>(); POMInfo pom = searchMatchingPOM(dependency); if (pom != null) { result.add(pom); return result; } for (POMInfo testPom : resolvedPoms.values()) { if (testPom.getThisPom().equalsIgnoreVersion(dependency)) { result.add(testPom); } } return result; }
3
private void updateEnvironment(Graphics g) { // see if application is paused if (running) { drawFood(g); drawFeeders(g); // loop through all food and feeders for (Food fd : FoodCollection.getFoods()) { // make sure the food is still active if (fd.isActive()) { for (Feeder fr : FeederCollection.getFeeders()) { // if the feeder "sees" the food, react to it. if (fd.isPerceived(fr)) {// && //!fr.getObservedFood().contains(fd)) { fr.reactTo(fd); } } } } // update all of the feeders for (Feeder fr : FeederCollection.getFeeders()) { fr.update(); } // if the generation loop count is the same as the number of generation // loops until the next generation, advance the generation if (++genLoopCount == numGenLoops) { advanceTheGeneration(); // make sure we reset the loop counter genLoopCount = 0; } } // repaint the component repaint(); }
7
static Color getReligionColor(String religion) { religion = religion.toLowerCase(); Color ret = relColorCache.get(religion); if (ret == null) { for (GenericObject group : religions.children) { for (GenericObject rel : group.children) { if (rel.name.equalsIgnoreCase(religion)) { // found it GenericList color = rel.getList("color"); if (color == null) { System.err.println("color for " + religion + " is null"); return COLOR_NO_RELIGION_DEF; } ret = new Color( Float.parseFloat(color.get(0)), Float.parseFloat(color.get(1)), Float.parseFloat(color.get(2)) ); relColorCache.put(religion, ret); return ret; } } } return COLOR_NO_RELIGION_DEF; } return ret; }
5
@Override public void update(int deltaTicks) { int mouseX = Mouse.getX(); int mouseY = Mouse.getY(); if (mouseX > this.position.x - this.size.x / 2 && mouseX < this.position.x + this.size.x / 2 && mouseY > this.position.y - this.size.y / 2 && mouseY < this.position.y + this.size.y / 2) { hover = true; } else { hover = false; } if (this.inFocus) { if (mouseX > this.position.x - this.size.x / 2 && mouseX < this.position.x + this.size.x / 2 && mouseY > this.position.y - this.size.y / 2 - this.text.length * this.size.y && mouseY < this.position.y + this.size.y / 2 - this.size.y) { int offsetY = (mouseY - this.position.y + this.size.y / 2) * -1; this.hoverIndex = (int)Math.floor(offsetY / this.size.y) + 1; } else { this.hoverIndex = -1; } } else { this.hoverIndex = -1; } }
9
public ByteVector putByteArray(final byte[] b, final int off, final int len) { if (length + len > data.length) { enlarge(len); } if (b != null) { System.arraycopy(b, off, data, length, len); } length += len; return this; }
2
public BoGenerator( Table table ) { super( table ); boName = table.getDomName() + "Bo"; filePath = "src/main/java/" + packageToPath() + "/bo/" + boName + ".java"; for ( Column column : table.getColumns() ) { if ( column.isKey() ) { keyColumns.add(column); } } }
2
@Override public void run() { int frec = 100; try { keep_going = true; //Creamos los sockets para la transmisión de información. control_sck = new Socket(CONTROL_HOST, CONTROL_PORT); data_sck = new Socket(DATA_HOST, DATA_PORT); //Creamos los flujos de información asociados a cada socket. control_input = new BufferedReader(new InputStreamReader(control_sck.getInputStream())); data_input = new DataInputStream(new BufferedInputStream(data_sck.getInputStream())); //Variables auxiliares que necesitaremos. int sampleRate, format, channels; String entry; //Emezamos a leer información. entry = control_input.readLine(); int aux = Integer.parseInt(entry); //Tratamos la información recibida y leemos nuevos datos en caso necesario. while (aux != 0) { if (aux > 0) { byte[] bytes = new byte[aux]; data_input.read(bytes); playJavaSound(bytes); entry = control_input.readLine(); ec.addData(entry, frec); } else if (aux == -1) { terminateJavaSound(); entry = control_input.readLine(); entry = control_input.readLine(); sampleRate = Integer.parseInt(entry); entry = control_input.readLine(); format = Integer.parseInt(entry); entry = control_input.readLine(); channels = Integer.parseInt(entry); openJavaSound(sampleRate, format, channels); } else if (!keep_going) { terminateJavaSound(); } entry = control_input.readLine(); aux = Integer.parseInt(entry); } //Al terminar, cerramos el socket y finalizamos la reproducción de música. closeJavaSound(); control_sck.close(); } catch (Exception e) { con.connectError(); } }
5
public static boolean compareSubstringBare(String ion, int ii){ boolean test = false; if(IonicRadii.ions1[ii].indexOf(ion)>-1||IonicRadii.ions2[ii].indexOf(ion)>-1||IonicRadii.ions3[ii].indexOf(ion)>-1||IonicRadii.ions4[ii].indexOf(ion)>-1||IonicRadii.ions5[ii].indexOf(ion)>-1||IonicRadii.ions6[ii].indexOf(ion)>-1){ test = true; } return test; }
6
private boolean check() { if (N == 0) { if (first != null) return false; } else if (N == 1) { if (first == null) return false; if (first.next != null) return false; } else { if (first.next == null) return false; } // check internal consistency of instance variable N int numberOfNodes = 0; for (Node x = first; x != null; x = x.next) { numberOfNodes++; } if (numberOfNodes != N) return false; return true; }
8
public void initReferees() { // create file reader and referee program object FileReader refereesFileReader = null; refereeProgram = new RefereeProgram(); try { try { // initialise file reader using RefereesIn.txt refereesFileReader = new FileReader(refereesInFile); // create new Scanner using file reader Scanner in = new Scanner(refereesFileReader); // while there are more lines in the file to check while (in.hasNextLine()) { // create RefereeClass for each line in RefereesIn.txt RefereeClass refereeClass = new RefereeClass(in.nextLine()); //update the referee program object refereeProgram.refereeClassArrayBuilder(refereeClass); } // close Scanner in.close(); } finally { // close file reader if not null if (refereesFileReader != null) refereesFileReader.close(); } } catch (IOException iox) { JOptionPane.showMessageDialog(this, "File cannot be opened or does not exist", "Error", JOptionPane.ERROR_MESSAGE); } }
3
public static void main(String[] args) throws Exception { Options plumeOptions = new Options( TestIsolationDataGenerator.usage_string, TestIsolationDataGenerator.class); plumeOptions.parse_or_usage(args); // Display the help screen. if (showHelp) { plumeOptions.print_usage(); return; } if (projName == null || repoPath == null || startCommitID == null || endCommitID == null) { plumeOptions.print_usage(); return; } File repoDir = new File(repoPath); BuildStrategy buildStrategy = null; if (projName.equals(VOLDEMORT)) { buildStrategy = new VoldemortBuildStrategy(repoDir, buildCommand); } else if (projName.equals(JODA_TIME)) { buildStrategy = new JodatimeBuildStrateygy(repoDir, buildCommand); } assert buildStrategy != null; Repository repository = new GitRepository(repoDir, buildStrategy); HistoryGraph hGraph = repository.buildHistoryGraph(startCommitID, endCommitID); saveHistoryGraph(hGraph); }
7
public Grafic(final String title, JPanel fondo, double plotWindowTime) { super(title); this.plotWindowTime=plotWindowTime; final CombinedDomainXYPlot plot1 = new CombinedDomainXYPlot(new NumberAxis("Time")); final CombinedDomainXYPlot plot2 = new CombinedDomainXYPlot(new NumberAxis("Time")); this.datasets = new XYSeriesCollection[SUBPLOT_COUNT]; final XYSeries series1 = new XYSeries("Energia Cinetica",false); final XYSeries series2 = new XYSeries("Energia Potencial",false); final XYSeries series3 = new XYSeries("Energia Total",false); this.datasets[0] = new XYSeriesCollection(series1); this.datasets[1] = new XYSeriesCollection(series2); this.datasets[2] = new XYSeriesCollection(series3); String eje = "Energia Cinetica"; for (int i = 0; i < SUBPLOT_COUNT-1; i++) { this.lastValue[i] = 100.0; if(i==1)eje = "Energia Potencial"; final NumberAxis rangeAxis = new NumberAxis(eje); rangeAxis.setAutoRangeIncludesZero(false); final XYPlot subplot = new XYPlot( this.datasets[i], null, rangeAxis, new StandardXYItemRenderer() ); subplot.setBackgroundPaint(Color.lightGray); subplot.setDomainGridlinePaint(Color.white); subplot.setRangeGridlinePaint(Color.white); subplot.getRenderer().setSeriesPaint(0, Color.BLUE); if(i==0)plot1.add(subplot); else plot2.add(subplot); } final JFreeChart chart1 = new JFreeChart("Grafico Energia Kinec vs Tiempo", plot1); chart1.setBorderPaint(Color.black); chart1.setBorderVisible(true); chart1.setBackgroundPaint(Color.white); plot1.setBackgroundPaint(Color.lightGray); plot1.setDomainGridlinePaint(Color.white); plot1.setRangeGridlinePaint(Color.white); final ValueAxis axis = plot1.getDomainAxis(); axis.setAutoRange(true); axis.setFixedAutoRange(plotWindowTime); // 30 seconds final JFreeChart chart2 = new JFreeChart("Grafico Energia Pot vs Tiempo", plot2); chart2.setBorderPaint(Color.black); chart2.setBorderVisible(true); chart2.setBackgroundPaint(Color.white); plot2.setBackgroundPaint(Color.lightGray); plot2.setDomainGridlinePaint(Color.white); plot2.setRangeGridlinePaint(Color.white); final ValueAxis axis2 = plot2.getDomainAxis(); axis2.setAutoRange(true); axis2.setFixedAutoRange(plotWindowTime); // 30 seconds JFreeChart chart3 = ChartFactory.createXYLineChart("Grafico Energia Mec v/s Tiempo", "Tiempo", // Leyenda Eje X "Energia Mec", // Leyenda Eje Y this.datasets[2], PlotOrientation.VERTICAL, false, false, false ); XYPlot plot3 = chart3.getXYPlot(); chart3.setBorderPaint(Color.black); chart3.setBorderVisible(true); plot3.getRenderer().setSeriesPaint(0, Color.BLUE); final ValueAxis axis3 = plot3.getDomainAxis(); axis3.setAutoRange(true); final ValueAxis ayis3 = plot3.getRangeAxis(); //ayis3.setInverted(true); final ChartPanel chartPanel1 = new ChartPanel(chart1); final ChartPanel chartPanel2 = new ChartPanel(chart2); final ChartPanel chartPanel3 = new ChartPanel(chart3); fondo.setLayout(new BoxLayout(fondo, BoxLayout.PAGE_AXIS)); fondo.add(chartPanel2); fondo.add(chartPanel1); fondo.add(chartPanel3); chartPanel1.setPreferredSize(new java.awt.Dimension(500, 190)); //500,380 chartPanel1.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); chartPanel2.setPreferredSize(new java.awt.Dimension(500, 190));//500,270 chartPanel2.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); chartPanel3.setPreferredSize(new java.awt.Dimension(500, 190)); chartPanel3.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setContentPane(fondo); }
3
public boolean satisfies(ArrayList<Boolean> b) { for(Clause c: clauses) { //since a formula is a conjuction, if one clause returns //false, the whole formula is false. if(!(c.satisfies(b))) return false; } return true; }
2
public static void main(String[] args){ try{ ThreadPoolExecutor executor = new ThreadPoolExecutor(30, 30, 1, TimeUnit.SECONDS, new LinkedBlockingQueue()); List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(9000); // 发送垃圾邮件, 用户名假设为4位数字 for(int i=1000; i<10000; i++){ futures.add(executor.submit(new FictionalEmailSender(i+"@qq.com", "Knock, knock, Neo", "The Matrix has you..."))); } // 提交所有的任务后,关闭executor System.out.println("Starting shutdown..."); executor.shutdown(); // 每秒钟打印执行进度 while(!executor.isTerminated()){ executor.awaitTermination(1, TimeUnit.SECONDS); int progress = Math.round((executor.getCompletedTaskCount() *100)/executor.getTaskCount()); System.out.println(progress + "% done (" + executor.getCompletedTaskCount() + " emails have been sent)."); } // 现在所有邮件已发送完, 检查futures, 看成功发送的邮件有多少 int errorCount = 0; int successCount = 0; for(Future<Boolean> future : futures){ if(future.get()){ successCount++; }else{ errorCount++; } } System.out.println(successCount + " emails were successfully sent, but " + errorCount + " failed."); }catch(Exception ex){ ex.printStackTrace(); } }
5
public final WaiprParser.inval_return inval() throws RecognitionException { WaiprParser.inval_return retval = new WaiprParser.inval_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token set68=null; CommonTree set68_tree=null; try { // Waipr.g:61:7: ( ( ID | NUMBER | TEXT ) ) // Waipr.g: { root_0 = (CommonTree)adaptor.nil(); set68=input.LT(1); if ( input.LA(1)==ID||input.LA(1)==NUMBER||input.LA(1)==TEXT ) { input.consume(); adaptor.addChild(root_0, (CommonTree)adaptor.create(set68)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
4
public static void main(String[] args) throws FileNotFoundException { System.out.println(new File(".").getAbsolutePath()); Scanner inputFile = new Scanner(new File(".\\src\\hashMap\\inputFile.txt")); HashMap2 hashMap = new HashMap2(SIZE); JFrame frame = new JFrame("Hash Map"); JPanel grid = new JPanel(new GridLayout(2, 0)); String[] inputLines; for(int i = 0; i < SIZE; i++) { grid.add(new JLabel(Integer.toString(i))); } JPanel[] buckets = addBucketsToPanel(grid); grid.validate(); while(inputFile.hasNextLine()) { inputLines = inputFile.nextLine().split(" "); if(inputLines.length < 2) { continue; } System.out.println(inputLines[0]); addToBucketsAndHashMap(inputLines[0], inputLines[1], hashMap, buckets); } inputFile.close(); frame.setPreferredSize(new Dimension(640, 480)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(grid); frame.pack(); frame.setVisible(true); }
3
public void addTask(Task task){ StringBuilder update = new StringBuilder("insert into tasks(reporter,assignee,`status`,description,priority,`completion`,start_date,deadline,title) values("); if(task.getReporter()!=null && task.getReporter().getUserName()!=null) update.append("\""+task.getReporter().getUserName()+"\","); else update.append("\"\","); if(task.getAssignee()!=null && task.getAssignee().getUserName()!=null) update.append("\""+task.getAssignee().getUserName()+"\","); else update.append("\"\","); if(task.getStatus()!=null && task.getStatus().getStatusName()!=null) update.append("\""+task.getStatus().getStatusName()+"\","); else update.append("\"\","); if(task.getDescription()!=null) update.append("\""+task.getDescription()+"\","); else update.append("\"\","); update.append(""+task.getPriority()+","); update.append(""+task.getCompletionPercent()+","); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss",java.util.Locale.getDefault()); String date; if(task.getStartDate()!=null){ date = formatter.format(task.getStartDate().getTime()); update.append("\""+date+"\","); } else update.append("\"\","); if(task.getDeadLine()!=null) { date = formatter.format(task.getDeadLine().getTime()); update.append("\""+date+"\","); } else update.append("\"\","); update.append("\""+task.getTitle()+"\")"); System.out.println(update); execUpdate(update.toString()); }
9
public static MiscellaneousReasonEnumeration fromString(String v) { if (v != null) { for (MiscellaneousReasonEnumeration c : MiscellaneousReasonEnumeration.values()) { if (v.equalsIgnoreCase(c.toString())) { return c; } } } throw new IllegalArgumentException(v); }
3
void bedIterate() { // Open file BedFileIterator bfi = new BedFileIterator(inFile, config.getGenome()); bfi.setCreateChromos(true); // Any 'new' chromosome in the input file will be created (otherwise an error will be thrown) for (Variant bed : bfi) { try { // Find closest exon Markers closestMarkers = findClosestMarker(bed); String id = bed.getId(); // Update ID field if any marker found if (closestMarkers != null) { StringBuilder idsb = new StringBuilder(); // Previous ID idsb.append(bed.getId()); if (idsb.length() > 0) idsb.append(";"); // Distance int dist = reportDistance(closestMarkers, bed); idsb.append(dist); // Append all closest markers for (Marker closestMarker : closestMarkers) idsb.append(";" + closestMarker.idChain(",", false)); id = idsb.toString(); } // Show output System.out.println(bed.getChromosomeName() // + "\t" + bed.getStart() // BED format: Zero-based position + "\t" + (bed.getEnd() + 1) // BED format: End base is not included + "\t" + id // ); } catch (Exception e) { e.printStackTrace(); // Show exception and move on... } } }
5
public void run() { while (!stop) { try { File f = Main.encontrados.take(); System.out.println(f.getCanonicalPath()); } catch (InterruptedException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2
@SuppressWarnings("unchecked") public static ListTag fromNBTTag(NBTTagList base) { Type type = Tag.fromNBTTag(base.get(0)).getClass(); List<Tag> list = new ArrayList<>(); for (int i = 0; i < base.size(); i++) { list.add(Tag.fromNBTTag(base.get(i))); } return new ListTag((Class<? extends Tag>) type.getClass(), list); }
2
public void startDocumentInternal() throws org.xml.sax.SAXException { if (m_needToCallStartDocument) { super.startDocumentInternal(); m_needToCallStartDocument = false; if (m_inEntityRef) return; m_needToOutputDocTypeDecl = true; m_startNewLine = false; /* The call to getXMLVersion() might emit an error message * and we should emit this message regardless of if we are * writing out an XML header or not. */ final String version = getXMLVersion(); if (getOmitXMLDeclaration() == false) { String encoding = Encodings.getMimeEncoding(getEncoding()); String standalone; if (m_standaloneWasSpecified) { standalone = " standalone=\"" + getStandalone() + "\""; } else { standalone = ""; } try { final java.io.Writer writer = m_writer; writer.write("<?xml version=\""); writer.write(version); writer.write("\" encoding=\""); writer.write(encoding); writer.write('\"'); writer.write(standalone); writer.write("?>"); if (m_doIndent) { if (m_standaloneWasSpecified || getDoctypePublic() != null || getDoctypeSystem() != null) { // We almost never put a newline after the XML // header because this XML could be used as // an extenal general parsed entity // and we don't know the context into which it // will be used in the future. Only when // standalone, or a doctype system or public is // specified are we free to insert a new line // after the header. Is it even worth bothering // in these rare cases? writer.write(m_lineSep, 0, m_lineSepLen); } } } catch(IOException e) { throw new SAXException(e); } } } }
9
public void setHistorialClinicoidHistorialClinico(Historialclinico historialClinicoidHistorialClinico) { this.historialClinicoidHistorialClinico = historialClinicoidHistorialClinico; }
0
public int loadStripImages(String fnm, int number) /* * Can be called directly, to load a strip file, <fnm>, holding <number> * images. */ { String name = getPrefix(fnm); if (imagesMap.containsKey(name)) { System.out.println("Error: " + name + "already used"); return 0; } // load the images into an array BufferedImage[] strip = loadStripImageArray(fnm, number); if (strip == null) return 0; ArrayList imsList = new ArrayList(); int loadCount = 0; System.out.print(" Adding " + name + "/" + fnm + "... "); for (int i = 0; i < strip.length; i++) { loadCount++; imsList.add(strip[i]); System.out.print(i + " "); } System.out.println(); if (loadCount == 0) System.out.println("No images loaded for " + name); else imagesMap.put(name, imsList); return loadCount; } // end of loadStripImages()
4
public void testAdd2() { RunArray<Font> runArray = new RunArray<Font>(); int i; // Add 10 fonts for first 100 characters for (i = 0; i < 10; i++) { if (i % 2 == 0) { assertEquals(i, runArray.addRun(i * 10, 10, fontA)); } else { assertEquals(i, runArray.addRun(i * 10, 10, fontB)); } } // Verify fonts for (i = 0; i < 100; i++) { if ((i / 10) % 2 == 0) { assertEquals(fontA, runArray.atRun(i)); } else { assertEquals(fontB, runArray.atRun(i)); } } // Add fontC for characters 15-84, it should be after 0-10 and 10-14 assertEquals(2, runArray.addRun(15, 70, fontC)); // Verify fonts, 0-9 fontA, 10-14 fontB, 15-84 fontC, 85-90 fontA, 90-99 // fontB for (i = 0; i < 10; i++) { assertEquals(fontA, runArray.atRun(i)); } for (i = 10; i < 15; i++) { assertEquals(fontB, runArray.atRun(i)); } for (i = 15; i < 85; i++) { assertEquals(fontC, runArray.atRun(i)); } for (i = 85; i < 90; i++) { assertEquals(fontA, runArray.atRun(i)); } for (i = 90; i < 100; i++) { assertEquals(fontB, runArray.atRun(i)); } }
9
public void showSet(String name, Player controller, double amount, boolean console) { Player online = iConomy.getBukkitServer().getPlayer(name); if (online != null) { name = online.getName(); } Account account = iConomy.getAccount(name); if (account != null) { Holdings holdings = account.getHoldings(); holdings.set(amount); Double balance = Double.valueOf(holdings.balance()); iConomy.getTransactions().insert("[System]", name, 0.0D, balance.doubleValue(), amount, 0.0D, 0.0D); if (online != null) { Messaging.send(online, this.Template.color("tag.money") + this.Template.parse("personal.set", new String[] { "+by", "+amount,+a" }, new String[] { console ? "Console" : controller.getName(), iConomy.format(amount) })); showBalance(name, online, true); } if (controller != null) { Messaging.send(this.Template.color("tag.money") + this.Template.parse("player.set", new String[] { "+name,+n", "+amount,+a" }, new String[] { name, iConomy.format(amount) })); } if (console) System.out.println("Player " + account + "'s account had " + iConomy.format(amount) + " set to it."); else System.out.println(Messaging.bracketize("iConomy") + "Player " + account + "'s account had " + iConomy.format(amount) + " set to it by " + controller.getName() + "."); } }
6
public CheckResultMessage checkJ04(int day) { return checkReport.checkJ04(day); }
0
public boolean chargeIt(double price){ if (price + balance > (double)limit) return false; balance +=price; return true; }
1
private void KeyboardPanelPressed(final JPanel jPanel) { if (!new ArrayList(Arrays.asList(jPanel.getComponents())).isEmpty()) { return; } for (final Component comp : KeysPanel.getComponents()) { if (comp instanceof JToggleButton) { JToggleButton keyButton = (JToggleButton) comp; if (keyButton.isSelected()) { jPanel.setLayout(new FlowLayout()); final JButton keyboardPanelButton = new JButton(keyButton.getText()); keyboardPanelButton.setBackground(comp.getBackground()); keyboardPanelButton.setForeground(comp.getForeground()); keyboardPanelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { KeyboardPanelButtonPressed(evt, jPanel, comp); } }); jPanel.add(keyboardPanelButton); jPanel.validate(); jPanel.repaint(); keyButton.setSelected(false); listOfDisabledKeys.add(comp); } else { if (!listOfDisabledKeys.contains(comp)) { comp.setEnabled(true); } } } } }
5
public ChartHandle createChart( String name, WorkSheetHandle wsh ) { if( wsh == null ) { // this is a sheetless chart - TODO: } /* a chart needs a supbook, externsheet, & MSO object in the book stream. * I think this is due to the fact that the referenced series are usually stored * in the fashon 'Sheet1!A4:B6' The sheet1 reference requires a supbook, though the * reference is internal. */ try { ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( getPrototypeChart() ) ); Chart newchart = (Chart) ois.readObject(); newchart.setWorkBook( getWorkBook() ); if( getIsExcel2007() ) { newchart = new OOXMLChart( newchart, this ); } mybook.addPreChart(); mybook.addChart( newchart, name, wsh.getSheet() ); /* add font recs if nec: for the default chart: default chart text fonts are # 5 & 6 title # 7 axis # 8 */ ChartHandle bs = new ChartHandle( newchart, this ); int nfonts = mybook.getNumFonts(); while( nfonts < 8 ) { // ensure Font f = new Font( "Arial", Font.PLAIN, 200 ); mybook.insertFont( f ); nfonts++; } Font f = mybook.getFont( 8 ); // axis title font if( f.toString().equals( "Arial,400,200 java.awt.Color[r=0,g=0,b=0] font style:[falsefalsefalsefalse00]" ) ) { // it's default text font -- change to default axis title font f = new Font( "Arial", Font.BOLD, 240 ); bs.setAxisFont( f ); } f = mybook.getFont( 7 ); // chart title font if( f.toString().equals( "Arial,400,200 java.awt.Color[r=0,g=0,b=0] font style:[falsefalsefalsefalse00]" ) ) { // it's default text font -- change to default title font f = new Font( "Arial", Font.BOLD, 360 ); bs.setTitleFont( f ); } bs.removeSeries( 0 ); // remove the "dummied" series bs.setAxisTitle( ChartHandle.XAXIS, null ); // remove default axis titles, if any bs.setAxisTitle( ChartHandle.YAXIS, null ); // "" return bs; } catch( Exception e ) { log.error( "Creating New Chart: " + name + " failed: " + e ); return null; } }
6
private String getPrecedence(String op1, String op2){ String multiplicativeOps = "*/%"; String additiveOps = "+-"; if ((multiplicativeOps.indexOf(op1) != -1) && (additiveOps.indexOf(op2) != -1)) return op1; else if ((multiplicativeOps.indexOf(op2) != -1) && (additiveOps.indexOf(op1) != -1)) return op2; else if((multiplicativeOps.indexOf(op1) != -1) && (multiplicativeOps.indexOf(op2) != -1)) return op1; else return op1; }
6
private String getInput(){ @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); String userInput; do{ System.out.print("Enter your move [WASD?]: "); userInput = scanner.nextLine(); userInput = userInput.trim().substring(0, 1); if(VALID_KEYS.contains(userInput.toUpperCase())){ continue; } else if(userInput.equals("?")){ printHelp(); } else{ System.out.println("Invalid move. Please enter just A (left), S (down), D (right), or W (up)."); } }while(!VALID_KEYS.contains(userInput.toUpperCase()) || userInput.isEmpty()); return userInput; }
4
@Override public boolean activate() { return Game.isLoggedIn() && Players.getLocal().isInCombat() || initialized; }
2
private void home(Value v) throws Exception { if(isSpilled(v)) { // then this value has been spilled, the value is // currently in t1, insert the spill code now // if the color is less than 0, it is 'spilled', but // doesn't need to be put into a home since it is never // used if(v.getColor() < 0) { return; } int address = getSpillAddress(v); emit(DLX.assemble(DLX.STW, t1, fp, address)); } // otherwise, do nothing, the value is home }
2
@EventHandler public void touchytouchy(PlayerInteractEntityEvent event) { Player player = (Player)event.getPlayer(); Entity rightclick = event.getRightClicked(); if(rightclick instanceof Player) { Player rightclicked = (Player)rightclick; if(plugin.isActivated(player.getName())) { if(player.getItemInHand().getTypeId() == plugin.getConfig().getInt("BanItemId")) { plugin.banPlayer(player, rightclicked); } if(player.getItemInHand().getTypeId() == plugin.getConfig().getInt("EncasingTool")) { if(rightclicked.hasPermission("bh.bypass")) { player.sendMessage(new StringBuilder(pre).append("You can not encase this player!").toString()); return; } trapPlayer(rightclicked); player.sendMessage(new StringBuilder(pre).append(rightclicked.getName()).append(" has been trapped by you").toString()); } if(player.getItemInHand().getTypeId() == plugin.getConfig().getInt("FreezingTool")) { if(rightclicked.hasPermission("bh.bypass")) { player.sendMessage(new StringBuilder(pre).append("You can not freeze this player!").toString()); return; } if(plugin.freezePlayer(rightclicked)) { player.sendMessage(new StringBuilder(pre).append(rightclicked.getName()).append(" has been frozen!").toString()); rightclicked.sendMessage(new StringBuilder(pre).append("You have been frozen!").toString()); }else { player.sendMessage(new StringBuilder(pre).append(rightclicked.getName()).append(" has been unfrozen!").toString()); rightclicked.sendMessage(new StringBuilder(pre).append("You have been unfrozen!").toString()); } } } } }
8
public void buy(MapleClient c, int itemId, short quantity) { if (quantity <= 0) { AutobanManager.getInstance().addPoints(c, 1000, 0, "Buying " + quantity + " " + itemId); return; } MapleShopItem item = findById(itemId); if (item != null && item.getPrice() > 0) { if (c.getPlayer().getMeso() >= item.getPrice() * quantity) { if (MapleInventoryManipulator.checkSpace(c, itemId, quantity, "")) { if (InventoryConstants.isPet(itemId)) { MapleInventoryManipulator.addById(c, itemId, quantity, null, MaplePet.createPet(itemId)); } else { MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); if (InventoryConstants.isRechargable(itemId)){ quantity = ii.getSlotMax(item.getItemId()); c.getPlayer().gainMeso(-(item.getPrice()), false); MapleInventoryManipulator.addById(c, itemId, quantity); } else { c.getPlayer().gainMeso(-(item.getPrice() * quantity), false); MapleInventoryManipulator.addById(c, itemId, quantity); } } } else { c.getPlayer().dropMessage(1, "Your Inventory is full"); } c.getSession().write(MaplePacketCreator.confirmShopTransaction((byte) 0)); } } }
7
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
4
@Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { TrendBar bar = doneBars.take(); trendBarDao.addTrendBar(bar); } catch (InterruptedException e) { executorService.shutdown(); Thread.currentThread().interrupt(); } } }
2
@Override public boolean onPointerMove(int mX, int mY, int mDX, int mDY) { PhysicsComponent pc = (PhysicsComponent)actor.getComponent("PhysicsComponent"); float X = pc.getX(); float Y = pc.getY(); if(mX < placementAreaX) { X = placementAreaX; } else if(mX > placementAreaX + placementAreaWidth) { X = placementAreaX + placementAreaWidth; } else { X = mX; } if(mY < placementAreaY) { Y = placementAreaY; } else if(mY > placementAreaY + placementAreaHeight) { Y = placementAreaY + placementAreaHeight; } else { Y = mY; } actor.move(X, Y); return false; }
4
public CeremonialAxe() { this.name = Constants.CEREMONIAL_AXE; this.attackScore = 9; this.attackSpeed = 14; this.money = 1500; }
0
@Override public boolean dispatchKeyEvent(KeyEvent e) { switch (e.getKeyCode()) { case 37: GUI.scrollBothPaneH("dec", 30); break; case 39: GUI.scrollBothPaneH("inc", 30); break; case 38: GUI.scrollBothPaneV("inc", 30); break; case 40: GUI.scrollBothPaneV("dec", 30); break; } return false; }
4
private void p_bookingPage(){ p_bookingPane = new JPanel(); p_bookingPane.setBackground(SystemColor.activeCaption); p_bookingPane.setLayout(null); if (patient!=null){ db.showBookingPat(PBT_model,patient.getHKID()); } PBL_choose_model.removeAllElements(); PBT_date.setValue(null); JLabel lbl_Booking = new JLabel("Booking"); lbl_Booking.setFont(new Font("Arial", Font.BOLD, 30)); lbl_Booking.setBounds(428, 20, 127, 47); p_bookingPane.add(lbl_Booking); JLabel lbl_date = new JLabel("Date:"); lbl_date.setHorizontalAlignment(SwingConstants.RIGHT); lbl_date.setFont(new Font("Arial", Font.PLAIN, 20)); lbl_date.setBounds(185, 119, 57, 24); p_bookingPane.add(lbl_date); JLabel lblDdmmyyyy = new JLabel("dd/mm/yyyy"); lblDdmmyyyy.setHorizontalAlignment(SwingConstants.RIGHT); lblDdmmyyyy.setFont(new Font("Arial", Font.PLAIN, 20)); lblDdmmyyyy.setBounds(124, 141, 116, 24); p_bookingPane.add(lblDdmmyyyy); JLabel lbl_doctor = new JLabel("Doctor:"); lbl_doctor.setHorizontalAlignment(SwingConstants.RIGHT); lbl_doctor.setFont(new Font("Arial", Font.PLAIN, 20)); lbl_doctor.setBounds(92, 198, 71, 24); p_bookingPane.add(lbl_doctor); JButton PBB_update = new JButton("update"); PBB_update.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { PBupdate(); }}); PBB_update.setFont(new Font("Arial", Font.PLAIN, 20)); PBB_update.setBounds(278, 274, 101, 47); p_bookingPane.add(PBB_update); //set Doctor list PBCB_doctor.removeAllItems(); Doctor.addCombo(logAc, PBCB_doctor); JButton PBB_book = new JButton("Book"); PBB_book.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try{ if (PBL_choose.getSelectedIndex()==-1) throw new NullFieldException(3); int day, month, year; day = Integer.parseInt(((String)PBT_date.getValue()).substring(0,2)); month = Integer.parseInt(((String)PBT_date.getValue()).substring(3,5))-1; year = Integer.parseInt(((String)PBT_date.getValue()).substring(6,10)); GregorianCalendar date = new GregorianCalendar(); date.set(year, month, day,Integer.parseInt(PBL_choose_model.getElementAt(PBL_choose.getSelectedIndex()).substring(0, 2)),0); int index = PBCB_doctor.getSelectedIndex(); String doctorID = logAc.getDoctor(index).getUserName(); if (!db.is30Day(patient.getHKID(),date)) throw new NullFieldException(4); if (!db.isWithin30(date)) throw new NullFieldException(5); db.createbooking(patient.getHKID(), doctorID, date); if (elderly){ GregorianCalendar date2 = new GregorianCalendar(); date2.set(year, month, day,Integer.parseInt(PBL_choose_model.getElementAt(PBL_choose.getSelectedIndex()).substring(0, 2))+1,0); db.createbooking(patient.getHKID(), doctorID, date2); } } catch (NullFieldException e){ e.error(); } PBupdate(); db.showBookingPat(PBT_model,patient.getHKID()); } }); PBB_book.setFont(new Font("Arial", Font.PLAIN, 20)); PBB_book.setBounds(843, 300, 109, 47); p_bookingPane.add(PBB_book); JButton btnBackToPatient = new JButton("Patient"); btnBackToPatient.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { cardLayout.show(contentPane, "Patient"); } }); btnBackToPatient.setFont(new Font("Arial", Font.PLAIN, 20)); btnBackToPatient.setBounds(827, 585, 116, 47); p_bookingPane.add(btnBackToPatient); }
6
@Test public void testLoadingCards() { // Test loading cards ArrayList<Card> cards = testBoard.getCards(); // check total number of cards Assert.assertEquals(cards.size(), 21); // check number of types of cards int numberOfWeaponCards = 0; int numberOfRoomCards = 0; int numberOfPersonCards = 0; for( Card card : cards ) { if( card.getType() == Card.CardType.WEAPON ) numberOfWeaponCards++; if( card.getType() == Card.CardType.ROOM ) numberOfRoomCards++; if( card.getType() == Card.CardType.PERSON ) numberOfPersonCards++; } Assert.assertEquals(numberOfWeaponCards, 6); Assert.assertEquals(numberOfPersonCards, 6); Assert.assertEquals(numberOfRoomCards, 9); // check if specific cards are in the deck String person = "Lars"; String weapon = "pile of dirt"; String room = "Pool"; boolean personExists = false; boolean weaponExists = false; boolean roomExists = false; for( Card card : cards ) { if( card.getName().equalsIgnoreCase(person) ) personExists = true; if( card.getName().equalsIgnoreCase(weapon) ) weaponExists = true; if( card.getName().equalsIgnoreCase(room) ) roomExists = true; } Assert.assertTrue(personExists); Assert.assertTrue(weaponExists); Assert.assertTrue(roomExists); }
8
public boolean isNaN(){ boolean test = false; if(this.magnitude!=this.magnitude || this.phaseInDeg!=this.phaseInDeg)test = true; return test; }
2
public void runScript(String serverUrl, String userId, ScriptName scriptName) { Thread thread = null; switch (scriptName) { case opUsPg: OpenPageScript openPageScript = new OpenPageScript(serverUrl, userId, this); thread = new Thread(openPageScript); break; case addRes: AddResScript addResScript = new AddResScript(serverUrl, userId, this); thread = new Thread(addResScript); break; case addResMas: AddResMasteryScript addResMasteryScript = new AddResMasteryScript( serverUrl, userId, this); thread = new Thread(addResMasteryScript); break; case newItems: AddNewItemsScript addNewItemsScript = new AddNewItemsScript( serverUrl, userId, this, itemType, itemIds); thread = new Thread(addNewItemsScript); break; case reset: ResetUser resetUser = new ResetUser(serverUrl, userId, this); thread = new Thread(resetUser); break; case dropAll: break; default: break; } thread.start(); }
6
public static void main(String[] args){ try { //prompt for IP address BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter server's IP"); String ip = reader.readLine(); if(!ip.trim().equals("")){ server_ip = ip; } //connect to server String eid = "njc487"; if(args.length == 1){ eid = args[0]; } System.out.println("My eid is " + eid); System.out.println("Connecting to " + server_ip); int port = Integer.parseInt(server_ip.split(":")[1]); String ia = server_ip.split(":")[0]; Socket socket = new Socket(ia, port); ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(socket.getInputStream())); ObjectOutputStream output = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream())); Answer dummyAnswer = new Answer(0, Integer.MAX_VALUE, eid); output.writeObject(dummyAnswer); //prevent InputStream on the server from blocking output.flush(); System.out.println("Waiting for clicker id."); Question question = (Question) input.readObject(); if(question.message == true){ clicker_id = question.clicker_id; System.out.println("Clicker id assigned by server: " + clicker_id); } System.out.println("Waiting for question."); question = (Question) input.readObject(); while(question != null){ System.out.println(question); //read answer choice (blocks until user hits enter) int choice = readAnswer(reader, question.size()); Answer answer = new Answer(choice, question.id, eid); //send back to the server output.writeObject(answer); output.flush(); //wait for next question (block here) System.out.println("Answer sent. Waiting for next question."); question = (Question) input.readObject(); } } catch(EOFException e){ System.out.println("Server disconnected."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
7
public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(1280, 768); frame.setTitle("BulletTester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Random r = new Random(); ArrayList<Bullet> bulletList = new ArrayList<Bullet>(); ArrayList<Drawable> drawableList = new ArrayList<Drawable>(); // Fills the ArrayList with a number of bullets. for (int i = 1; i < 10; i++) { double angle = r.nextDouble() * 359; bulletList.add(new Bullet(frame.getWidth() / 2, frame.getHeight() / 2, frame.getWidth() / 2, frame.getHeight() / 2, 5, angle, 1280, 768)); } //Creates the drawing component and adds it to the frame. AsteroidsComponent component = new AsteroidsComponent(drawableList); component.setDoubleBuffered(true); frame.add(component); frame.setVisible(true); boolean gameOver = false; while(!gameOver) { for (Bullet bullet : bulletList) bullet.move(); for (int i = 0; i < bulletList.size(); i++) { if (bulletList.get(i).distanceTraveled() > 300) bulletList.remove(i); } //Pause.pause(100); int listSize = drawableList.size(); for (int k = 0; k < listSize; k++) drawableList.remove(0); for (Bullet bullet : bulletList) drawableList.add(bullet); component.paintImmediately(0,0,frame.getWidth(),frame.getHeight()); } }
7
public static void main(String[] args) { Demo01 demo = new Demo01(); demo.method_b(b); }
0
public Type[] exceptions() { final ConstantPool cp = editor.constants(); final int[] indices = methodInfo.exceptionTypes(); final Type[] types = new Type[indices.length]; for (int i = 0; i < indices.length; i++) { types[i] = (Type) cp.constantAt(indices[i]); } return (types); }
1
public int run (String[] args) throws Exception { for(int i = 0; i < args.length; i++){ System.out.println(i + " : " + args[i]); } if (args.length < 2) { System.err.printf("Usage: %s [generic options] <d> <maxDimensions> <dataSets> <key> <input> <input2?> <output> <prevrun?> \n", getClass().getSimpleName()); ToolRunner.printGenericCommandUsage(System.err); return -1; } int d = Integer.parseInt(args[0]); boolean is2D = (Integer.parseInt(args[1]) < 3); int iter = d; if(!is2D) { iter = d*d; } boolean isPaired = (Integer.parseInt(args[2]) == 2); iter = 1; for(int i = 0; i < iter; i++) { System.out.println("Sub-iteration " + i); JobConf conf = getJobInstance(i,isPaired); FileSystem fs = FileSystem.get(conf); conf.setInt("ff.d", d); conf.setInt("ff.subepoch", i); int outputIndex = 4; if(isPaired) { MultipleInputs.addInputPath(conf, new Path(args[4]), KeyValueTextInputFormat.class, FFMapper.class); MultipleInputs.addInputPath(conf, new Path(args[5]), KeyValueTextInputFormat.class, FFMapperPaired.class); outputIndex = 6; } else { FileInputFormat.addInputPath(conf, new Path(args[4])); outputIndex = 5; } //FileOutputFormat.setOutputPath(conf, new Path(args[outputIndex] + "/final/")); conf.setStrings("ff.outputPath", args[outputIndex]); if(args.length > outputIndex + 1) { conf.setStrings("ff.prevPath", args[outputIndex+1]); } RunningJob job = JobClient.runJob(conf); //if(i % d == 0) { long loss = job.getCounters().findCounter("FF Loss","Loss").getCounter(); long count = job.getCounters().findCounter("FF Loss","Points").getCounter(); long updated = job.getCounters().findCounter("FlexiFaCT","Number Passed").getCounter(); String key = "-" + args[3]; BufferedWriter lossResults = new BufferedWriter(new FileWriter("loss" + key + ".txt",true)); ; //BufferedWriter lossResults = new BufferedWriter(new FileWriter("loss" + key + ".txt",true)); ; if(!isPaired) { lossResults.write(i + "\t" + (loss/1000.0) + "\t" + count + "\t" + updated + "\t" + ((loss/1000.0)/count)+ "\t" + Math.sqrt( (loss/1000.0)/count ) + "\n"); } else { long loss0= job.getCounters().findCounter("FF Loss","Loss-data0").getCounter(); long count0= job.getCounters().findCounter("FF Loss","Points-data0").getCounter(); long loss1= job.getCounters().findCounter("FF Loss","Loss-data1").getCounter(); long count1= job.getCounters().findCounter("FF Loss","Points-data1").getCounter(); lossResults.write(i + "\t" + (loss/1000.0) + "\t" + count + "\t" + ( (loss/1000.0)/count )+ "\t" + Math.sqrt( (loss/1000.0)/count ) + "\t" + updated + "\t" + (loss0/1000.0) + "\t" + count0 + "\t" + (loss1/1000.0) + "\t" + count1 + "\n"); } lossResults.close(); //} } return 0; }
7
public Gesture(PersistentCanvas c, Color o, Color f, Point p, Panel l, boolean gesture) { super(c, o, f); panel = l; type = 1; thickness = 2; shape = new GeneralPath(); ((GeneralPath) shape).moveTo(p.x, p.y); firstpoint = p; isGesture = gesture; if (isGesture) { dollar.setListener(this); dollar.setActive(true); dollar.pointerPressed(p.x, p.y); } }
1
protected void convertMapsToSections(Map<?, ?> input, ConfigurationSection section) { for (Map.Entry<?, ?> entry : input.entrySet()) { String key = entry.getKey().toString(); Object value = entry.getValue(); if (value instanceof Map) { convertMapsToSections((Map<?, ?>) value, section.createSection(key)); } else { section.set(key, value); } } }
8
public boolean remove(String name) { Connection conn = null; PreparedStatement ps = null; try { conn = iConomy.getiCoDatabase().getConnection(); ps = conn.prepareStatement("DELETE FROM " + Constants.SQLTable + " WHERE username = ? LIMIT 1"); ps.setString(1, name); ps.executeUpdate(); } catch (Exception e) { return false; } finally { if (ps != null) try { ps.close(); } catch (SQLException ex) { } if (conn != null) try { conn.close(); } catch (SQLException ex) { } } return true; }
5
public void readFile(String filename) throws FileNotFoundException, IOException, InvalidUserException { Scanner scanner = new Scanner(new File(filename)); fw = new FileWriter(new File(fileWriterName)); while (true) { String s = scanner.nextLine(); if (s.contains("EXIT")) { break; } else { try { writeToFile(s); } catch (InvalidMailFormatException | InvalidEditProfileInputException | InvalidPhoneNrFormatException | ProfileNotSetException ex) { Logger.getLogger(Twitter.class .getName()).log(Level.SEVERE, null, ex); } } } fw.flush(); fw.close(); }
3
static LinkedList copyAll(LinkedList list, ConstPool cp) { if (list == null) return null; LinkedList newList = new LinkedList(); int n = list.size(); for (int i = 0; i < n; ++i) { AttributeInfo attr = (AttributeInfo)list.get(i); newList.add(attr.copy(cp, null)); } return newList; }
2