text
stringlengths
14
410k
label
int32
0
9
public boolean getDirection (char current, char[] neighbors){ if(current == neighbors[4] || current == neighbors[6]){ return true; } else { return false; } }
2
private int scoreBowl(int[] bowl) { int score = 0; for (int i = 0; i < preferences.length; i++) { score += bowl[i] * preferences[i]; } return score; }
1
@Test public void KATest() { userInput.add("hi"); userInput.add("daniel"); userInput.add("can you help me in the kitchen"); userInput.add("bring me something"); userInput.add("bring me sausage"); userInput.add("yes"); userInput.add("ingredient"); userInput.add("supermarket"); userInput.add("bring me sausage"); removableFiles.add("sausage"); runMainActivityWithTestInput(userInput); assertTrue(nlgResults.get(2).contains("What can") && nlgResults.get(3).contains("What can") && nlgResults.get(4).contains("don't know") && nlgResults.get(5).contains("Ingredient") && nlgResults.get(6).contains("sausage") && nlgResults.get(7).contains("What can") && nlgResults.get(8).contains("Can't") || nlgResults.get(8).contains("can't")); }
7
public JLabel getjLabelLogin() { return jLabelLogin; }
0
@Override public void absolute(final int localPointer) { if (localPointer < 0 || localPointer >= rows.size()) { throw new IndexOutOfBoundsException("INVALID POINTER LOCATION: " + localPointer); } pointer = localPointer; currentRecord = new RowRecord(rows.get(pointer), metaData, parser.isColumnNamesCaseSensitive(), pzConvertProps, strictNumericParse, upperCase, lowerCase, parser.isNullEmptyStrings()); }
2
public static void main(String[] args) { // TODO Auto-generated method stub Scanner input=new Scanner(System.in); int k=input.nextInt(); char q; for(int r=0;r<k;r++){ String path=input.next(); int count=0,y=0,x; for(int i=0;i<path.length();i++){ q=path.charAt(i); x=0; if(q=='.'){ while(q!='#'){ x++; q = path.charAt(++i); } if(y<x){ count++; y=x; } } } System.out.println(count); } }
5
public TurnChanger (Player player1, Player player2){ turn = 0; players[0]=player1; players[1]=player2; }
0
public void visit_castore(final Instruction inst) { stackHeight -= 3; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
1
private static void attackBala(Ant ant) { int XLoc = ant.getLocationX(); int YLoc = ant.getLocationY(); int randNum = RandomNumGen.randomNumber(0, 3); // 50% Chance of killing a Bala ant in the same node as the soldier ant if (randNum == 1 || randNum == 3) { // Iterates through the linked list of bala ants until it finds the first ant // whose location is in the same node as the attacking soldier ant for (Ant balaAnt : AntColony.balaAnts) { if (balaAnt.getLocationX() == XLoc && balaAnt.getLocationY() == YLoc) { UpdateIcons.removeAntIcon(balaAnt); AntColony.balaAnts.remove(balaAnt); return; } } } }
5
private void onClick() { String newStatus; String callNumber = textFields.get(0).getText().trim(); int copyNo; if (!isNumeric(textFields.get(1).getText().trim())){ popMsg("copyNo must be a number!"); return; } copyNo = Integer.parseInt(textFields.get(1).getText().trim()); // check if book exists if(!LibraryDB.getManager().hasBookCopy(callNumber, copyNo)){ popMsg("Book does not exist in library!"); return; } // check if bookcopy is available for borrowing, i.e. status = out. if (!LibraryDB.getManager().isBookCopyStatus(callNumber,copyNo,BookCopy.OUT)){ popMsg("Sorry! This book is not out, please double check call number and copyNo."); return; } // Message to be shown later String msg = "Item Returned! \n"; //Retrieve Borrowing Borrowing b = LibraryDB.getManager().getBorrowing(callNumber, copyNo); // set inDate Calendar currentCal = new GregorianCalendar(TimeZone.getTimeZone("PST")); String currentDate = calendarToString(currentCal); LibraryDB.getManager().updateBorrowingInDate(b.getBorid(), currentDate); //Check Overdue and create a new Fine if it is. if (getOverDueTime(b) > 0) { Fine f = new Fine(0,getOverDueTime(b),currentDate,null,b.getBorid()); LibraryDB.getManager().insertFine(f); msg += "Fine is assessed. \n"; } // Check if on-hold newStatus = getNewStatus(callNumber); if (newStatus.matches(BookCopy.ON_HOLD)){ msg += "Book is placed on-hold. \n"; } LibraryDB.getManager().updateBookCopy(callNumber, copyNo, newStatus); popMsg(msg); this.dispose(); }
5
public boolean placePiece(Piece piece, int x, int y) { // colocando peça no pre-jogo if (status == statusPreGame) { if (board.getPiece(x, y) == null) { // lugar vazio int id = piece.getRank(); int co = piece.getColor(); if (co == teamRed && isRedField(x, y)) { if (redCollected[id - Piece.pSpy] > 0) { board.placePiece(piece, x, y); redCollected[id - Piece.pSpy]--; // red colocada no campo red vazio return true; } } else if (co == teamBlue && isBlueField(x, y)) { if (blueCollected[id - Piece.pSpy] > 0) { board.placePiece(piece, x, y); blueCollected[id - Piece.pSpy]--; // blue colocada no campo blue vazio return true; } } } } return false; }
8
public int addEmployee(String fname, String lname, String email) throws ServletException { //TODO implement method that adds an employee to repository //This method should check that email is not used by other employees if (fname.equals("") || lname.equals("") || email.equals("")){ throw new ServletException("Вы не заполнили все поля"); } int count = 0; for (Employee empl : getAllEmployees()) { if (empl.getEmail().equals(email)) { throw new IncorrectEmailException("Такой email существует"); } } Dbase.execInsert("Insert into EMPLOYEES (NAME,FAMILY,EMAIL)values('" + lname + "','" + fname + "','" + email + "')"); return 1; }
5
public static boolean moveSpot(NPC npc) { WorldTile key = new WorldTile(npc); WorldTile spot = moveSpots.get(key); if (spot == null && moveSpots.containsValue(key)) { for (WorldTile k : moveSpots.keySet()) { WorldTile v = moveSpots.get(k); if (v.getX() == key.getY() && v.getY() == key.getX() && v.getPlane() == key.getPlane()) { spot = k; break; } } } if (spot == null) return false; npc.setNextWorldTile(spot); return true; }
7
private void readBounds( BoxData<?> data, XElement xparent ) { XElement xbounds = xparent.getElement( "bounds" ); data.setX( xbounds.getElement( "x" ).getInt() ); data.setY( xbounds.getElement( "y" ).getInt() ); data.setWidth( xbounds.getElement( "width" ).getInt() ); data.setHeight( xbounds.getElement( "height" ).getInt() ); }
1
public static List<String> readWebPage(String url) { ArrayList<String> toRet = new ArrayList<String>(); @SuppressWarnings("resource") HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = null; do { try { response = client.execute(request); } catch (Exception e) { Logger.logException( "Problem occured while trying to get response from http request", e); break; } InputStream in = null; try { in = response.getEntity().getContent(); } catch (Exception e) { Logger.logException( "Problem occured while trying to get contents from http response", e); break; } BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = null; try { while ((line = reader.readLine()) != null) { toRet.add(line.trim()); } } catch (IOException e) { Logger.logException( "Problem occured while trying to read line from http response", e); break; } try { in.close(); } catch (IOException e) { Logger.logException( "Problem occured while trying to close the http contents stream", e); break; } } while (false); return toRet; }
6
public String echo(String input) throws java.rmi.RemoteException { connect(); if (echoSocket != null && os != null && is != null) { try { os.println(input); os.flush(); output= is.readLine(); } catch (IOException e) { System.err.println("I/O failed in reading/writing socket"); } } programDisconnection(); return output; }
4
@Test public void testPlayerIterator() { int i = 0; int count = 0; for (Player p : testGame.getTableIterator(players.get(i))) { assertEquals(players.get(i), p); i++; if (i == players.size()) { i = 0; } count++; } assertEquals(0, i); assertEquals(players.size(), count); i = 1; count = 0; for (Player p : testGame.getTableIterator(players.get(i))) { assertEquals(players.get(i), p); i++; if (i == players.size()) { i = 0; } count++; } assertEquals(1, i); assertEquals(players.size(), count); i = 2; count = 0; for (Player p : testGame.getTableIterator(players.get(i))) { assertEquals(players.get(i), p); i++; if (i == players.size()) { i = 0; } count++; } assertEquals(2, i); assertEquals(players.size(), count); i = 3; count = 0; for (Player p : testGame.getTableIterator(players.get(i))) { assertEquals(players.get(i), p); i++; if (i == players.size()) { i = 0; } count++; } assertEquals(3, i); assertEquals(players.size(), count); }
8
@Override protected Integer compute() { int sum = 0; if((start - end) < THRESHOLD){ for(int i = start; i< end;i++){ sum += i; } }else{ int middle = (start + end) /2; Calculator left = new Calculator(start, middle); Calculator right = new Calculator(middle + 1, end); left.fork(); right.fork(); sum = left.join() + right.join(); } return sum; }
2
public static void one_test(TestHolder test) throws Exception { System.out.print(test); char expect = test.expect.charAt(0); RE re; try { re = new RE(test.patt); } catch (RESyntaxException e) { boolean success = (expect == 'c'); // If we expected success but got failure, throw. if (!success) { throw(e); } return; } if (expect == 'c' /* && we are still here */) { throw new AssertionFailedError("Pattern compiled, but expected it to fail(c)"); } boolean matched = re.match(test.input); if (matched == (expect == 'y')) { System.out.println(passedMessage); } else { throw new AssertionFailedError(failedMessage + ": " + test); } }
4
@Override public void endElement(String uri, String localName, String qName) throws SAXException { // System.out.println("Ending -->" + qName); try { if (currenttag.equals(TagName.ID) && isFirst) { pageid = sb.toString(); currentPage.setId(pageid); isFirst = false; //IndexingTools.init(); } else if (qName.equals(TagName.TITLE)) { currentPage.setTitle(sb); } else if (qName.equals(TagName.TEXT)) { currentPage.setBodytext(sb); } else if (qName.equals(TagName.PAGE)) { // System.out.println("Page end"); // sb.setLength(0); IndexingTools.treatPage(currentPage); } else if(qName.equalsIgnoreCase(TagName.MEDIAWIKI) || qName.equalsIgnoreCase(TagName.FILE)) { System.out.println("End of media file Tag"); IndexingTools.fileend(); } } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } // System.out.println("String "+sb.toString()); // super.pendElement(uri, localName, qName); }
8
public boolean verifyJavaVersion() { if (!System.getProperty("os.name").startsWith("Windows")) { return true; } String version = System.getProperty("java.version"); double ver = Double.parseDouble(version.substring(0, 3)); int build = Integer.parseInt(version.substring(6)); return ver == JAVA_VERSION_REQUIRED && build >= JAVA_BUILD_REQUIRED; }
2
private void checkOSStarted(VirtualMachine virtualMachine) throws Exception { String startTimeout = virtualMachine .getProperty(VirtualMachineConstants.START_TIMEOUT); boolean checkTimeout = startTimeout != null; int remainingTries = 0; if (checkTimeout) { remainingTries = Integer.parseInt(startTimeout) / START_RECHECK_DELAY; } while (true) { try { ExecutionResult executionResult = exec(virtualMachine, "/bin/echo check-started"); HypervisorUtils.checkReturnValue(executionResult); break; } catch (Exception e) { if (checkTimeout && remainingTries-- == 0) { throw e; } } Thread.sleep(1000 * START_RECHECK_DELAY); } }
5
public static void main(String[] args) { Scanner inFile = null; try { // Create a scanner to read the file, file name is parameter inFile = new Scanner(new File(System.getProperty("user.dir") + "/src/Files/prog464a.dat")); } catch (FileNotFoundException e) { System.out.println("File not found!"); // Stop program if no file found System.exit(0); } // define array int array[][] = new int[5][5]; // loop for (int i = 0; i < 5; i++) { String[] current = inFile.nextLine().split(" "); for (int j = 0; j < 5; j++) { array[i][j] = Integer.valueOf(current[j]); } } // Print out array System.out.println("Original"); for (int[] row : array) { System.out.println(Arrays.toString(row).replace("[", "").replace("]", "").replace(",", "\t")); } System.out.println("With Totals:"); for (int[] row : array) { // System.out.println(Arrays.toString(row).replace("[", "").replace("]", "").replace(",", "\t") + "\t" + IntStream.of(row).sum()); } for (int k = 0; k < array.length; k++){ int total = 0; for (int i = 0; i < array.length; i++){ total += array[i][k]; } System.out.print(total + "\t"); } }
7
@Override protected boolean canFigureMove(Point x, Point Abs) { if (((x.x == 2 || x.x == -2) && (x.y == 1 || x.y == -1) || (x.y == 2 || x.y == -2) && (x.x == 1 || x.x == -1)) && !C.isFigure(Abs)) return true; return false;}
9
public ExternalFilesystem(String basedir) throws IOException { if (basedir.endsWith("/") || basedir.endsWith("\\")) basedir = basedir.substring(0, basedir.length() - 1); baseDirectory = new File(basedir); if (!baseDirectory.exists()) throw new IOException("Directory '" + basedir + "' doesn't exist"); if (!baseDirectory.isDirectory()) throw new IOException(basedir + " isn't a directory"); }
4
public static QuadVector<String,Integer,Integer,Boolean> cabilities(HTTPRequest httpReq) { final QuadVector<String,Integer,Integer,Boolean> theclasses=new QuadVector<String,Integer,Integer,Boolean>(); if(httpReq.isUrlParameter("CABLES1")) { int num=1; String behav=httpReq.getUrlParameter("CABLES"+num); while(behav!=null) { if(behav.length()>0) { String prof=httpReq.getUrlParameter("CABPOF"+num); if(prof==null) prof="0"; String qual=httpReq.getUrlParameter("CABQUA"+num); if(qual==null) qual="";// null means unchecked String levl=httpReq.getUrlParameter("CABLVL"+num); if(levl==null) levl="0"; theclasses.addElement(behav,Integer.valueOf(CMath.s_int(prof)),Integer.valueOf(CMath.s_int(levl)),qual.equals("on")?Boolean.TRUE:Boolean.FALSE); } num++; behav=httpReq.getUrlParameter("CABLES"+num); } } return theclasses; }
7
public static void main(String args[]) { int a = 0; int b = 0; int c = 0; int sum; int sqr; int product; loop : for (c = 2; c > 0; c++) { for (b = 1; b < c; b++) { for (a = 1; a < b; a++) { sqr =(int)(Math.pow(a, 2) + Math.pow(b, 2)); sum = a + b +c ; if(sqr==(c*c) && sum==1000){ break loop; } } } } product = a*b*c; System.out.println(product); }
5
public void setNeighbors(Cell[] neighbors) { this.neighbors = neighbors; }
0
private void handleError(String message, Exception e) { MessageDialog.getInstance().showError(message); LOGGER.error(message, e); }
0
private List<MorrisLineAdjacent> getSkewUpLineAdjacent() { List<MorrisLineAdjacent> lines = new ArrayList<MorrisLineAdjacent>(); boolean bsru = this.hasSkewRightUp(); boolean bsld = this.hasSkewLeftDown(); MorrisLineAdjacent oneLine = null; if (bsru && bsld) { //this is in the middle oneLine = new MorrisLineAdjacent(this, this.skewRightUp(), this.down()); lines.add(oneLine); } else { if (bsru) { //this is in the most skew left down MorrisIntersection sru = this.skewRightUp(); if (sru.hasSkewRightUp()) { oneLine = new MorrisLineAdjacent(this, sru, sru.skewRightUp()); lines.add(oneLine); } } if (bsld) { //this is in the most skew right up MorrisIntersection sld = this.skewLeftDown(); if (sld.hasSkewRightDown()) { oneLine = new MorrisLineAdjacent(this, sld, sld.skewLeftDown()); lines.add(oneLine); } } } return lines; }
6
private NoB busca(NoB no, int x) { NoB pt = no; if (pt == null) return null ; //nao achou else { pt = pt.proximo; while (pt.proximo != null && pt.chave < x) pt = pt.proximo; if (pt.chave < x && pt.pagina != null) pt = busca(pt.pagina,x); else if (pt.chave > x && pt.anterior.pagina != null) pt = busca(pt.anterior.pagina,x); return(pt); } }
7
public long getTransferRate() { long time = (System.currentTimeMillis() - _startTime) / 1000; if (time <= 0) { return 0; } return getProgress() / time; }
1
public void detectAll(){ for(int baud : BAUD_RATES) { SerialPort serialPort = null; InputStream in = null; OutputStream out = null; try { log.info("Opening serial port..."); serialPort = (SerialPort) portIdentifier.open("ATDeviceDetector", 2000); log.info("Port opened. Setting flow control mode..."); serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN); log.info("Flow control mode set. Setting port params..."); serialPort.setSerialPortParams(baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); log.info("Port params set. Opening input stream..."); in = serialPort.getInputStream(); log.info("Input stram opened. Opening output stream..."); out = serialPort.getOutputStream(); log.info("Output stream opened. Enabling receive timeout..."); serialPort.enableReceiveTimeout(1000); log.info("Receive timeout enabled."); log.trace("LOOPING."); // discard all data currently waiting on the input stream Utils.readAll(in); Utils.writeCommand(out, "AT"); Thread.sleep(1000); String response = Utils.readAll(in); if(!Utils.isResponseOk(response)) { //throw new ATDeviceDetectionException("Bad response: " + response); } serial = getSerial(in, out); maxBaudRate = Math.max(maxBaudRate, baud); // detection is complete, so let's try and get the device manufacturer, model and phone number manufacturer = getManufacturer(in, out); model = getModel(in, out); phoneNumber = getPhoneNumber(in, out); lockType = getLockType(in, out); setSmsSupport(in, out); imsi = getImsi(in, out); } catch(Exception ex) { } finally { if(out != null) try { out.close(); } catch(Throwable t) { log.warn("Error closing output stream.", t); } if(in != null) try { in.close(); } catch(Throwable t) { log.warn("Error closing input stream.", t); } } finished = true; log.info("Detection completed on port: " + this.portIdentifier.getName() + "; manufacturer: " + manufacturer + "; model: " + model + "; phoneNumber: " + phoneNumber); } }
7
public void monitotarPressao(float pressao, Paciente paciente) throws ControllerException { try { if (pressao < 0 || pressao > 30) { throw new ControllerException("valor da pressão é inválido"); } if (ValidarPaciente(paciente) && (pressao < 8 || pressao > 12)) { Publish publish = new Publish(paciente.getIdTopico(), uriHub); Evento evento = new Evento(PRESSAO + "=" + pressao, Calendar.getInstance(), paciente); eventoDAO.save(evento); publish.publish(evento.getDescricao()); } } catch (ObjetoNuloException | ValorInvalidoException e) { throw new ControllerException(e.getMessage()); } catch (ComunicationException e) { throw new ControllerException(e.getMessage()); } catch (DAOException e) { throw new ControllerException(e.getMessage()); } }
8
public CheckResultMessage checkDayofMonth() { int r1 = get(2, 2); int c1 = get(3, 2); date(); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if (!(getValueString(r1 + 1, c1 - 1, 0) .equals(lastMaxDay + "日") && getValueString( r1 + 1 + maxDay, c1 - 1, 0).equals(maxDay + "日"))) { return error("日期设置错误!<" + fileName + ">" + " Sheet:1-1" + ", 应设为上月最后日期:" + lastMaxDay + "日"); } in.close(); } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); if (!(getValueString1(r1 + 1, c1 - 1, 0).equals( lastMaxDay + "日") && (getValueString1(r1 + 1 + maxDay, c1 - 1, 0).equals(maxDay + "日")))) { return error("日期设置错误!<" + fileName + ">" + " Sheet:1-1" + ", 应设为上月最后日期:" + lastMaxDay + "日"); } in.close(); } catch (Exception e) { } } return pass("支付支付机构单个账户表格:<" + fileName + ">Sheet:1-1日期核对正确"); }
7
private final int method1104(Model class124_101_, int i, int i_102_, short i_103_) { anInt1858++; int i_104_ = ((Model) class124_101_).vertexX[i_102_]; int i_105_ = ((Model) class124_101_).vertexY[i_102_]; int i_106_ = ((Model) class124_101_).vertexZ[i_102_]; for (int i_107_ = i; i_107_ < ((Model) this).vertices; i_107_++) { if (((Model) this).vertexX[i_107_] == i_104_ && i_105_ == ((Model) this).vertexY[i_107_] && ((((Model) this).vertexZ[i_107_] ^ 0xffffffff) == (i_106_ ^ 0xffffffff))) { ((Model) this).aShortArray1842[i_107_] = (short) Class273.bitOr((((Model) this) .aShortArray1842[i_107_]), i_103_); return i_107_; } } ((Model) this).vertexX[((Model) this).vertices] = i_104_; ((Model) this).vertexY[((Model) this).vertices] = i_105_; ((Model) this).vertexZ[((Model) this).vertices] = i_106_; ((Model) this).aShortArray1842[((Model) this).vertices] = i_103_; ((Model) this).vgroups[((Model) this).vertices] = (((Model) class124_101_).vgroups != null ? ((Model) class124_101_).vgroups[i_102_] : -1); return ((Model) this).vertices++; }
5
private Dock getDockInternal() { for (DockLayoutNode child : mChildren) { if (child instanceof DockContainer) { return (Dock) ((DockContainer) child).getParent(); } else if (child instanceof DockLayout) { Dock dock = ((DockLayout) child).getDockInternal(); if (dock != null) { return dock; } } } return null; }
4
public void run() { try { writeRouteLog(msgEvent, msg); Logger.getLogger(WriteLog.class.getName()).log(Level.SEVERE, "Записано " + WriteLog.getCurrentTime()); } catch (IOException ex) { Logger.getLogger(WriteLog.class.getName()).log(Level.SEVERE, null, ex); } }
1
private static Object normaliseObject( Object o ) { if ( o instanceof Integer ){ o = new Long(((Integer)o).longValue()); }else if ( o instanceof Boolean ){ o = new Long(((Boolean)o).booleanValue()?1:0); }else if ( o instanceof Float ){ o = String.valueOf((Float)o); }else if ( o instanceof byte[] ){ try{ o = new String((byte[])o,"UTF-8"); }catch( Throwable e ){ } } return( o ); }
6
public void saveAlbumsPhotos(String folderToSave) { MyDownloadExecutor executor = new MyDownloadExecutor(nThreads); for (Album album : albums) { File folder = new File(folderToSave + album.getAid() + "_" + fixWindowsFileName(album.getTitle())); boolean success = folder.mkdirs(); System.out.println("created folder: " + folder.getAbsolutePath() + " " + success); for (Photo photo : album.getPhotos()) { File dest = new File(folder.getAbsolutePath() + "/" + photo.getFileName()); if (!dest.exists() || dest.length() < 120) { executor.jobsCountInc(); executor.execute(new Downloader(photo.getSrc(), dest, executor)); downloadedPhotosCount++; } else { System.out.println(dest + " already exists"); } } } if (downloadedPhotosCount == 0) { executor.shutdown(); } try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("All photos try to download."); }
6
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(GUI_mp3player.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI_mp3player.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI_mp3player.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI_mp3player.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 GUI_mp3player().setVisible(true); } }); }
6
public void keyPressed(KeyEvent e) { int keycode = e.getKeyCode(); System.out.println("key pressed: "); switch(keycode) { case KeyEvent.VK_UP: System.out.println("up"); this.upPress = true; break; case KeyEvent.VK_DOWN: System.out.println("down"); this.downPress = true; break; case KeyEvent.VK_LEFT: System.out.println("left"); this.leftPress = true; break; case KeyEvent.VK_RIGHT: System.out.println("right"); this.rightPress = true; break; case KeyEvent.VK_SPACE: System.out.println("space"); this.spacePress = true; break; case KeyEvent.VK_ESCAPE: System.out.println("escape!"); this.escPressed = true; }// end switch e.consume(); //Game_Screen.keyAction(); }
6
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(ImageDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ImageDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ImageDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ImageDisplay.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 ImageDisplay().setVisible(true); } }); }
6
private ButtonType getButtonType(int keyCode) { switch (keyCode) { case KeyEvent.VK_UP: return ButtonType.Up; case KeyEvent.VK_DOWN: return ButtonType.Down; case KeyEvent.VK_LEFT: return ButtonType.Left; case KeyEvent.VK_RIGHT: return ButtonType.Right; case KeyEvent.VK_SPACE: return ButtonType.A; case KeyEvent.VK_CONTROL: return ButtonType.B; case KeyEvent.VK_ENTER: case KeyEvent.VK_ESCAPE: return ButtonType.Start; } return null; }
8
public void testWithFieldAdded_DurationFieldType_int_5() { LocalDate test = new LocalDate(2004, 6, 9); try { test.withFieldAdded(DurationFieldType.hours(), 6); fail(); } catch (IllegalArgumentException ex) {} }
1
public static <T, E extends Exception> T validateHandler(OwnerView view, T parameterToValidate, Validator<T, E> validator, MethodProvider<T> methodProvider) { List<E> validateExceptionList = validator.validate(parameterToValidate); if (!validateExceptionList.isEmpty()) { view.printValidateExceptionsList(validateExceptionList); parameterToValidate = methodProvider.implOfMethodToProvide(); } return parameterToValidate; }
1
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(((msg.targetMajor()&CMMsg.MASK_MALICIOUS)>0) &&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS)) &&((msg.amITarget(affected)))) { final MOB target=(MOB)msg.target(); if((!target.isInCombat()) &&(msg.source().isMonster()) &&(msg.source().location()==target.location()) &&(msg.source().getVictim()!=target)) { msg.source().tell(L("Attack a plant?!")); if(target.getVictim()==msg.source()) { target.makePeace(true); target.setVictim(null); } return false; } } return super.okMessage(myHost,msg); }
8
public List<Speciality> getSpecialityList() { return specialityList; }
0
private static void printMembers(Member[] mems){ for (Member m : mems) { Annotation[] annotations = new Annotation[0]; if (m instanceof Field) { annotations = ((Field)m).getAnnotations(); } if (m instanceof Constructor) { annotations = ((Constructor<?>)m).getAnnotations(); } if (m instanceof Method) { annotations = ((Method)m).getAnnotations(); } if (m.getDeclaringClass() == Object.class) continue; String decl = m.toString().replaceAll(ClassContents.ignoreName(), ""); //String decl = m.toString(); System.out.print(" "); System.out.println(decl); for (Annotation ano : annotations) System.out.println(ano.toString()); } }
7
final Class27_Sub1 method703(boolean flag1, int i) { Class27_Sub1 class27Sub1 = (Class27_Sub1) Class142_Sub27_Sub6.aMRUNodes_4752.getObjectForID((flag1 ? 0x40000 : 0) | (anInt1013 | i << 16)); if (class27Sub1 != null) { return class27Sub1; } Class137.aClass73_2264.method791(anInt1013); class27Sub1 = Class153.method2030((byte) 80, anInt1013, Class137.aClass73_2264, 0); if (class27Sub1 != null) { class27Sub1.method319(Class141.anInt2307, Class16.anInt262, Class52.anInt856); class27Sub1.anInt497 = ((Class27) (class27Sub1)).anInt505; class27Sub1.anInt503 = ((Class27) (class27Sub1)).anInt508; if (flag1) { class27Sub1.method316(); } for (int j = 0; ~i < ~j; j++) { class27Sub1.method320(); } Class142_Sub27_Sub6.aMRUNodes_4752.addObject(i << 16 | anInt1013 | (flag1 ? 0x40000 : 0), class27Sub1); } return class27Sub1; }
6
public double evaluateSubset (BitSet subset) throws Exception { int [] fs; int i; int count = 0; for (i=0;i<m_numAttribs;i++) { if (subset.get(i)) { count++; } } double [] instArray = new double[count]; int index = 0; fs = new int[count]; for (i=0;i<m_numAttribs;i++) { if (subset.get(i)) { fs[index++] = i; } } // create new hash table m_table = new Hashtable((int)(m_numInstances * 1.5)); for (i=0;i<m_numInstances;i++) { Instance inst = m_trainInstances.instance(i); for (int j=0;j<fs.length;j++) { if (fs[j] == m_classIndex) { throw new Exception("A subset should not contain the class!"); } if (inst.isMissing(fs[j])) { instArray[j] = Double.MAX_VALUE; } else { instArray[j] = inst.value(fs[j]); } } insertIntoTable(inst, instArray); } return consistencyCount(); }
8
public void readXML() { try { File xmlFile = new File("basedados.xml"); DocumentBuilderFactory documentFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder documentBuilder = documentFactory .newDocumentBuilder(); Document doc = documentBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("HOST"); HashMap<String, String> mapa = new HashMap<String, String>(); //System.out.println("Root element :" //+ doc.getDocumentElement().getNodeName()); for (int temp = 0; temp < nodeList.getLength(); temp++) { Node node = nodeList.item(temp); //System.out.println("\nElement type :" + node.getNodeName()); System.out.println("\n"); if (node.getNodeType() == Node.ELEMENT_NODE) { Element host = (Element) node; String nome = host.getAttribute("name"); //System.out.println(nome); String porcentagem = host.getAttribute("H_CPU"); //System.out.println(porcentagem); mapa.put(nome, porcentagem); Set<String> chaves = mapa.keySet(); for (String chave : chaves) { if(chave != null) System.out.println(chave + " = " + mapa.get(chave)); } /*System.out.println("Host name : " + host.getAttribute("name")); System.out.println("Percentage : " + host.getAttribute("H_CPU")); System.out.println("Total Cores : " + host.getAttribute("O_CPU_TOTAL")); System.out.println("Cores Used : " + host.getAttribute("O_CPU_USED"));*/ } //fimif } //fimfor } //fimtry catch (Exception e) { e.printStackTrace(); }//fimcatch } //fim_metodo
5
public String getName(){ return file.getName(); }
0
public static MDDManager getProxy(MDDStore store, List<?> customOrder) { MDDVariable[] rawVariables = store.getAllVariables(); // build order mapping boolean sameOrder = rawVariables.length == customOrder.size(); int[] custom2store = new int[customOrder.size()]; for (int i=0 ; i<custom2store.length ; i++) { custom2store[i] = -1; } int i = 0; for (Object v: customOrder) { MDDVariable var = store.getVariableForKey(v); if (var.order != i) { sameOrder = false; } custom2store[i] = var.order; i++; } if (sameOrder) { // no order mapping is needed return store; } // save the order mapping and compute the reverse one int[] store2custom = new int[rawVariables.length]; for (i=0 ; i<store2custom.length ; i++) { store2custom[i] = -1; } i=0; for (int k: custom2store) { if (k >= 0) { store2custom[k] = i; } i++; } return new MDDManagerProxy(store, custom2store, store2custom); }
8
private void loadAvaliblePlattformar() { try { ArrayList<String> plattemp = DB.fetchColumn("select pid from PLATTFORM"); ArrayList<Plattform> platt = new ArrayList<>(); for (String st : plattemp) { platt.add(new Plattform(Integer.parseInt(st))); } for (Plattform pt : platt) { cbPlattform.addItem(pt); } } catch (InfException e) { e.getMessage(); } }
3
public boolean checkBlockInitializer(InvokeOperator invoke) { if (!invoke.isThis() || invoke.getFreeOperandCount() != 0) return false; MethodAnalyzer methodAna = invoke.getMethodAnalyzer(); if (methodAna == null) return false; FlowBlock flow = methodAna.getMethodHeader(); MethodType methodType = methodAna.getType(); if (!methodAna.getName().startsWith("block$") || methodType.getParameterTypes().length != 0 || methodType.getReturnType() != Type.tVoid) return false; if (flow == null || !flow.hasNoJumps()) return false; if (!isThis(invoke.getSubExpressions()[0], clazzAnalyzer.getClazz())) return false; methodAna.setJikesBlockInitializer(true); transformBlockInitializer(flow.block); return true; }
9
private HashMap<Article, Location> findArticle(int articleID, int quantity) { HashMap<Article, Location> map = new HashMap<Article, Location>(); for (Location location : locations) { for (int i = 0; i < location.getArticles().size() && quantity > 0; i++) { if (location.getArticles().get(i).getArticleID() == articleID) { map.put(location.getArticles().get(i), location); quantity--; } } } return map; }
4
protected Container createComboBox(final Object[] args) { final String tip = ((args.length > 0) && (args[0] != null)) ? args[0].toString() : null; final String text = ((args.length > 1) && (args[1] != null)) ? args[1].toString() : null; final Object imageArg = args[2]; final Dimension size = ((args.length > 3) && (args[3] instanceof Dimension)) ? (Dimension) args[3] : new Dimension(-1, -1); if (classComboBox != ComboBox.class) { try { return (Container) classComboBox.newInstance(); } catch (final Throwable exp) { } } return new ComboBox(tip, (imageArg == null) ? text : null, imageArg, size); }
9
public void close() { ServerLogger.info(Server.class, "Closing server", null); stopDataServers(); try { outputStream.close(); } catch (IOException e) { // do nothing } try { inputStream.close(); } catch (IOException e) { // do nothing } try { connectionSocket.close(); } catch (IOException e) { // do nothing } }
3
public void sendInterrupt (byte buf []) throws IOException { if ("interrupt" != getType () || buf.length > getMaxPacketSize ()) throw new IllegalArgumentException (); if (spi == null) spi = iface.getDevice ().getSPI (); // FIXME getInterval() ms timeout (caller guarantees periodicity) spi.writeIntr (getU8 (2), buf); }
3
public void bubble () { char temp; // tijdelijke opslag van de waarde int i, j; // waarde 1, 2 for (j = 0; j < rij.length; j++) // voor elke j kleiner dan de lengte van rij { for (i = 1; i < rij.length - j; i++) // voor elke i kleiner dan de lengte van rij - j { if(rij[i-1] > rij[i]) // conditie testen. is rij i-1 groter dan rij i de conditie uitvoeren en de waardes wisselen. { temp = rij[i]; // de rij[i] waarde in een temp(orary) variabele opslaan rij[i] = rij[i-1]; // de kleinste waarde omzetten naar de rechter waarde rij[i-1] = temp; // de tijdelijke waarde op de plaats van de linker waarde terugzetten } } } }
3
private void updateQueues() { while(!taskSet.isEmpty() && taskSet.peek().getArrivalTime() <= currentTime) { if(isPreSatisfied(taskSet.peek())) { readyQueue.addLast(taskSet.poll()); } else { Task t = taskSet.poll(); t.setWaiting(); waitQueue.addLast(t); } } for(Task t : waitQueue) { if(isPreSatisfied(t)) { readyQueue.addLast(t); } } for(Task t : readyQueue) { waitQueue.remove(t); } if(currentTask != null) { /* current task not preempted*/ if(getEffectiveDeadline(currentTask) <= getMinDeadline(getEffectiveDeadline(currentTask))) { readyQueue.addFirst(currentTask); } else { /*current task gets preempted, add to end of the queue*/ System.out.println(currentTime + " " + currentTask.getName() + " gets preempted"); currentTask.setReady(); readyQueue.addLast(currentTask); } } Collections.sort(readyQueue, new Comparator<Task>(){ public int compare(Task t1, Task t2) { return getEffectiveDeadline(t1) - getEffectiveDeadline(t2); } }); }
8
public PublicKey decodePublicKey(byte[] k) { // magic if (k[0] != Registry.MAGIC_RAW_RSA_PUBLIC_KEY[0] || k[1] != Registry.MAGIC_RAW_RSA_PUBLIC_KEY[1] || k[2] != Registry.MAGIC_RAW_RSA_PUBLIC_KEY[2] || k[3] != Registry.MAGIC_RAW_RSA_PUBLIC_KEY[3]) { throw new IllegalArgumentException("magic"); } // version if (k[4] != 0x01) { throw new IllegalArgumentException("version"); } int i = 5; int l; byte[] buffer; // n l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8 | (k[i++] & 0xFF); buffer = new byte[l]; System.arraycopy(k, i, buffer, 0, l); i += l; BigInteger n = new BigInteger(1, buffer); // e l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8 | (k[i++] & 0xFF); buffer = new byte[l]; System.arraycopy(k, i, buffer, 0, l); i += l; BigInteger e = new BigInteger(1, buffer); return new GnuRSAPublicKey(n, e); }
5
public static int byteArrayToInt(byte[] b) { // 0是高位,3是低位 // 每次取最高8位 int i = (b[0] << 24) & 0xFF000000; i |= (b[1] << 16) & 0xFF0000; i |= (b[2] << 8) & 0xFF00; i |= b[3] & 0xFF; return i; }
0
@SuppressWarnings("unchecked") public List<Customer> getAllCustomers() { return (List<Customer>) this.em.createNamedQuery("findAllCustomers") .getResultList(); }
0
public Instruction newInstruction(MethodModel _methodModel, ByteReader byteReader, boolean _isWide) { Instruction newInstruction = null; if (clazz != null) { try { final Constructor<?> constructor = clazz.getDeclaredConstructor(MethodModel.class, ByteReader.class, boolean.class); newInstruction = (Instruction) constructor.newInstance(_methodModel, byteReader, _isWide); newInstruction.setLength(byteReader.getOffset() - newInstruction.getThisPC()); } catch (final SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return (newInstruction); }
8
@SuppressWarnings("rawtypes") private String getEnumValue(final Field field, final Object object) { String resValue = null; Object value = getRawValue(field, object); if (value != null) { int valEnum = ((Enum) value).ordinal(); resValue = String.valueOf(valEnum); } return resValue; }
1
@SuppressWarnings("unchecked") private void initGUI() { // C O M P O N E N T S --------------------------------------------- this.jcbState = new JComboBox<ImageIcon>(EzimImage.icoStates); this.jcbState.setEditable(false); this.jcbState.addItemListener ( new ItemListener() { public void itemStateChanged(ItemEvent evtTmp) { if (ItemEvent.SELECTED == evtTmp.getStateChange()) EzimMain.this.jcbState_StateChanged(); } } ); this.jcbState.setToolTipText(EzimLang.ClickToChangeState); this.etfStatus = new EzimTextField ( new EzimPlainDocument(EzimNetwork.maxAckLength) , EzimContact.STATUS_DEFAULT , 1 , false ); this.etfStatus.setEnabled(false); this.etfStatus.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent evtTmp) { EzimMain.this.etfStatus_ActionPerformed(); } } ); this.etfStatus.addMouseListener ( new MouseListener() { public void mouseClicked(MouseEvent evtTmp) { EzimMain.this.etfStatus_MouseClicked(); } public void mouseEntered(MouseEvent evtTmp) { } public void mouseExited(MouseEvent evtTmp) { } public void mousePressed(MouseEvent evtTmp) { } public void mouseReleased(MouseEvent evtTmp) { } } ); this.etfStatus.addFocusListener ( new FocusListener() { public void focusGained(FocusEvent evtTmp) { } public void focusLost(FocusEvent evtTmp) { EzimMain.this.etfStatus_FocusLost(); } } ); this.etfStatus.setToolTipText(EzimLang.ClickToChangeStatus); this.jlstContacts = new JList<EzimContact> ( EzimContactList.getInstance() ); this.jlstContacts.setCellRenderer(new EzimContactListRenderer()); this.jlstContacts.setSelectionMode ( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); this.jlstContacts.setTransferHandler ( EzimContactTransferHandler.getInstance() ); this.jlstContacts.setDragEnabled(true); this.jlstContacts.addMouseListener ( new MouseListener() { public void mouseClicked(MouseEvent evtTmp) { if ( evtTmp.getButton() == MouseEvent.BUTTON1 && evtTmp.getClickCount() > 1 ) { EzimMain.this.jlstContacts_MouseDblClicked(); } } public void mouseEntered(MouseEvent evtTmp) { } public void mouseExited(MouseEvent evtTmp) { } public void mousePressed(MouseEvent evtTmp) { } public void mouseReleased(MouseEvent evtTmp) { } } ); this.jspContacts = new JScrollPane(this.jlstContacts); this.jspContacts.setPreferredSize(new Dimension(1, 100)); this.jbtnMsg = new JButton(EzimImage.icoButtons[0]); this.jbtnMsg.setPreferredSize(new Dimension(32, 32)); this.jbtnMsg.setToolTipText(EzimLang.SendMessageToContact); this.jbtnMsg.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent evtTmp) { EzimMain.this.jbtnMsg_ActionPerformed(); } } ); this.jbtnFtx = new JButton(EzimImage.icoButtons[1]); this.jbtnFtx.setPreferredSize(new Dimension(32, 32)); this.jbtnFtx.setToolTipText(EzimLang.SendFileToContact); this.jbtnFtx.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent evtTmp) { EzimMain.this.jbtnFtx_ActionPerformed(); } } ); this.jbtnRfh = new JButton(EzimImage.icoButtons[2]); this.jbtnRfh.setPreferredSize(new Dimension(32, 32)); this.jbtnRfh.setToolTipText(EzimLang.RefreshContactList); this.jbtnRfh.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent evtTmp) { EzimMain.this.jbtnRfh_ActionPerformed(); } } ); this.jbtnPlz = new JButton(EzimImage.icoButtons[3]); this.jbtnPlz.setPreferredSize(new Dimension(32, 32)); this.jbtnPlz.setToolTipText(EzimLang.PlazaOfSpeech); this.jbtnPlz.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent evtTmp) { EzimMain.this.jbtnPlz_ActionPerformed(); } } ); this.jbtnPrefs = new JButton(EzimImage.icoButtons[4]); this.jbtnPrefs.setPreferredSize(new Dimension(32, 32)); this.jbtnPrefs.setToolTipText(EzimLang.Prefs); this.jbtnPrefs.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent evtTmp) { EzimMain.this.jbtnPrefs_ActionPerformed(); } } ); this.jlblAbout = new JLabel(EzimImage.icoLblAbout); this.jlblAbout.setPreferredSize(new Dimension(16, 16)); this.jlblAbout.addMouseListener ( new MouseListener() { public void mouseClicked(MouseEvent evtTmp) { EzimMain.this.jlblAbout_MouseClicked(); } public void mouseEntered(MouseEvent evtTmp) { } public void mouseExited(MouseEvent evtTmp) { } public void mousePressed(MouseEvent evtTmp) { } public void mouseReleased(MouseEvent evtTmp) { } } ); this.jpnlBase = new JPanel(); this.add(this.jpnlBase); // L A Y O U T ----------------------------------------------------- GroupLayout glBase = new GroupLayout(this.jpnlBase); this.jpnlBase.setLayout(glBase); glBase.setAutoCreateGaps(true); glBase.setAutoCreateContainerGaps(true); GroupLayout.SequentialGroup hGrp = glBase.createSequentialGroup(); hGrp.addGroup ( glBase.createParallelGroup() .addGroup ( glBase.createSequentialGroup() .addComponent ( this.jcbState , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.etfStatus , GroupLayout.DEFAULT_SIZE , GroupLayout.PREFERRED_SIZE , Short.MAX_VALUE ) ) .addGroup ( glBase.createSequentialGroup() .addComponent ( this.jspContacts , GroupLayout.DEFAULT_SIZE , GroupLayout.PREFERRED_SIZE , Short.MAX_VALUE ) ) .addGroup ( glBase.createSequentialGroup() .addComponent ( this.jbtnMsg , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnFtx , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnRfh , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnPlz , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnPrefs , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) ) .addGroup ( glBase.createSequentialGroup() .addContainerGap ( 0 , Short.MAX_VALUE ) .addComponent ( this.jlblAbout , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) ) ); glBase.setHorizontalGroup(hGrp); GroupLayout.SequentialGroup vGrp = glBase.createSequentialGroup(); glBase.linkSize ( SwingUtilities.VERTICAL , this.jcbState , this.etfStatus ); vGrp.addGroup ( glBase.createParallelGroup(Alignment.BASELINE) .addComponent ( this.jcbState , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.etfStatus , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) ); vGrp.addGroup ( glBase.createParallelGroup(Alignment.BASELINE) .addComponent ( this.jspContacts , GroupLayout.DEFAULT_SIZE , GroupLayout.PREFERRED_SIZE , Short.MAX_VALUE ) ); vGrp.addGroup ( glBase.createParallelGroup(Alignment.BASELINE) .addComponent ( this.jbtnMsg , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnFtx , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnRfh , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnPlz , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) .addComponent ( this.jbtnPrefs , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) ); vGrp.addGroup ( glBase.createParallelGroup(Alignment.BASELINE) .addComponent ( this.jlblAbout , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE , GroupLayout.PREFERRED_SIZE ) ); glBase.setVerticalGroup(vGrp); // W I N D O W L I S T E N E R ----------------------------------- this.addWindowListener(this); // T R A Y I C O N ----------------------------------------------- if (SystemTray.isSupported()) this.initTrayIcon(); else this.tiMain = null; }
4
public void update(float delta){ Vector2D position = circleShape.getPosition(); if((position.x -radius/2)<0){ circleShape.setXPosition(radius/2); velocity.thisBounceNormal(new Vector2D(1,0));} if((position.x +radius/2)>GamePanel.WIDTH){ circleShape.setXPosition(GamePanel.WIDTH-radius/2);velocity.thisBounceNormal(new Vector2D(-1,0));} if((position.y -radius/2)<0){circleShape.setYPosition(radius/2);velocity.thisBounceNormal(new Vector2D(0,1));} if((position.y +radius/2)>GamePanel.HEIGHT){ circleShape.setYPosition(GamePanel.HEIGHT-radius/2);velocity.thisBounceNormal(new Vector2D(0,-1));} Vector2D c = new Vector2D(position.x - Mouse.x, position.y -Mouse.y); if (c.length() < 100){ c.thisNormalize(); c.thisScale(1); velocity.thisAdd(c); } if (velocity.length() > 20) { velocity.thisNormalize(); velocity.thisScale(10); } position.thisAdd(velocity.scale(delta)); }
6
@Test public void runTestArrayAccess2() throws IOException { InfoflowResults res = analyzeAPKFile("ArraysAndLists_ArrayAccess2.apk"); Assert.assertEquals(0, res.size()); }
0
public static boolean isValidOption(String option) { if (GRE_OPTION_A.equals(option) || GRE_OPTION_B.equals(option) || GRE_OPTION_C.equals(option) || GRE_OPTION_D.equals(option) || GRE_OPTION_E.equals(option)) { return true; } return false; }
5
private void method392(byte abyte0[], int i, int j, int k, int l, int i1) { int j1 = i + j * width; int k1 = width - k; int l1 = 0; int i2 = 0; if (j < topY) { int j2 = topY - j; l -= j2; j = topY; i2 += j2 * k; j1 += j2 * width; } if (j + l >= bottomY) l -= ((j + l) - bottomY); if (i < topX) { int k2 = topX - i; k -= k2; i = topX; i2 += k2; j1 += k2; l1 += k2; k1 += k2; } if (i + k >= bottomX) { int l2 = ((i + k) - bottomX); k -= l2; l1 += l2; k1 += l2; } if (!(k <= 0 || l <= 0)) { method393(pixels, abyte0, i1, i2, j1, k, l, k1, l1); } }
6
void loadSettings(String name, String value) throws Exception { if(name==null) return; if(name.equals("name")) { //$NON-NLS-1$ documentName=value; } if(name.equals("author")) { //$NON-NLS-1$ documentAuthor=value; } if(name.equals("date")) { //$NON-NLS-1$ documentDate=new SimpleDateFormat("yyyy/MM/dd").parse(value); //$NON-NLS-1$ } if(name.equals("truck-width")) { //$NON-NLS-1$ documentTruckSize.width=new Integer(value); } if(name.equals("truck-height")) { //$NON-NLS-1$ documentTruckSize.height=new Integer(value); } if(name.equals("truck-tonnage")) { //$NON-NLS-1$ documentTruckTonnage=new Integer(value); } }
7
private void createSlide(Attributes attrs) { slide = new Slide(slideDef); // loop through all attributes, setting appropriate values for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName(i).equals("id")) slide.setId(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("backgroundcolor")) slide.setBkCol(new Color(Integer.valueOf(attrs.getValue(i) .substring(1), 16))); else if (attrs.getQName(i).equals("duration")) slide.setDuration(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("nextslideid")) slide.setNext(Integer.valueOf(attrs.getValue(i))); else if (attrs.getQName(i).equals("previewpath")){ String path = attrs.getValue(i).replace('\\', '/'); if (isLocal(path)){ int directoryPathEnd = xmlPath.lastIndexOf('/'); String directoryPath = xmlPath.substring(0, directoryPathEnd + 1); slide.setPrevPath(directoryPath + path); }else { // if remote download file and insert local path try { slide.setPrevPath(RemoteFileRetriever.downloadFile(path)); } catch (MalformedURLException e) { System.out.println("Could not download remote preview image" + e.getMessage()); } } } slide.setPrevPath(attrs.getValue(i)); } }
8
public float getPhysicalWidthInch() { int w = getWidth(); int pw = getPhysicalWidthDpi(); if (w > 0 && pw > 0) { return ((float)w) / ((float)pw); } else { return -1.0f; } }
2
public static int getID(String usu){ String sql = " SELECT idusuarios FROM usuarios WHERE usuario = '"+usu+"' "; if(!BD.getInstance().sqlSelect(sql)){ return 0; } if(!BD.getInstance().sqlFetch()){ return 0; } return BD.getInstance().getInt("idusuarios"); }
2
public void step() { if (board.getState() == State.GAME_OVER) { board.clear(); board.setState(State.PLAYING); } if (board.fallingBlock == null) { board.addFallingBlock(tm.getPoly(rand.nextInt(tm.getNumberOfTypes()))); } if (CollisionDetector.collision(board, board.fallingBlock, Action.MOVE_DOWN)) { board.stickFallingBlock(); if (board.fallingBlock.position.y == 1) { board.setState(State.GAME_OVER); } board.fallingBlock = null; board.removeFullRows(); } else { board.moveFallingBlock(Board.Move.DOWN); } }
4
public ProductDao getProductDao(){ if(productDao==null) productDao=new ProductDaoImpl(); return productDao; }
1
protected Figure createFigure(Point[] points, int numPoints, boolean closed) { ContainerFigure container = new ContainerFigure(); if (closed && settings.commonFillType != ToolSettings.ftNone && numPoints >= 3) { container.add(new SolidPolygonFigure(settings.commonBackgroundColor, points, numPoints)); } if (! closed || settings.commonFillType != ToolSettings.ftSolid || numPoints < 3) { for (int i = 0; i < numPoints - 1; ++i) { final Point a = points[i]; final Point b = points[i + 1]; container.add(new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle, a.x, a.y, b.x, b.y)); } if (closed) { final Point a = points[points.length - 1]; final Point b = points[0]; container.add(new LineFigure(settings.commonForegroundColor, settings.commonBackgroundColor, settings.commonLineStyle, a.x, a.y, b.x, b.y)); } } return container; }
8
public static void main(String[] args) { PlayerReplayer playerReplayers[] = new PlayerReplayer[NUM_SLOTS]; Scanner input; int num = 0; File dir = new File(Position.GAME_NAME + "Commands"); String inputfilename; File[] directoryListing = dir.listFiles(); if (directoryListing != null) { for (File child : directoryListing) { num = gameUtils.gameFunctionUtils.getFileNum(child); try { inputfilename = Position.GAME_NAME + "Commands\\" + Position.GAME_NAME + "Commands" + num + ".txt"; input = new Scanner(new File(inputfilename)); System.out.println("Playing: " + inputfilename); FrustrationServerMiddleMan middleMan = new FrustrationServerMiddleMan(); middleMan.setOutputFileWriter( GameReplayPrinter.getNewReplayOuput(Position.GAME_NAME, num) ); //Frustation Irwin version: input.nextLine(); for(int i=0; i<NUM_SLOTS; i++) { playerReplayers[i] = null; } String currentScan = input.nextLine(); //position A: Michael while(currentScan.startsWith("First") == false) { String playerArgs[] = currentScan.split(" "); char posLetter = playerArgs[1].charAt(0); String playerName = playerArgs[2]; playerReplayers[(int)(posLetter - 'A')] = new PlayerReplayer(input, playerName); currentScan = input.nextLine(); } String firstRoller = currentScan.split(" ")[2]; random.dice.RiggedDie rigged = new random.dice.RiggedDie(input); int startingIndex = -1; for(int i=0; i<NUM_SLOTS; i++) { if(playerReplayers[i] != null && playerReplayers[i].getName().equals(firstRoller)) { startingIndex = i; break; } } Position.startFrustration(middleMan, playerReplayers, rigged, startingIndex); System.out.println("Finished playing: " + inputfilename); input.close(); } catch (Exception e) { System.out.println("WARNING wtf: " + e.getMessage()); e.printStackTrace(); System.exit(1); } } } else { // Handle the case where dir is not really a directory. // Checking dir.isDirectory() above would not be sufficient // to avoid race conditions with another process that deletes // directories. System.out.println(" you did not find the folder... too bad."); } System.out.println("Done running frustration irwin tests"); }
8
private void options() { final Stage dialog = new Stage(); initializeDialog(dialog); Label label = new Label(txt); defaultVolume = makeVolumeSlider(); Button okButton = new Button("OK"); okButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { dialog.close(); } }); FlowPane pane = new FlowPane(10, 10); pane.setAlignment(Pos.CENTER); pane.getChildren().addAll(okButton); VBox vBox = new VBox(10); vBox.setAlignment(Pos.CENTER); Label tempoAdjustHack = new Label("Increase tempo by how many times?"); tempoField = new TextField(); vBox.getChildren().addAll(label, defaultVolume, tempoAdjustHack, tempoField, pane); defaultVolume.autosize(); Scene scene1 = new Scene(vBox); dialog.setScene(scene1); dialog.showAndWait(); while (dialog.isShowing()) { try { Thread.sleep(1); } catch (InterruptedException e) { // Do nothing } } updateValues(); theStaff.redraw(); }
2
public void takeFromContainer(int playerID, int index) { Player p = this.playerIDs.get(playerID); if (p != null) { Location on = p.getLocationInFrontOf(); if (board.tileAt(on).getOn() != null && board.tileAt(on).getOn() instanceof Inventory) { Inventory takingFrom = (Inventory)board.tileAt(on).getOn(); if (index < takingFrom.size()) { Item toTake = takingFrom.getContents().get(index); if (p.addItemToInventory(toTake)) { takingFrom.removeItem(toTake); server.queuePlayerUpdate(new PickUpItemEvent(toTake), playerID); for (int id: playerIDs.keySet()) { server.queuePlayerUpdate(new RemoveFromContainerEvent(on, index), id); } } } } } }
6
public static void startupPartialMatch() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupPartialMatch.helpStartupPartialMatch1(); } if (Stella.currentStartupTimePhaseP(4)) { Logic.$PARTIAL_MATCH_MODE$ = Logic.KWD_BASIC; Logic.$RULE_COMBINATION$ = Logic.KWD_MAX; Logic.$PLANABLE_PREDICATES$ = Stella.NIL; } if (Stella.currentStartupTimePhaseP(5)) { { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("PARTIAL-MATCH-FRAME", "(DEFCLASS PARTIAL-MATCH-FRAME (STANDARD-OBJECT) :DOCUMENTATION \"Abstract class acting as placeholder for system and\nuser-defined partial match implementations.\" :ABSTRACT? TRUE :SLOTS ((KIND :TYPE KEYWORD :REQUIRED? TRUE) (CONTROL-FRAME :TYPE CONTROL-FRAME :REQUIRED? TRUE) (PARENT :TYPE PARTIAL-MATCH-FRAME) (CHILD :TYPE PARTIAL-MATCH-FRAME) (POSITIVE-SCORE :TYPE PARTIAL-MATCH-SCORE :INITIALLY NULL) (NEGATIVE-SCORE :TYPE PARTIAL-MATCH-SCORE :INITIALLY NULL) (DYNAMIC-CUTOFF :TYPE FLOAT) (ARGUMENT-SCORES :TYPE (CONS OF FLOAT-WRAPPER) :INITIALLY NIL) (ARGUMENT-WEIGHTS :TYPE (CONS OF FLOAT-WRAPPER) :INITIALLY NIL) (UNBOUND-VARS :TYPE CONS :INITIALLY NIL) (SUCCESS? :TYPE BOOLEAN :INITIALLY FALSE)))"); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.PartialMatchFrame", "accessPartialMatchFrameSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.PartialMatchFrame"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("INCREMENTAL-PARTIAL-MATCH", "(DEFCLASS INCREMENTAL-PARTIAL-MATCH (PARTIAL-MATCH-FRAME) :SLOTS ((PARENT :TYPE INCREMENTAL-PARTIAL-MATCH) (CHILD :TYPE INCREMENTAL-PARTIAL-MATCH) (ACCUMULATED-SCORE :TYPE PARTIAL-MATCH-SCORE :INITIALLY 0.0) (ACCUMULATED-WEIGHT :TYPE FLOAT :INITIALLY 0.0) (TOTAL-WEIGHT :TYPE FLOAT) (MAXIMUM-SCORE :TYPE PARTIAL-MATCH-SCORE :INITIALLY 0.0)) :INITIALIZER INITIALIZE-INCREMENTAL-PARTIAL-MATCH)"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.IncrementalPartialMatch", "newIncrementalPartialMatch", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Keyword"), Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.IncrementalPartialMatch", "accessIncrementalPartialMatchSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.IncrementalPartialMatch"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } { Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("NN-PARTIAL-MATCH", "(DEFCLASS NN-PARTIAL-MATCH (PARTIAL-MATCH-FRAME) :SLOTS ((PARENT :TYPE NN-PARTIAL-MATCH) (CHILD :TYPE NN-PARTIAL-MATCH) (ACCUMULATED-SCORE :TYPE PARTIAL-MATCH-SCORE :INITIALLY 0.0) (MAXIMUM-SCORE :TYPE PARTIAL-MATCH-SCORE :INITIALLY 0.0) (RULES :TYPE (CONS OF PROPOSITION) :INITIALLY NIL) (ARITY :TYPE INTEGER)) :INITIALIZER INITIALIZE-NN-PARTIAL-MATCH)"); renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.NnPartialMatch", "newNnPartialMatch", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Keyword"), Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}); renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.NnPartialMatch", "accessNnPartialMatchSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.NnPartialMatch"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}); } } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { _StartupPartialMatch.helpStartupPartialMatch2(); _StartupPartialMatch.helpStartupPartialMatch3(); } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PARTIAL-MATCH-MODE* KEYWORD :BASIC)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *GREEDY-NETWORK-PRUNING* BOOLEAN TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *RULE-COMBINATION* KEYWORD :MAX)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PLANNING-MODE* BOOLEAN FALSE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PLANABLE-PREDICATES* CONS NIL)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *FAIL-UNBOUND-CLAUSES?* BOOLEAN FALSE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MINIMUM-SCORE-CUTOFF* PARTIAL-MATCH-SCORE 0.0 :DOCUMENTATION \"Positive scores below *minimum-score-cutoff* get trimmed\nto 0.0 during partial match operations.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MAXIMUM-SCORE-CUTOFF* PARTIAL-MATCH-SCORE 0.0 :DOCUMENTATION \"Positive scores above *maximum-score-cutoff* get trimmed\nto 1.0 during partial match operations.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *AND-MISSED-A-BINDING* BOOLEAN FALSE)"); { Object old$Module$001 = Stella.$MODULE$.get(); Object old$Context$001 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Logic.$PL_KERNEL_MODULE$); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); Logic.createLogicInstance(Logic.SGT_PL_KERNEL_KB_NULL, null); } finally { Stella.$CONTEXT$.set(old$Context$001); Stella.$MODULE$.set(old$Module$001); } } } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
7
@Override public boolean remove(T element) { int i = 0; int hashCode = element.hashCode() % hashTable.size(); if (keyCode.get(hashCode).equals("f") && hashTable.get(hashCode).equals(element)) { hashTable.set(hashCode, null); keyCode.set(hashCode, "r"); return true; } else if (keyCode.get(hashCode).equals("r") || keyCode.get(hashCode).equals("f")) { if (keyCode.get(hashCode + i).equals("e")) { // System.out.println("cannot remove: not in the array"); return false; } while (!(hashTable.get(hashCode + i).equals(element))) { // System.out.println("remove iterating: " + i); i++; if ((hashCode + i) >= hashTable.size()) { hashCode = 0; i = 0; } } // System.out.println("remove probing called"); hashTable.set(hashCode + i, null); keyCode.set(hashCode + i, "r"); } return true; }
7
private static void showWallet(ApiAuthorization auth, int acId) { AbstractWalletTransactionsParser parser = WalletTransactionsParser.getInstance(); WalletTransactionsResponse response; try { response = parser.getResponse(auth, 1000); Set<ApiWalletTransaction> walletTransactions = response.getAll(); DecimalFormat formatter = new DecimalFormat("#,###.00"); for (ApiWalletTransaction walletTransaction : walletTransactions) { System.out.println(walletTransaction.getQuantity() + " " + walletTransaction.getTypeName() + " " + formatter.format(walletTransaction.getPrice())); } } catch (ApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
public static YearsStatisticsByCities convert( CitiesStatisticsByYears statisticsByYears) { YearsStatisticsByCities yearsStatisticsByCities = new YearsStatisticsByCities(); Map<City, EmployeesStatisticsByYears> emplByCities = new TreeMap<City, EmployeesStatisticsByYears>(); EmployeesStatisticsByYears employeesStatisticsByYears; Map<Integer, EmployeesOnQuarters> emplByYear; for (Entry<Integer, EmployeesStatisticsByCities> yearEntry : statisticsByYears .getCitiesStatistics().entrySet()) { for (Entry<City, EmployeesOnQuarters> cityEntry : yearEntry .getValue().getStatisticsByCities().entrySet()) { City city = cityEntry.getKey(); if (!emplByCities.containsKey(city)) { employeesStatisticsByYears = new EmployeesStatisticsByYears(); emplByYear = new TreeMap<Integer, EmployeesOnQuarters>(); emplByYear.put(yearEntry.getKey(), cityEntry.getValue()); employeesStatisticsByYears.setEmplStat(emplByYear); emplByCities.put(city, employeesStatisticsByYears); } else { employeesStatisticsByYears = emplByCities.get(city); emplByYear = employeesStatisticsByYears.getEmplStat(); emplByYear.put(yearEntry.getKey(), cityEntry.getValue()); } } } yearsStatisticsByCities.setEmpl(emplByCities); return yearsStatisticsByCities; }
3
public void addChunk() { String chunkName = null; List<DataNodeEntry> locations = null; try { chunkName = this.nameNodeStub.nameChunk(); if (Hdfs.Core.DEBUG) { System.out.println("DEBUG HDFSFile.addChunk(): chunk name:" + chunkName); } locations = this.nameNodeStub.select(this.replicaFactor); int i = 0; if (Hdfs.Core.DEBUG) { System.out.format("DEBUG HDFSFile.addChunk(): Locations\n"); for (DataNodeEntry entry: locations) { System.out.format("\tIP=%s\t%s\n", entry.dataNodeRegistryIP, entry.dataNodeRegistryPort); } } } catch (RemoteException e) { if (Hdfs.Core.DEBUG) { e.printStackTrace(); } } HDFSChunk newChunk = new HDFSChunk(chunkName, locations); this.chunkList.add(newChunk); }
5
@Test public void testGetMarker() { System.out.println("getMarker"); Unmark instance = new Unmark(6, 9); int expResult = 6; int result = instance.getMarker(); assertEquals(expResult, result); }
0
public static void insertSqlCommandTemplate(PropertyList template) { { Stella_Object commandname = template.lookup(Sdbc.KWD_COMMAND); { Stella_Object temp000 = template.lookup(Sdbc.KWD_DATA_SOURCE); { Cons datasources = (((temp000 != null) ? temp000 : Sdbc.KWD_DEFAULT)).consify(); Stella_Object sql = template.lookup(Sdbc.KWD_SQL); KeyValueList templates = ((KeyValueList)(((KeyValueMap)(Sdbc.$SQL_COMMAND_TEMPLATES$.get())).lookup(commandname))); if (commandname == null) { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("Missing :command name in SQL template: `" + template + "'"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } if (!(Stella_Object.stringP(sql))) { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); { stream001.nativeStream.println("Illegal or missing :sql specification in SQL template: `" + sql + "'"); stream001.nativeStream.print(" String expected."); } ; throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace())); } } if (templates == null) { templates = KeyValueList.newKeyValueList(); ((KeyValueMap)(Sdbc.$SQL_COMMAND_TEMPLATES$.get())).insertAt(commandname, templates); } { Stella_Object datasource = null; Cons iter000 = datasources; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { datasource = iter000.value; if (datasource == Sdbc.KWD_OTHERWISE) { datasource = Sdbc.KWD_DEFAULT; } templates.insertAt(datasource, template); } } } } } }
6
private boolean checkSpawnerLocation(int x, int y){ for(int ya = y - spawnerRadius; ya < y + spawnerRadius + 1; ya++){ for(int xa = x - spawnerRadius; xa < x + spawnerRadius + 1; xa++){ if(!checkBounds(xa, ya)) continue; if(!getTile(xa, ya).equals(Tile.floorTile)) return false; } } return true; }
4
public void updateUserbyUserName(final String name, final String pass, final String phone, final int type) { for (User u : userList.getUserList()) { if (name.equals(u.getName())) { u.setPassword(pass); u.setPhoneNumber(phone); u.setType(type); } } writeUserList(); }
2
public void truncate(float max) { if(this.length() > max) { this.normalize(); this.x *= max; this.y *= max; } }
1
private void DownLoad10K(String urlStr, String outPath) { // the length of input stream int chByte = 0; // the url of the doc to download URL url = null; // HTTP connection HttpURLConnection httpConn = null; InputStream in = null; FileOutputStream out = null; try { url = new URL(urlStr); httpConn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); httpConn.setRequestMethod("GET"); in = httpConn.getInputStream(); out = new FileOutputStream(new File(outPath)); chByte = in.read(); while (chByte != -1) { out.write(chByte); chByte = in.read(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); in.close(); httpConn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } }
4
@Override public IReceiveQuery getReceiveQuery() { return receiveQuery; }
0
public void generate() { final int maxHeight = HEIGHT / 2; final int stepHeight = maxHeight / 75 * blockSize; int maxBlockHeight = 0; blockHeights[0] = Util.rand(maxHeight); for (int i = 1; i < blocksCount; i++) { int value = blockHeights[i - 1] + Util.rand(-stepHeight, stepHeight); if (value > maxHeight) value = maxHeight; else if (value < 0) value = 0; blockHeights[i] = value; // Detect max block height if (maxBlockHeight < value) maxBlockHeight = value; } // Flatten out left and right blocks for turrets. for (int i = 0; i < PLAYERS_BLOCK_COUNT; i++) { blockHeights[i] = getFirstBlockHeight(); blockHeights[blocksCount - i - 1] = getLastBlockHeight(); } // Smooth blocks final int halfCount = PLAYERS_BLOCK_COUNT / 2; for (int start = 1; start <= SMOOTH_ITERATIONS; start++) { for (int i = start + halfCount; i < blocksCount - halfCount; i += 2) { blockHeights[i] = (blockHeights[i - 1] + blockHeights[i + 1]) / 2; } } gradientPaint = new LinearGradientPaint( 0, HEIGHT - maxBlockHeight, 0, HEIGHT, new float[] {0f, 1f}, TERRAIN_COLOR); }
7
public void run() { debug("GC: started"); synchronized (this) { for (; ;) { while (rrdMap.size() > capacity && rrdGcList.size() > 0) { try { RrdEntry oldestRrdEntry = (RrdEntry) rrdGcList.get(0); debug("GC: closing " + oldestRrdEntry.dump()); removeRrdEntry(oldestRrdEntry); } catch (IOException e) { e.printStackTrace(); } } try { debug("GC: waiting: " + rrdMap.size() + " open, " + rrdGcList.size() + " released, " + "capacity = " + capacity + ", " + "hits = " + poolHitsCount + ", " + "requests = " + poolRequestsCount); wait(); debug("GC: running"); } catch (InterruptedException e) { } } } }
5
public boolean deduplicate (ObjectatEvent event) { boolean success = false; // Update last timestamp this.setLast(new Date()); // Update count this.setEventCount(this.getEventCount() + 1); if (event.isOwned() != this.isOwned()) { if (this.logger != null) { this.logger.log(ObjectatLogLevel.DEBUG, "Updating event key " + this.getKey() + " owned from " + this.isOwned() + " to " + event.isOwned()); } this.setOwned(event.isOwned()); } if (!event.getOwnedBy().equals(this.getOwnedBy()) && event.getOwnedBy() != null) { if (this.logger != null) { this.logger.log(ObjectatLogLevel.DEBUG, "Updating event key " + this.getKey() + " owned by from " + this.getOwnedBy() + " to " + event.getOwnedBy()); } this.setOwnedBy(event.ownedBy); } if (!event.getEventDescription().equals(this.getEventDescription())) { if (this.logger != null) { this.logger.log(ObjectatLogLevel.DEBUG, "Updating event key " + this.getKey() + " description from " + this.getEventDescription() + " to " + event.getEventDescription()); } this.setEventDescription(event.getEventDescription()); } if (event.getEventSeverity().getSeverityInteger() != this.getEventSeverity().getSeverityInteger()) { if (this.logger != null) { this.logger.log(ObjectatLogLevel.DEBUG, "Updating event key " + this.getKey() + " severity from " + this.getEventSeverity() + " to " + event.getEventSeverity()); } this.setEventSeverity(event.getEventSeverity()); } return success; }
9
public static void main( String[] args ) { WorkBookHandle book = null; try { // generate a PDF and confirm // load the current file and output it to same directory book = new WorkBookHandle( System.getProperty( "user.dir" ) + "/docs/samples/Input_CSV/contacts.csv" ); System.out.println( book.getStats() ); log.info( "Successfully read CSV into spreadsheet: " + book ); } catch( Exception e ) { log.error( "Spreadsheet_CSV_Input failed.", e ); } // Write out the spreadsheet as CSV -- try { WorkSheetHandle wsh = null; wsh = book.getWorkSheet( 0 ); StringBuffer arr = new StringBuffer(); // return WorkBookCommander.returnXMLErrorResponse("PluginSheet.get() failed: "+ex.toString()); RowHandle[] rwx = wsh.getRows(); for( int i = 0; i < rwx.length; i++ ) { RowHandle r = rwx[i]; try { CellHandle[] chx = r.getCells(); for( int t = 0; t < chx.length; t++ ) { arr.append( "'" + chx[t].getFormattedStringVal() + "'," ); } arr.setLength( arr.length() - 1 ); arr.append( "\r\n" ); } catch( Exception ex ) { log.error( "Spreadsheet CSV output failed to fetch row:" + i, ex ); } } System.out.println( "WorkBook:" + book + " CSV output: " + arr.toString() ); } catch( Exception e ) { log.error( "Spreadsheet CSV output failed: " + e.toString() ); } }
5
public Point fight(){ int aLost = 0; int dLost = 0; // Resets dice values d[DEFENDERFIRST]=0; d[DEFENDERSECOND]=0; a[ATTACKERFIRST]=0; a[ATTACKERSECOND]=0; a[ATTACKERTHIRD]=0; unitsAttacker = getFirstTerritory().getNbrOfUnits() - 1; unitsDefender = getSecondTerritory().getNbrOfUnits(); for(int i = 0; i < unitsAttacker && i < 3; i++){ a[i] = Dice.d6Roll(); } Arrays.sort(a); int i = 1; do{ d[i-1] = Dice.d6Roll(); i++; }while(i < unitsDefender && i < 3); if(a[ATTACKERTHIRD] <= Math.max(d[DEFENDERFIRST], d[DEFENDERSECOND])){ getFirstTerritory().setNbrOfUnits(unitsAttacker); aLost++; } else{ getSecondTerritory().setNbrOfUnits(unitsDefender - 1); dLost++; } if(a[ATTACKERFIRST] != 0 && a[ATTACKERSECOND] <= Math.min(d[DEFENDERFIRST], d[DEFENDERSECOND]) ){ getFirstTerritory().setNbrOfUnits(getFirstTerritory().getNbrOfUnits() - 1); aLost++; } else if(Math.min(d[DEFENDERFIRST], d[DEFENDERSECOND]) != 0 && Math.min(d[DEFENDERFIRST], d[DEFENDERSECOND]) < a[ATTACKERSECOND]){ getSecondTerritory().setNbrOfUnits(getSecondTerritory().getNbrOfUnits() -1); dLost++; } model.changed(); Point losses = new Point(aLost, dLost); return losses; }
9
public int[][] AllPairsShortestPath(int[][] matrix) { int numberVertices = matrix.length; // create new storage container for path and weight information path = new int[numberVertices][numberVertices]; pathWeights = new int[numberVertices][numberVertices]; // Initialise containers; for (int i = 0; i < numberVertices; i++) { for (int j = 0; j < numberVertices; j++) { // If no direct path, set weight to Infinity. pathWeights[i][j] = matrix[i][j] > 0 ? matrix[i][j] : Integer.MAX_VALUE; if(i == j){ pathWeights[i][j] = 0; } path[i][j] = NULL; } } // Main loop. for (int k = 0; k < numberVertices; k++) { for (int i = 0; i < numberVertices; i++) { for (int j = 0; j < numberVertices; j++) { if ((long)pathWeights[i][j] > (long)pathWeights[i][k] + (long)pathWeights[k][j]) { // Store new min weight pathWeights[i][j] = pathWeights[i][k] + pathWeights[k][j]; // Store new path through k. path[i][j] = k; } } } } return pathWeights; }
8