text
stringlengths
14
410k
label
int32
0
9
public Double calculateCost(Order order){ if(order == null){ System.out.println("Order is empty"); } double totalCost = 0; for(Pizza pizza : order.getPizzas()){ totalCost += pizza.getCost(); for(String topping : pizza.getToppings()){ Double toppingPrice = toppingsMenu.get(topping); if(toppingPrice == null){ toppingPrice = 0.0; } totalCost += toppingPrice; } } return totalCost; }
4
public void setUserSavedGame() { File file = new File("Users.txt"); String line = ""; FileWriter writer; ArrayList<String> userData= new ArrayList<String>(); ListIterator<String> iterator; try { Scanner s = new Scanner(file); while(s.hasNextLine()) { userData.add(s.nextLine()); } s.close(); iterator = userData.listIterator(); while(iterator.hasNext()) { if(iterator.next().equals(user.getUsername())) { if(iterator.hasNext()) { iterator.next(); if(iterator.hasNext()) { line = iterator.next(); if(line.equals("false")) iterator.set("true"); break; } } } } writer = new FileWriter("Users.txt"); iterator = userData.listIterator(); while(iterator.hasNext()) { writer.write(iterator.next()); writer.write("\n"); } writer.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Could not find User file. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Could not update Users. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } }
9
@Override public void rightMultiply(IMatrix other) { // TODO Auto-generated method stub for(int i=0;i<4;i++) for(int j=0;j<4;j++) copy[i][j]=0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { copy[i][j]=copy[i][j] + this.get(k, i) * other.get(j, k); } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { this.set(j, i, copy[i][j]); } } }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") Entry<K,V> other = (Entry<K,V>) obj; if (k == null) { if (other.k != null) return false; } else if (!k.equals(other.k)) return false; return true; }
6
public ArrayList<Reservation> ReservationsByCustomerForFranchise( int FranID, int CustID) throws UnauthorizedUserException, BadConnectionException, DoubleEntryException { /* Variable Section Start */ /* Database and Query Preperation */ PreparedStatement statment = null; ResultSet results = null; String statString = "SELECT * FROM `reservation` WHERE 'FranchiseNumber' = ? AND 'CustomerID' = ?"; /* Return Parameter */ ArrayList<Reservation> BPArrayList = new ArrayList<Reservation>(); /* Variable Section Stop */ /* TRY BLOCK START */ try { /* Preparing Statment Section Start */ statment = con.prepareStatement(statString); statment.setInt(1, FranID); statment.setInt(2, CustID); /* Preparing Statment Section Stop */ /* Query Section Start */ results = statment.executeQuery(); /* Query Section Stop */ /* Metadata Section Start*/ //ResultSetMetaData metaData = results.getMetaData(); /* Metadata Section Start*/ /* ArrayList Prepare Section Start */ while (results.next()) { Reservation temp = new Reservation(); //results.getBigDecimal("AMOUNT") temp.setAirline(results.getString("Airline")); temp.setComment(results.getString("Comment")); temp.setCustomerID(results.getInt("CustomerID")); temp.setDate(results.getString("Date")); temp.setDropOffTime(results.getDouble("DropOffTime")); temp.setFlightNumber(results.getString("FlightNumber")); temp.setFlightTime(results.getDouble("FlightTime")); temp.setFranchiseNumber(results.getInt("FranchiseNumber")); temp.setPickUpTime(results.getDouble("PickUpTime")); temp.setPrice(results.getDouble("Price")); temp.setReservationNumber(results.getString("ReservationNumber")); temp.setStatus(results.getString("Status")); temp.setVehicleID(results.getInt("VehicleID")); temp.setAltAddress(results.getString("AltAddress")); temp.setAltCity(results.getString("AltCity")); temp.setAltState(results.getString("AltState")); temp.setAltZip(results.getInt("AltZip")); BPArrayList.add(temp); } /* ArrayList Prepare Section Stop */ } catch(SQLException sqlE) { if(sqlE.getErrorCode() == 1142) throw(new UnauthorizedUserException("AccessDenied")); else if(sqlE.getErrorCode() == 1062) throw(new DoubleEntryException("DoubleEntry")); else throw(new BadConnectionException("BadConnection")); } finally { try { if (results != null) results.close(); } catch (Exception e) {}; try { if (statment != null) statment.close(); } catch (Exception e) {}; } /* TRY BLOCK STOP*/ /* Return to Buisness Section Start */ return BPArrayList; /* Return to Buisness Section Start */ }
8
public boolean isValidPassword(String userName, String password) { try { LoginDao ds = new LoginDao(); String pwdFromDB = ds.getUserPassword(userName); if (null != pwdFromDB) { if (pwdFromDB.equals(password)) { return true; } } } catch (Exception ex) { if (!(ex instanceof DaoException)) { ex.printStackTrace(); } throw new ServiceException("global.exception.message"); } return false; }
4
public void ensureConnection() throws AuthenticationException { BugLog.getInstance().assertNotNull(getConnection()); if (getConnection().isOpen()) { return; } // #69689 detect silent servers, possibly caused by proxy errors final Throwable ex[] = new Throwable[1]; final boolean opened[] = new boolean[] { false }; final Runnable probe = new Runnable() { public void run() { try { getConnection().open(); synchronized (opened) { opened[0] = true; } } catch (final Throwable e) { synchronized (ex) { ex[0] = e; } } } }; final Thread probeThread = new Thread(probe, "CVS Server Probe"); // NOI18N probeThread.start(); try { probeThread.join(60 * 1000); // 1 min Throwable wasEx; synchronized (ex) { wasEx = ex[0]; } if (wasEx != null) { if (wasEx instanceof CommandAbortedException) { // User cancelled abort(); return; } else if (wasEx instanceof AuthenticationException) { throw (AuthenticationException) wasEx; } else if (wasEx instanceof RuntimeException) { throw (RuntimeException) wasEx; } else if (wasEx instanceof Error) { throw (Error) wasEx; } else { assert false : wasEx; } } boolean wasOpened; synchronized (opened) { wasOpened = opened[0]; } if (wasOpened == false) { probeThread.interrupt(); throw new AuthenticationException("Timeout, no response from server.", "Timeout, no response from server."); } } catch (final InterruptedException e) { // User cancelled probeThread.interrupt(); abort(); } }
9
private MailUtil(){ };
0
@Override public void discoverChildren() { //super.discoverChildren(); Map<Date, VirtualFolder> datums = new HashMap<Date, VirtualFolder>(); Map<String, VirtualFolder> series = new HashMap<String, VirtualFolder>(); String xml = HTTPWrapper.Request("http://iptv.rtl.nl/xl/VideoItem/IpadXML"); int i = 0; for (MatchResult m : Regex.all("<item>.*?<title>(.*?)</title>.*?<broadcastdatetime>(.*?)</broadcastdatetime>" + ".*?<thumbnail>(.*?)</thumbnail>.*?<movie>(.*?)</movie>.*?<serienaam>(.*?)</serienaam>.*?<classname>(.*?)</classname>", xml)) { String titel = m.group(1); String uitzendtijd = m.group(2).substring(0, 10).trim(); String thumb = m.group(3).trim(); String movie = m.group(4).trim(); String serienaam = m.group(5).trim(); String classname = m.group(6).trim(); if (classname.equals("eps_fragment")) { continue; } //Voeg toe aan datum Date d = null; try { d = new SimpleDateFormat("yyyy-MM-dd").parse(uitzendtijd); } catch (ParseException ex) { Logger.getLogger(RTLGemist.class.getName()).log(Level.SEVERE, null, ex); } String uitzendtijdNL = new SimpleDateFormat("EEEE d MMMM").format(d); if (!datums.containsKey(d)) { datums.put(d, new VirtualFolder(uitzendtijdNL, null)); } datums.get(d).addChild(new WebStream(titel, movie, thumb, Format.VIDEO)); //Voeg toe aan serie if(!series.containsKey(serienaam)) { series.put(serienaam, new VirtualFolder(serienaam, null)); } series.get(serienaam).addChild(new WebStream(titel, movie, thumb, Format.VIDEO)); } VirtualFolder datumfolder = new VirtualFolder("Op datum", null); VirtualFolder seriefolder = new VirtualFolder("Op serie", null); ArrayList<Date> datumnamen = new ArrayList<Date>(datums.keySet()); Collections.sort(datumnamen); Collections.reverse(datumnamen); for(Date datum : datumnamen) { datumfolder.addChild(datums.get(datum)); } ArrayList<String> serienamen = new ArrayList<String>(series.keySet()); Collections.sort(serienamen); for(String serienaam : serienamen) { seriefolder.addChild(series.get(serienaam)); } this.addChild(datumfolder); this.addChild(seriefolder); }
7
public static void toggleCommentAndClear(Node currentNode, JoeTree tree, OutlineLayoutManager layout) { CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree); JoeNodeList nodeList = tree.getSelectedNodes(); for (int i = 0, limit = nodeList.size(); i < limit; i++) { toggleCommentAndClearForSingleNode(nodeList.get(i), undoable); } if (!undoable.isEmpty()) { if (undoable.getPrimitiveCount() == 1) { undoable.setName("Toggle Comment and Clear Decendants for Node"); } else { undoable.setName(new StringBuffer().append("Toggle Comment and Clear Decendants for ").append(undoable.getPrimitiveCount()).append(" Nodes").toString()); } tree.getDocument().getUndoQueue().add(undoable); } layout.draw(currentNode, OutlineLayoutManager.ICON); }
3
public void sendWertBerechnenX(int inputX, int inputY){ if(inputX >= 0){ //Positiv if(inputX <= 256){ posX1 = setPosWert(inputX); posX2 = 0; }else{ posX1 = 256; posX2 = setPosWert(inputX - 256); } } if(inputX < 0){ //Negativ if(inputX > -255){ negX1 = setNegWert(inputX); negX2 = 0; }else{ negX1 = -255; negX2 = setNegWert(inputX - 255); } } if(inputY >= 0){ //Positiv if(inputY <= 256){ posY1 = setPosWert(inputY); posY2 = 0; }else{ posY1 = 256; posY2 = setPosWert(inputY - 256); } } if(inputY < 0){ //Negativ if(inputY > -255){ negY1 = setNegWert(inputY); negY2 = 0; }else{ negY1 = -255; negY2 = setNegWert(inputY - 255); } } }
8
@Override public double fun(double[] w) { double f = 0; double[] y = prob.y; int l = prob.l; int w_size = get_nr_variable(); double d; Xv(w, z); for (int i = 0; i < w_size; i++) f += w[i] * w[i]; f /= 2; for (int i = 0; i < l; i++) { d = z[i] - y[i]; if (d < -p) f += C[i] * (d + p) * (d + p); else if (d > p) f += C[i] * (d - p) * (d - p); } return f; }
4
public String getTooltipExtraText(final Province curr) { final int id = curr.getId(); if (!editor.Main.map.isLand(id)) return ""; String owner = mapPanel.getModel().getHistString(id, "owner"); String controller = mapPanel.getModel().getHistString(id, "controller"); if (owner == null && controller == null) return ""; owner = Text.getText(owner); controller = Text.getText(controller); final StringBuilder ret = new StringBuilder(); if (owner != null && !Utilities.isNotACountry(owner)) ret.append("Owner: ").append(owner).append("<br />"); if (controller != null && !controller.equalsIgnoreCase(owner)) ret.append("Controller: ").append(Utilities.isNotACountry(controller) ? "none" : controller); return ret.toString(); }
8
public static Map<Integer, Double> getResourcesFromUserWithBLL(List<Bookmark> trainData, List<Bookmark> testData, int userID, List<Map<Integer, Double>> bllValues) { Map<Integer, Double> resourceMap = new LinkedHashMap<Integer, Double>(); Map<Integer, Double> values = null; if (bllValues != null && userID < bllValues.size()) { values = bllValues.get(userID); } for (Bookmark data : trainData) { if (data.userID == userID) { double val = 1.0; if (values != null) { val = 0.0; for (Integer t : data.getTags()) { Double v = values.get(t); if (v != null) { val += v.doubleValue(); } } } resourceMap.put(data.resID, val); } } return resourceMap; }
7
protected String removeHttpProtocol(String html) { //remove http protocol from tag attributes if(removeHttpProtocol) { Matcher matcher = httpProtocolPattern.matcher(html); StringBuffer sb = new StringBuffer(); while(matcher.find()) { //if rel!=external if(!relExternalPattern.matcher(matcher.group(0)).matches()) { matcher.appendReplacement(sb, "$1$2"); } else { matcher.appendReplacement(sb, "$0"); } } matcher.appendTail(sb); html = sb.toString(); } return html; }
3
@Override public boolean login(String userID, String password) { // TODO Auto-generated method stub if(validate(userID)){ String[] userIds= (rb.getString("userIds")).split(" "); String[] passwords= (rb.getString("passwords")).split(" "); String[] status= (rb.getString("status")).split(" "); for (int i = 0; i < userIds.length; i++) { if (userIds[i].equals(userID)) { if (passwords[i].equals(password)) { if (status[i].equals("true")) { return true; } else { return false; } } else { occurance++; return false; } } else { occurance++; return false; } } }return false; }
5
@Override public void destroy(VirtualMachine virtualMachine) throws Exception { if (status(virtualMachine).equals(VirtualMachineStatus.RUNNING)) { stop(virtualMachine); } IMachine machine = this.vbox.findMachine(virtualMachine.getName()); ISession session = getSession(virtualMachine); machine.lockMachine(session, LockType.Write); try { IConsole console = session.getConsole(); if (machine.getCurrentSnapshot() != null) { IProgress deleteSnapshotProg = console.deleteSnapshot(machine.getCurrentSnapshot().getId()); deleteSnapshotProg.waitForCompletion(-1); if (deleteSnapshotProg.getResultCode() != 0) { throw new Exception("Cannot delete snapshot from VM. " + deleteSnapshotProg.getErrorInfo().getText()); } } IMachine mutable = session.getMachine(); try { mutable.removeStorageController(DISK_CONTROLLER_NAME); } catch (VBoxException e) { // Do nothing if the controller does not exist } mutable.saveSettings(); } catch (Exception e) { throw e; } finally { unlock(session); } machine.delete(machine.unregister(CleanupMode.Full)); }
5
public void crossReferenceMetaAnnotations() throws CrossReferenceException { Set<String> unresolved = new HashSet<String>(); Set<String> index = new HashSet<String>(); index.addAll(annotationIndex.keySet()); for (String annotation : index) { if (ignoreScan(annotation)) { continue; } if (classIndex.containsKey(annotation)) { for (String xref : classIndex.get(annotation)) { annotationIndex.get(xref).addAll(annotationIndex.get(annotation)); } continue; } InputStream bits = Thread.currentThread().getContextClassLoader().getResourceAsStream(annotation.replace('.', '/') + ".class"); if (bits == null) { unresolved.add(annotation); continue; } try { scanClass(bits); } catch (IOException e) { unresolved.add(annotation); } for (String xref : classIndex.get(annotation)) { annotationIndex.get(xref).addAll(annotationIndex.get(annotation)); } } if (unresolved.size() > 0) throw new CrossReferenceException(unresolved); }
8
@Override public Book readBook(String isbn) { if (doc == null) return null; Element currRoot = doc.getRootElement(); Element parrentBook = currRoot.getChild("books"); List<Element> listBooks = parrentBook.getChildren(); for (Element book : listBooks) { String bookIsbn = book.getChild("isbn").getText(); if (isbn.equals(bookIsbn)) { String title = book.getChild("title").getText(); String author = book.getChild("author").getText(); double price = Double.parseDouble(book.getChild("price") .getText()); Book bo = new Book(bookIsbn, title, author, price); return bo; } } return null; }
3
private void printEnclosedStackTrace(PrintStreamOrWriter s, StackTraceElement[] enclosingTrace, String caption, String prefix, Set<Throwable> dejaVu) { assert Thread.holdsLock(s.lock()); if (dejaVu.contains(this)) { s.println("\t[CIRCULAR REFERENCE:" + this + "]"); } else { dejaVu.add(this); // Compute number of frames in common between this and enclosing // trace StackTraceElement[] trace = getOurStackTrace(); int m = trace.length - 1; int n = enclosingTrace.length - 1; while (m >= 0 && n >= 0 && trace[m].equals(enclosingTrace[n])) { m--; n--; } int framesInCommon = trace.length - 1 - m; // Print our stack trace s.println(prefix + caption + this); for (int i = 0; i <= m; i++) s.println(prefix + "\tat " + trace[i]); if (framesInCommon != 0) s.println(prefix + "\t... " + framesInCommon + " more"); // Print suppressed exceptions, if any for (Throwable se : getSuppressed()) se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, prefix + "\t", dejaVu); // Print cause, if any Throwable ourCause = getCause(); if (ourCause != null) ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu); } }
8
public static EnumColumn getEnumColumn(int value) { for (EnumColumn column : EnumColumn.values()) { if (column.getPosition() == value) { return column; } } return null; }
2
protected void selectImageFilter(){ FileNameExtensionFilter imageFilter; imageFilter= new FileNameExtensionFilter("All files (*.*)","*.*"); switch(this.selectedExtensionImage){ case all: imageFilter = new FileNameExtensionFilter("All files (*.*)","*.*"); break; case all_images: imageFilter = new FileNameExtensionFilter("All image files","bmp","dib","gif", "jpg","jpeg","jpe","jfif","png"); break; case bmp: imageFilter = new FileNameExtensionFilter("Bitmap (*.bmp, *.dib)","bmp","dib"); break; case gif: imageFilter = new FileNameExtensionFilter("GIF (*.gif)","gif"); break; case jpg: imageFilter = new FileNameExtensionFilter("JPEG (*.jpg,*.jpeg,*.jpe,*.jfif)","jpg","jpeg","jpe","jfif"); break; case png: imageFilter = new FileNameExtensionFilter("PNG (*.png)","png"); break; } this.selectorImage.setFileFilter(imageFilter); }
6
public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; }
1
public int checkLine(int[] line) { int i; boolean test = (line[0] == 0); for (i = 0; i < line.length; i++) { if ((line[i] == 0) != test) { break; } } if (i >= line.length) { return 0; // Ligne incomplète } else if (test) { return 1; //Ligne vide } return -1;//Ligne pleine }
4
@Override public List<Object> filter(Status status) { URLEntity urls[] = status.getURLEntities(); if (urls == null) { return null; } URL finalUrl = null; List<Object> marketUrls = new LinkedList<Object>(); for (URLEntity url : urls) { try { //finalUrl = getFinalUrl(url.getURL()); finalUrl = new URL(url.getExpandedURL()); if (finalUrl == null) { continue; } String extra = null; if (!url.getURL().toString().equals(finalUrl.toString())) { extra = ", \"original\": \"" + url.getURL().toString() + "\""; } JSONObject msg = new JSONObject(); msg.put("link", finalUrl.toString()); msg.put("host", finalUrl.getHost()); if (extra != null) { msg.put("original", url.getURL().toString()); } publish(msg.toJSONString()); if ("play.google.com".equals(finalUrl.getHost()) && finalUrl.getPath().contains("details")) { marketUrls.add(msg.toJSONString()); } } catch (MalformedURLException ex) { Logger.getLogger(RedisLinksPublisherBolt.class.getName()).log(Level.SEVERE, null, ex); } } return marketUrls.size() == 0 ? null : marketUrls; }
9
public void recursiveBFS(String label) { Vertex v = getVertex(label); if (v.wasVisited() == false) { v.setVisited(true); this.queueOfNodes.add(v); System.out.println("Visited vertex : " + v); } int r = getVertexIndex(label); for (int i = 0; i < this.COLS; i++) { if (graph[r][i] == 1) { Vertex t = this.vertices[i]; if (t.wasVisited() == false) { t.setVisited(true); this.queueOfNodes.add(t); System.out.println("Visited vertex : " + t); } } } this.queueOfNodes.poll(); if (queueOfNodes.isEmpty()) return; this.recursiveBFS(this.queueOfNodes.peek().getLabel()); }
5
public Hashtable SibXMLMessageParser(String xml, String id[]) { if(xml==null) { System.out.println("ERROR:SSAP_XMLTools:SibXMLMessageParser: XML message is null") ;return null; } if(id==null) { System.out.println("ERROR:SSAP_XMLTools:SibXMLMessageParser:id is null"); return null; } Document doc=null; try { //System.out.println("################" + xml); doc = builder.build(new ByteArrayInputStream(xml.getBytes())); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(doc==null) { System.out.println("ERROR:SSAP_XMLTools:SibXMLMessageParser:doc is null"); return null; } Hashtable hashtable = new Hashtable(); Element root = doc.getRootElement(); Namespace ns = root.getNamespace(); //String Comm = root.getChild("Command", ns ).getText(); //Element rootActivity = root.getChild("Activity", ns); for(int i=0; i< id.length; i++) { hashtable.put(id[i],root.getChild(id[i], ns ).getText() ); }//for(int i=0; i< e.size(); i++) return hashtable; }//public Hashtable SibXMLMessageParser(String xml, String id[])
5
private void tarjanAlgorithm(Node n) { n.setIndex(index); n.setLowlink(index); index++; s.add(n); for(Node c: n.getToNode()) { if(c.getIndex() == -1) { tarjanAlgorithm(c); n.setLowlink(Math.min(n.getLowlink(), c.getLowlink())); } else if(s.contains(c)) { n.setLowlink(Math.min(n.getLowlink(), c.getIndex())); } } if(n.getLowlink() == n.getIndex()) { Node n1 = null; ArrayList<Node> new_list = new ArrayList<Node>(); //scc.add( (ArrayList<Node>) s.clone() ); int s_size = 0; do { s_size = s.size()-1; n1 = s.get(s_size); new_list.add(n1); s.remove(s_size); //w = this.stack.vertices.pop(); // add w to current strongly connected component //vertices.push(w); } while (!n.equals(n1)); if(new_list.size() > 0) scc.add(new_list); //s.clear(); } }
6
public Object[][] getMultipleRows(String testcase) { String testSheetName = getTestSheetName(testcase); if(testSheetName.equalsIgnoreCase("TestSheet Not Found")){ return null; } HSSFSheet testSheet = workBook.getSheet(testSheetName); String cellData; int totalRows = testSheet.getPhysicalNumberOfRows(); // Total rows in sheet. int totalCols = testSheet.getRow(0).getLastCellNum(); int startIndex = 0; int endIndex = 0; boolean foundStartIndex = false; for(int row=1; row<totalRows; row++){ if(foundStartIndex == false && testcase.equalsIgnoreCase(testSheet.getRow(row).getCell(0).toString())) { startIndex = row; foundStartIndex = true; } if(foundStartIndex == true && !testcase.equalsIgnoreCase(testSheet.getRow(row).getCell(0).toString())){ endIndex = row; break; } endIndex = totalRows; //if bottom reached. } totalRows = endIndex-startIndex; // total rows contains same scenario String[][] testData = new String[totalRows][totalCols - 1]; int index = 0 ; for(int row=startIndex; row<endIndex ; row++) { for (int col = 1; col < totalCols; col++) { if (testSheet.getRow(row).getCell(col) == null) { cellData = ""; } else { cellData = testSheet.getRow(row).getCell(col).toString(); } testData[index][col - 1] = cellData; } index++; } return testData; }
9
public int getCurrentSectionNo(){ if (isEmpty()) return -1; int position = size()-1; Enumeration en = positionMap.keys(); Integer nextKey = null; Integer nextValue = null; while(en.hasMoreElements()){ nextKey = (Integer)en.nextElement(); nextValue = positionMap.get(nextKey); int v = nextValue.intValue(); if (v == position){ return nextKey.intValue(); } } return 0; }
3
public Cloud(int id, Channel leftIn, Channel leftOut, Channel rightIn, Channel rightOut) { this.id_ = id; this.leftIn_ = leftIn; this.leftOut_ = leftOut; this.rightIn_ = rightIn; this.rightOut_ = rightOut; name = this.getId(); currentState = Status.PRE_AUTHED; /* Swing parts */ cloudLbl = new JLabel("Cloud"+id); cloudBtn = new JButton("Waiting"); cloudBtn.setEnabled(false); add(cloudLbl); add(cloudBtn); cloudLbl.setAlignmentX(Component.CENTER_ALIGNMENT); cloudBtn.setAlignmentX(Component.CENTER_ALIGNMENT); /* Pane Config */ setPreferredSize(Config.ENTITY_SIZE); setLayout(new GridLayout(3,1 )); //setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); setBorder(BorderFactory.createMatteBorder(1, 2, 1, 1,Color.black)); cloudBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { switch (currentState) { /* The Java implementation keeps track of "happens-before" events * in order to execute the correct sequence of events according to specific input events */ /* We have to send a GETPIN request to verify the user in the PRE_AUTHED State */ case PRE_AUTHED: ThreadHelper.threadMessage("Send GETPIN to DB", getId()); Message authMsg = new Message(Message.Type.GETPIN, servedUser, id_); //ThreadHelper.threadMessage("Requesting PIN from DB", name); //ThreadHelper.threadMessage("Sending PIN Request over network", name); lastMsgSentOnRight_ = authMsg; rightOut_.send(authMsg); cloudBtn.setEnabled(false); break; /* We can send a AUTHOK to the ATM after being AUTHED */ case AUTHED: ThreadHelper.threadMessage("Send AUTHOK to ATM"+id_, getId()); Message authOKMsg = new Message(Message.Type.AUTHOK, servedUser, id_); lastMsgSentOnLeft_ = authOKMsg; leftOut_.send(authOKMsg); cloudBtn.setEnabled(false); break; /* We can Send a DEAUTHOK message back to the ATM after handling a CANCEL request */ case CANCELED: ThreadHelper.threadMessage("Send DEAUTHOK to ATM"+getId(), getId()); Message deauthOKMsg = new Message(Message.Type.DEAUTHOK, servedUser, id_); lastMsgSentOnLeft_ = deauthOKMsg; leftOut_.send(deauthOKMsg); cloudBtn.setEnabled(false); break; /* We have to RETRIEVERECORD from the Database before actually WITHDRAWING */ case PRE_WITHDRAW: ThreadHelper.threadMessage("Send GETBALANCE("+servedUser+") to DB", getId()); Message recMsg = new Message(Message.Type.GETBALANCE, servedUser, id_); lastMsgSentOnRight_ = recMsg; rightOut_.send(recMsg); cloudBtn.setEnabled(false); break; /* We can send a SETBALANCE request upon receiving a record */ case RECORDFETCHED: ThreadHelper.threadMessage("Send SETBALANCE("+servedUser+") to DB", getId()); lastMsgSentOnRight_ = new Message(Message.Type.SETBALANCE, servedUser, id_); rightOut_.send(lastMsgSentOnRight_); // relay cloudBtn.setEnabled(false); break; /* We can send a WITHDRAWOK to the ATM after a successful SETBALANCE */ case WITHDRAWN: ThreadHelper.threadMessage("Send WITHDRAWOK to ATM"+id_, getId()); lastMsgSentOnLeft_ = new Message(Message.Type.WITHDRAWOK, servedUser, id_); leftOut_.send(lastMsgSentOnLeft_); // relay cloudBtn.setEnabled(false); break; /* A FAILURE message from the channel between ATM-Cloud is dealt with by a resend */ case FAILUREFROMLEFT: ThreadHelper.threadMessage("Resend "+lastMsgSentOnLeft_+" to ATM"+getId(), getId()); leftOut_.send(lastMsgSentOnLeft_); cloudBtn.setEnabled(false); break; /* A FAILURE message from the channel between Cloud-DB is dealt with by a resend */ case FAILUREFROMRIGHT: ThreadHelper.threadMessage("Resend "+lastMsgSentOnRight_+" to DB"+getId(), getId()); rightOut_.send(lastMsgSentOnRight_); cloudBtn.setEnabled(false); break; } } catch(Exception ie){} } }); }
9
@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); }
0
@RequestMapping(value = "/login", method = RequestMethod.GET, produces = "application/json") private @ResponseBody User checkLoginAvailability(@RequestParam String login) { User user = appContext.getUserService().readUserByLogin(login); if (user != null) { return user; } return new User(); }
1
public void setField(String field) { this.field = field; }
0
@Override public boolean getOutput() { for (int j = 0; j < getNumInputs(); j++) if (getInput(j)) return true; return false; }
2
public BasicStructure2 parse(BasicStructure1 structure1) { ArrayList<Integer> types = structure1.getTypes(); ArrayList<String> tokens = structure1.getTokens(); ArrayList<Integer> types1 = new ArrayList<Integer>(); ArrayList<String> tokens1 = new ArrayList<String>(); int type; String token; boolean startline = true; List<Expression> exprs = new ArrayList<Expression>(); int ei = 0; Map<Integer, Integer> linenumbers = new HashMap<Integer, Integer>(); for(int i = 0; i < types.size(); i++) { type = types.get(i); token = tokens.get(i); if (startline && (type == TYPE_NUMBER)) { linenumbers.put(Integer.valueOf(token), ei); } else if (type == TYPE_NEXT_OPERATOR || type == TYPE_NEXT_LINE) { if (types1.size() > 0) { Expression e = new Expression(ei, get1(types1), get2(tokens1)); exprs.add(e); tokens1.clear(); types1.clear(); ei++; } if (type == TYPE_NEXT_LINE) { if (exprs.size() > 0) { Expression e = exprs.get(exprs.size() - 1); e.setLast(); } startline = true; } else { startline = false; } } else { types1.add(type); tokens1.add(token); startline = false; } } if (types1.size() > 0) { Expression e = new Expression(ei, get1(types1), get2(tokens1)); exprs.add(e); tokens1.clear(); types1.clear(); //ei++; } BasicStructure2 structure2 = new BasicStructure2(exprs, linenumbers); return structure2; }
9
private int search(int[]A,int b,int e,int target) { if (b >= e) return b; if (b + 1 == e) { if (A[b] >= target) return b; return e; } int mid = (b + e) /2; if (A[mid] == target) return mid; if (A[mid] > target) return search(A,b,mid,target); return search(A,mid+1,e,target); }
5
public void update(){ up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W]; down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S]; left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A]; right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D]; }
4
@Override public Group findGroupByGroupIdAndUserId(int groupId, int userId) { Group group = null; Connection cn = null; PreparedStatement ps = null; ResultSet rs = null; try { cn = ConnectionHelper.getConnection(); ps = cn.prepareStatement(QTPL_SELECT_BY_USER_ID_AND_GROUP_ID); ps.setInt(1, userId); ps.setInt(2, groupId); rs = ps.executeQuery(); if (rs.next()) { group = processResultSet(rs); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { cn.close(); } catch (SQLException e) { e.printStackTrace(); } } return group; }
5
public static double[] getPageMargins(PrintService service, PrintRequestAttributeSet set, LengthUnits units) { PageOrientation orientation = getPageOrientation(service, set); double[] margins = getPaperMargins(service, set, units); if (orientation == PageOrientation.LANDSCAPE) { return new double[] { margins[1], margins[2], margins[3], margins[0] }; } if (orientation == PageOrientation.REVERSE_PORTRAIT) { return new double[] { margins[2], margins[3], margins[0], margins[1] }; } if (orientation == PageOrientation.REVERSE_LANDSCAPE) { return new double[] { margins[3], margins[0], margins[1], margins[2] }; } return margins; }
3
public String getName() { return delegate.getName(); }
0
private static void insertSongs(int count) { int processors = Runtime.getRuntime().availableProcessors(); Thread[] threads = new Thread[processors]; int size = count / 2; for(int i = 0; i < processors; i++) { threads[i] = new InsertThread(size, size * i); threads[i].start(); } for(Thread t : threads) { try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3
public double obtenerPorcMateria() { double porcentajeMateria = 0; switch (getTamannoEnvase()) { case 'P': if (getGrosorEnvase() == 1) { porcentajeMateria = Constantes.PORCENTAJE_ENVASE_P_1; } break; case 'M': if (getGrosorEnvase() == 1) { porcentajeMateria = Constantes.PORCENTAJE_ENVASE_M_1; } else if (getGrosorEnvase() == 2) { porcentajeMateria = Constantes.PORCENTAJE_ENVASE_M_2; } break; case 'G': if (getGrosorEnvase() == 2) { porcentajeMateria = Constantes.PORCENTAJE_ENVASE_G_2; } else if (getGrosorEnvase() == 3) { porcentajeMateria = Constantes.PORCENTAJE_ENVASE_G_3; } break; } return porcentajeMateria; }
8
public SaveAsAction(Environment environment) { super("Save As...", null); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, MAIN_MENU_MASK + InputEvent.SHIFT_MASK)); this.environment = environment; this.fileChooser = Universe.CHOOSER; }
0
public synchronized void drop() { taken = false; notifyAll(); }
0
public void generateParticles(){ if (ParticleSystem.enabled) for(int i = 0; i < 4 * intensity; ++i) try { ParticleSystem.addParticle(newParticle()); } catch (IllegalArgumentException e) { e.printStackTrace(); } }
3
private static boolean isUnsafe(char ch) { if (ch > 128 || ch < 0) return true; return " []$&+,;=?@<>#%".indexOf(ch) >= 0; }
2
public static String getName(Subcategorias subcat){ String sql="SELECT * FROM subcategorias WHERE idsubcategorias = '"+subcat.getId()+"'"; if(!BD.getInstance().sqlSelect(sql)){ return null; } if(!BD.getInstance().sqlFetch()){ return null; } return BD.getInstance().getString("nombre"); }
2
private void dfs(Graph G, int v) { marked[v] = true; id[v] = count; for (int w : G.adj(v)) if (!marked[w]) dfs(G, w); }
2
@EventHandler(ignoreCancelled = true) public void weatherevent(WeatherChangeEvent event) { if(!Config.enabledWorlds.contains(event.getWorld().getName())) {return;} if(event.toWeatherState() == true) { if(Config.rainWarning) { World world = event.getWorld(); if(rand.nextInt(100) < Config.acidRainChance) { plugin.raining.add(world); } else { return; } List<Player> players = world.getPlayers(); for(Player player : players) { if(player.hasPermission("acidrain.immune")) {return;} String formatedmsg = Config.rainWarningMsg; formatedmsg = ChatColor.translateAlternateColorCodes('&', formatedmsg); player.sendMessage(formatedmsg); } } } else { if(plugin.raining.contains(event.getWorld())) { plugin.raining.remove(event.getWorld()); } } }
7
private byte[] loadJarData(String path, String fileName) { ZipFile zipFile= null; InputStream stream= null; File archive= new File(path); if (!archive.exists()) return null; try { zipFile= new ZipFile(archive); } catch(IOException io) { return null; } ZipEntry entry= zipFile.getEntry(fileName); if (entry == null) return null; int size= (int) entry.getSize(); try { stream= zipFile.getInputStream(entry); byte[] data= new byte[size]; int pos= 0; while (pos < size) { int n= stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; }
7
final public String assignexpr() throws ParseException { /*@bgen(jjtree) ASSIGN */ SimpleNode jjtn000 = new SimpleNode(JJTASSIGN); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t; String s; String assign = ""; try { t = jj_consume_token(ASSIGN); assign += t.image.toString(); s = expression(); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; assign += s; jjtn000.value = assign; {if (true) return assign;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } throw new Error("Missing return statement in function"); }
9
public void setAnswers(ArrayList<String> answers) { textAnswer=answers; }
0
private void processResponse(int userInput) { switch (userInput) { case 0: //switch person to view System.out.println("Switching Person..."); currentPerson = null; break; case 1: //Add Relationship addRelationship(); break; case 2://Delete Relationship deleteRelationship(); break; case 3://Add New Person addPerson(); break; case 4: //Delete Person deletePerson(); break; case 5: //Add New Relationship Type addRelationshipType(); break; case 6: //Delete Relationship Type deleteRelationshipType(); break; case 7: //Save saveState(); break; case 8: //Exit Program endProgram(); break; } }
9
public boolean win() { for (int i = 0; i < plateau.length; i++) { if (plateau[0][i] != null && plateau[0][i].getHaveBall() && plateau[0][i].getColor().equals("Noir") || plateau[6][i] != null && plateau[6][i].getHaveBall() && plateau[6][i].getColor().equals("Blanc")) { return true; } } return false; }
7
public static String oneScan(String s){ if(s==null) return null; StringBuilder result = new StringBuilder(); int end = s.length(); for(int i=s.length()-1;i>=0;i--){ if(s.charAt(i)==' '){ end = i; continue; } if(i==0||s.charAt(i-1)==' '){ if(result.length()!=0){ result.append(' '); } result.append(s.substring(i, end)); } } return result.toString(); }
6
private MethodIdentifier findMethod(String name, String typeSig) { for (Iterator i = methodIdents.iterator(); i.hasNext();) { MethodIdentifier ident = (MethodIdentifier) i.next(); if (ident.getName().equals(name) && ident.getType().equals(typeSig)) return ident; } return null; }
3
@Transactional public void doSomeThing() { TestBean bean1 = new TestBean(3,"piyoxs"); dao.update(bean1); List<TestBean> list = dao.findAll(); for (TestBean bean : list) { SimpleLogger.debug("..." +bean.toString()); } TestBean bean3 = dao.find(3); SimpleLogger.debug(bean3.toString()); }
1
@Override public Move getMove() { int thinkingTime = 0; if (playerColour == Definitions.WHITE) { thinkingTime = 750; } else { thinkingTime = 750; } System.out.println("AI Thinking (" + thinkingTime / 1000.0 + " seconds)"); long startTime = System.currentTimeMillis(); long finishTime = System.currentTimeMillis(); int depth = 1; Move move = null; Move[][] moves = new Move[depth][depth]; Move[] previousMoves = null; currentBoard.generateMoves(playerColour); //Create the first thread and start it running. System.out.println("Running depth 1 search"); Runnable search; if (playerColour == Definitions.WHITE) { search = new MiniMaxSearch2(currentBoard, playerColour, otherPlayerColour, depth, previousMoves, moves); } else { search = new MiniMaxSearch(currentBoard, playerColour, otherPlayerColour, depth, previousMoves, moves); } Thread t = new Thread(search); t.start(); //Ensure the first thread completes try { t.join(); } catch (InterruptedException ex) { Logger.getLogger(AIPlayer.class.getName()).log(Level.SEVERE, null, ex); } while (System.currentTimeMillis() - startTime < thinkingTime) { try { //if the thread has finished start another one if (t.getState() == State.TERMINATED) { move = moves[0][0]; finishTime = System.currentTimeMillis(); //System.out.println("Current best move is " + move.oldX + move.oldY + move.newX + move.newY); depth++; System.out.println("Trying depth " + depth); previousMoves = moves[0]; moves = new Move[depth][depth]; currentBoard.generateMoves(playerColour); if (playerColour == Definitions.WHITE) { search = new MiniMaxSearch2(currentBoard, playerColour, otherPlayerColour, depth, previousMoves, moves); } else { search = new MiniMaxSearch(currentBoard, playerColour, otherPlayerColour, depth, previousMoves, moves); } t = new Thread(search); t.start(); } Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(AIPlayer.class.getName()).log(Level.SEVERE, null, ex); } } t.interrupt(); try { t.join(); } catch (InterruptedException ex) { Logger.getLogger(AIPlayer.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Terminating depth " + depth + " search"); System.out.println("The move to be used is " + move.oldX + move.oldY + move.newX + move.newY); System.out.println("The " + (depth - 1) + " level search took " + (finishTime - startTime) / 1000.0 + " seconds"); currentBoard.makeMove(move); return move; }
8
@Override public int hashCode() { boolean test = false; if (test || m_test) { System.out.println("Coordinate :: hashCode() BEGIN"); } if (test || m_test) { System.out.println("Coordinate :: hashCode() END"); } return m_X + m_Y; }
4
@Override public Object[] getChildren(Object parentElement) { if (parentElement instanceof IProject) { IProject project = (IProject) parentElement; IFile gruntFile = project.getFile(GRUNT_FILE); if (gruntFile.exists()) { return new Object[] { new TaskContainer(gruntFile, getTasks(gruntFile), false), new TaskContainer(gruntFile, aliasTasks, true) }; } } else if (parentElement instanceof TaskContainer) { TaskContainer container = (TaskContainer) parentElement; List<String> tasks = container.tasks; mapFileToTasks(tasks, container.file); mapTasksToFile(tasks, container.file); if (container.alias) { List<AliasTask> retVal = new ArrayList<AliasTask>(); for (String task : aliasTasks) { String definition = aliasTaskDefinitions.get(task); retVal.add(new AliasTask(task, definition)); } return retVal.toArray(new AliasTask[0]); } else { return tasks.toArray(new String[0]); } } return Collections.emptyList().toArray(new Object[0]); }
5
public int search(CharSequence text, String pattern) { int M = text.length(); int N = pattern.length(); for (int i = 0; i < M - N; i++) { int j; for (j = 0; j < N; i++) if (text.charAt(i + j) != pattern.charAt(j)) break; if (j == N) return i; } return N; }
4
public StockItem getProductByName(String productName) { for (StockItem stockItem : stockList) { if (stockItem.getProduct().getProductName().equals(productName)) { return stockItem; } } return null; }
2
public boolean isLibrary() { if (libVisit) return false; if (library == 0 && nextCourse == Course.HUMANITIES) return true; else if (library == 1 && nextCourse == Course.MATH) return true; else if (library == 2 && nextCourse == Course.SCIENCE) return true; else return false; }
7
public <T> T unmap(Map<String, ?> genericised, Class<T> type) { ReMapperMeta meta = extractMeta(genericised); if (meta == null) { //assume this is a hash map System.err.println("__ null meta: umm... what now?"); } if (meta != null) { //note: its possible for the type to change (specialisation - to a sub sol Class<?> metaType = meta.getType(); if (!type.isAssignableFrom(metaType)) throw new RuntimeException("Type " + metaType + " is not a subclass of expected type " + type); Object instance; try { instance = metaType.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } for(String fieldName: genericised.keySet()) { if (fieldName.equals(metaTagName)) continue; PersistentFieldMeta persistentFieldMeta = getPersistentFieldMeta(metaType, fieldName); if (persistentFieldMeta == null) continue; //eg - an unmapped auto field (like _id for MongoDB) Object value = fullUnmap(genericised.get(fieldName), persistentFieldMeta.getType()); persistentFieldOperator.set(instance, persistentFieldMeta, value); } return (T)instance; } throw new RuntimeException("Unable to unmap: " + genericised); }
9
public EarningsTest() { // TODO: use/display company descriptions // TODO: add dates to price/volume graph // TODO: merge idential files / double gae output File resources = new File(REPORTS_ROOT); if (!resources.exists()) resources.mkdir(); singleton = this; programSettings = MemoryManager.restoreSettings(); // JFrame application.setVisible(true); // application.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.setSize(1230, 700); application.setLocation(50, 50); application.add(gui); setUpTabs(); for (Entry<String, ArrayList<String>> x : EarningsTest.singleton.programSettings.tickersActual .entrySet()) { } // System.out.println(x); }
2
private void registerShiftListener(){ KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(KeyEvent e) { synchronized (KeyChecker.class){ switch (e.getID()){ case KeyEvent.KEY_PRESSED: if(e.getKeyCode()==KeyEvent.VK_SHIFT){ KeyChecker.shiftPressed = true; } break; case KeyEvent.KEY_RELEASED: if(e.getKeyCode()==KeyEvent.VK_SHIFT){ KeyChecker.shiftPressed = false; } break; } return false; } } }); }
4
public static void writePhones(ConcurrentHashSet<Long> set, String file) throws IOException { if (file == null || file.equals("")) return; FileWriter fw = new FileWriter(new File(file)); BufferedWriter bw = new BufferedWriter(fw); try { if (set.size() == 0) { bw.append("no phone numbers."); return; } else { Iterator<Long> iter = set.iterator(); while (iter.hasNext()) { bw.append(iter.next() + "\n"); } } } finally { bw.flush(); bw.close(); } }
4
public void updateView() { setLocationManually(myAutoPoint); }
0
public void dumpExpression(TabbedPrintWriter writer) throws java.io.IOException { if (!isInitializer) { writer.print("new "); writer.printType(type.getHint()); writer.breakOp(); writer.print(" "); } writer.print("{ "); writer.startOp(writer.EXPL_PAREN, 0); for (int i = 0; i < subExpressions.length; i++) { if (i > 0) { writer.print(", "); writer.breakOp(); } if (subExpressions[i] != null) subExpressions[i].dumpExpression(writer, 0); else empty.dumpExpression(writer, 0); } writer.endOp(); writer.print(" }"); }
4
public SetGUI(Client c) { client = c; setResizable(false); //cannot expand game to keep background image looking spiffy /* * Standard setup for contentPane, notice that it is a layered pane * so we are able to have a good-looking background */ getContentPane().setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(contentPaneX, contentPaneY, contentPaneWidth, contentPaneHeight); contentPane = new JLayeredPane(); contentPane.setBorder(new EmptyBorder(border, border, border, border)); setContentPane(contentPane); contentPane.setLayout(null); /* * Background inspired from LoZ Majora's Mask, covers entire content pane, but displayed on a layer * underneath everything else */ lblBackground = new JLabel(); lblBackground.setBounds(contentPaneX, contentPaneY, contentPaneWidth, contentPaneHeight); contentPane.add(lblBackground); contentPane.setLayer(lblBackground, -1); //-1 means it is the most "background" layer lblBackground.setIcon(new ImageIcon(SetGUI.class.getResource("/lab5/client/mediumcards/backgroundrescaled.png"))); /* * Fancy title text */ lblTitle = new JLabel("Set"); lblTitle.setForeground(Color.LIGHT_GRAY); lblTitle.setFont(new Font("Mistral", Font.PLAIN, 60)); lblTitle.setHorizontalAlignment(SwingConstants.CENTER); lblTitle.setBounds(titleX, titleY, titleWidth, titleHeight); contentPane.add(lblTitle); contentPane.setLayer(lblTitle, 0); //For all future cases, and including this one, //layer 0 is the standard above the background image /* * Pane which allows selection of number of players */ startGamePane = new JScrollPane(); startGamePane.setBounds(startNumPlayerX, startNumPlayerY, startNumPlayerWidth, startNumPlayerHeight); contentPane.add(startGamePane); contentPane.setLayer(startGamePane, 0); //model allows for modification of list information listModelStartPlayers = new DefaultListModel(); listStartPlayers = new JList(listModelStartPlayers); listStartPlayers.setBorder(new TitledBorder(null, "Number of Players", TitledBorder.LEADING, TitledBorder.TOP, null, null)); startGamePane.setViewportView(listStartPlayers); //Fills list with 1-4 players for (byte i = 1; i <= 4; i++) { listModelStartPlayers.addElement(i); } /* * Input text field for choosing player's name */ nameField = new JTextField(); nameField.setToolTipText("Type your name here"); nameField.setText("Type your name in this box"); nameField.setBounds(nameFieldX, nameFieldY, nameFieldWidth, nameFieldHeight); contentPane.add(nameField); contentPane.setLayer(nameField, 0); nameField.setColumns(border*2); /* * Standard button, lets player start after number of players * is chosen */ start = new JButton(); start.setToolTipText("Select number of players and enter your name and press to start."); start.setText("Start Game"); start.setBounds(startButtonX, startButtonY, startButtonWidth, startButtonHeight); contentPane.add(start); contentPane.setLayer(start, 0); /* * Upon press, checks to make sure a number of players are chosen, and that * the user has typed in a valid name. Will attempt to connect to server, using client's hello method */ start.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (listStartPlayers.getSelectedValue() != null) { if(nameField.getText()!= "" && !nameField.getText().equals("Type your name in this box") && !nameField.getText().equals("Need to type your name first")){ if(client.connect()){ start.setText("Waiting For Players"); start.setEnabled(false); String nameToSend = nameField.getText().replaceAll("%", "");//makes sure the name doesn't have a % in it if(nameToSend.length()>36)nameToSend=nameToSend.substring(0, 36);//makes sure the name isn't too long client.sayHello(nameToSend, ((Byte) (listStartPlayers.getSelectedValue())).byteValue()); } }else{ nameField.setText("Need to type your name first"); } } else { nameField.setText("Need to select the number of players"); } } }); /* * Set Button that allows player to pick cards * after pressing in order to attempt a set */ setButton = new JButton("Call Set"); setButton.setToolTipText("Press this button before selecting cards to send them as a set. If another player is selecting cards, you have to wait until they finish"); setButton.setBounds(setButtonX, setButtonY, setButtonWidth, setButtonHeight); contentPane.add(setButton); contentPane.setLayer(setButton, 0); //Button changes state of setPressed to true, allowing players to attempt //a set setButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (!setPressed) { client.playerCallSet(); //sends message to attempt to call set setPressed = true; } } }); /* * Counter section for number of cards left in deck. */ numberOfCardsInDeck = new JTextArea(); numberOfCardsInDeck.setToolTipText("Number of cards left in deck."); numberOfCardsInDeck.setEditable(false); numberOfCardsInDeck.setBounds(cardsNumAreaX, cardsNumAreaY, cardsNumAreaWidth, cardsNumAreaHeight); contentPane.add(numberOfCardsInDeck); contentPane.setLayer(numberOfCardsInDeck, 0); /* * Label to indicate what the counter is keeping track of */ lblNumberOfCards = new JLabel("Cards left in deck"); lblNumberOfCards.setForeground(Color.LIGHT_GRAY); lblNumberOfCards.setBounds(numCardsLblX, numCardsLblY, numCardsLblWidth, numCardsLblHeight); lblNumberOfCards.setHorizontalAlignment(SwingConstants.RIGHT); contentPane.add(lblNumberOfCards); contentPane.setLayer(numberOfCardsInDeck, 0); /* * Pane which keeps track of players in the game */ playersPane = new JScrollPane(); playersPane.setBounds(playerPaneX, playerPaneY, playerPaneWidth, playerPaneHeight); contentPane.add(playersPane); contentPane.setLayer(playersPane, 0); //list model allows for easy modification listModelPlayers = new DefaultListModel(); listPlayers = new JList(listModelPlayers); listPlayers.setBorder(new TitledBorder(null, "Players", TitledBorder.LEADING, TitledBorder.TOP, null, null)); playersPane.setViewportView(listPlayers); /* * Pane which keeps track of score */ playersPointsPane = new JScrollPane(); playersPointsPane.setBounds(pointPaneX, pointPaneY, pointPaneWidth, pointPaneHeight); contentPane.add(playersPointsPane); contentPane.setLayer(playersPointsPane, 0); //list model allows for easy change listModelScores = new DefaultListModel(); listPlayersPoints = new JList(listModelScores); playersPointsPane.setViewportView(listPlayersPoints); listPlayersPoints.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Scores", TitledBorder.LEADING, TitledBorder.TOP, null, null)); /* * Button which can be pressed to ask for a column addition, or call to end game */ addCardsButton = new JButton("Add Cards"); addCardsButton.setToolTipText("Ask for a new column of cards(Needs majority vote). Call if you can't find any sets"); addCardsButton.setBounds(addCardsButtonX, addCardsButtonY, addCardsButtonWidth, addCardsButtonHeight); contentPane.add(addCardsButton); contentPane.setLayer(addCardsButton, 0); //Upon press, sends message through client to request for a row addition, or if not enough cards, end the game addCardsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { client.askForCards(); addCardsButton.setEnabled(false); } }); // //All of the game components are set invisible until the set button is pressed // setButton.setVisible(false); lblNumberOfCards.setVisible(false); numberOfCardsInDeck.setVisible(false); playersPointsPane.setVisible(false); playersPane.setVisible(false); addCardsButton.setVisible(false); //cards are generated (invisible as well) generateCards(); }
8
public String simplifyPath(String path){ if (path == null || path.length() == 0) return "/"; Stack<String> stack = new Stack<String>(); for (String s : path.split("/")){ if (s.length() == 0 || s.equals(".")) continue; else if (s.equals("..")){ if (!stack.isEmpty()) stack.pop(); } else stack.push(s); } if (stack.isEmpty()) return "/"; StringBuffer sb = new StringBuffer(""); while (!stack.isEmpty()){ sb.insert(0, stack.pop()); sb.insert(0, "/"); } return sb.toString(); }
9
private boolean tryFindPath() { for (Node neighbour : neighbours) { if (neighbour.x == n || neighbour.y == 0) { return true; } if (!neighbour.isReachable()) { neighbour.setReachable(); if (neighbour.tryFindPath()) { return true; } } } return false; }
5
public Object getValueAt(int row, int col) { if(row>-1 && col>-1 && data!=null) return data[row][col]; else return null; }
3
public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException { // TODO Auto-generated method stub // // Testing 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(SimoneUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SimoneUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SimoneUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SimoneUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SimoneUI().setVisible(true); } }); SimoneCore.displayHighScore(); SimoneCore.buildPlayer(); }
6
private void finishFileReceiverThread() { if (this.fileReceiverThread != null) while (this.fileReceiverThread.isAlive()) { this.fileReceiverThread.interrupt(); this.log.fine("FileReceiver thread is interupt"); stopFileReceiver(); } }
2
public void run() { while (pause) { Thread.yield(); } paused = true; while (running) { if (DO_VALIDATION) { boolean done = false; while (pause) { if (!done) { System.out.println("Thread " + Thread.currentThread().getId() + ": Stoped"); paused = true; done = true; } } paused = false; } int op = rand.nextInt(100); if (op < put) { Article a = generateArticle(); repository.insertArticle(a); } else if (op < put + del) { int id = rand.nextInt(dictSize); repository.removeArticle(id); } else if (op < put + del + (get / 2)) { List<String> list = generateListOfWords(); repository.findArticleByAuthor(list); } else { List<String> list = generateListOfWords(); repository.findArticleByKeyword(list); } count++; } updateOperations(count); }
8
@Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (qName.equals("rowset")) { String name = getString(attrs, "name"); factions = name.equals("factions"); factionWars = name.equals("factionWars"); } else if (qName.equals("row")) { if (factions) { ApiFactionStats item = new ApiFactionStats(); item.setFactionID(getInt(attrs, "factionID")); item.setFactionName(getString(attrs, "factionName")); item.setPilots(getInt(attrs, "pilots")); item.setSystemsControlled(getInt(attrs, "systemsControlled")); item.setKillsYesterday(getInt(attrs, "killsYesterday")); item.setKillsLastWeek(getInt(attrs, "killsLastWeek")); item.setKillsTotal(getInt(attrs, "killsTotal")); item.setVictoryPointsYesterday(getInt(attrs, "victoryPointsYesterday")); item.setVictoryPointsLastWeek(getInt(attrs, "victoryPointsLastWeek")); item.setVictoryPointsTotal(getInt(attrs, "victoryPointsTotal")); response.addStat(item); } else if (factionWars) { ApiFactionWar item = new ApiFactionWar(); item.setFactionID(getInt(attrs, "factionID")); item.setFactionName(getString(attrs, "factionName")); item.setAgainstID(getInt(attrs, "againstID")); item.setAgainstName(getString(attrs, "againstName")); response.addStat(item); } } super.startElement(uri, localName, qName, attrs); }
4
@Override public void execute(double t) { try { if (input.getDic() != null && input.getDic().getSource() != null) output.setOutput(input.getDic().getInput()); } catch (OrderException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3
public void createMap(int size) { if (!edit) { gui.console("Click \"Edit Graph\" button"); return; } clearGraph(); boolean directed = graph.isDirected(); graph.setDirected(false); int center_x = rel(getWidth() / 2); int center_y = rel(getHeight() / 2); Point p = new Point(center_x, center_y); createAroundVertex(p); for (int i = 1; i < size; i++) { createAroundVertex(new Point(p.x - i, p.y)); createAroundVertex(new Point(p.x + i, p.y)); for (int j = 1; j < size / 2; j++) { createAroundVertex(new Point(p.x - i, p.y + j)); createAroundVertex(new Point(p.x + i, p.y - j)); createAroundVertex(new Point(p.x + i, p.y + j)); createAroundVertex(new Point(p.x - i, p.y - j)); } } for (int i = 1; i < size / 2; i++) { createAroundVertex(new Point(p.x, p.y + i)); createAroundVertex(new Point(p.x, p.y - i)); } graph.setDirected(directed); repaint(); }
4
public boolean mouseDown (Event event, int x, int y) { dragStart = new Point (x, y); dragged = false; if (selectionAllowed && wave != null) { if ((event.modifiers & Event.META_MASK) != 0 || (event.modifiers & Event.ALT_MASK) != 0 || (event.modifiers & Event.CTRL_MASK) != 0) { selectNone(); repaint(); } else if (event.clickCount == 2) { select (viewStart, viewEnd); repaint(); } else if (event.clickCount == 3) { selectAll(); repaint(); } else { rubberBand = new BoxStretchRubberBand (x, 1, size().height-2); selectingFlag = true; } } else return super.mouseDown (event, x, y); return true; }
7
public byte[] getTiledImageData() { byte[] palettedImage = new byte[width * height]; int tileCount = width * height / 64; int tileWidth = width / 8; for (int t = 0; t < tileCount; t++) for (int y = 0; y < 8; y++) for (int x = 0; x < 8; x++) { int tx = (t % tileWidth) * 8; int ty = (int) (t / tileWidth) * 8; palettedImage[t * 64 + y * 8 + x] = (byte) imageData[tx + x][ty + y]; } return palettedImage; }
3
public void fillObject(CreditProgram crProg, ResultSet result) { //Заполняем кредитную программу try { crProg.setId(result.getInt("ID")); crProg.setName(result.getString("CREDITNAME")); crProg.setMinAmount(result.getLong("CREDITMINAMOUNT")); crProg.setMaxAmount(result.getLong("CREDITMAXAMOUNT")); crProg.setDuration(result.getInt("CREDITDURATION")); crProg.setStartPay(result.getDouble("CREDITSTARTPAY")); crProg.setPercent(result.getDouble("CREDITPERCENT")); crProg.setDescription(result.getString("CREDITDESCRIPTION")); crProg.setCreditProgStatus(result.getInt("CREDITPROGSTATUS")); } catch (SQLException exc) { JOptionPane.showMessageDialog(null, "Ошибка при извлечении обьекта из базы"); } }
1
@SuppressWarnings("unchecked") public void configFromJSONFile(String fileName) throws IOException, JSONException, ClassNotFoundException{ File file=new File(fileName); FileInputStream fileStream=new FileInputStream(file); BufferedReader reader=new BufferedReader(new InputStreamReader(fileStream)); StringBuilder sb=new StringBuilder(); String line=null; while((line=reader.readLine())!=null){ sb.append(line); sb.append("\n"); } JSONObject configJson=new JSONObject(sb.toString()); JSONArray moduleArray=configJson.getJSONArray("modules"); //load class ClassLoader classLoader=ClassLoader.getSystemClassLoader(); for(int i=0,length=moduleArray.length();i<length;i++){ String moduleName=moduleArray.getString(i); Class<? extends IModule> clazz; clazz=(Class<? extends IModule>) classLoader.loadClass(moduleName); classSet.add(clazz); } //add config for each module into context for(Class<? extends IModule> clazz:classSet){ JSONObject moduleConfig; try{ moduleConfig=configJson.getJSONObject(clazz.getCanonicalName()); }catch(JSONException e){ continue; } Iterator<?> iter=moduleConfig.keys(); while(iter.hasNext()){ String key=(String) iter.next(); String value=moduleConfig.getString(key); this.moduleContext.addConfigParam(clazz, key, value); } } reader.close(); }
9
private void changeMapInternal(final MapleMap to, final Point pos, MaplePacket warpPacket) { if (NPCScriptManager.getInstance().getCM(client) != null) { NPCScriptManager.getInstance().dispose(client); } if (eventInstance != null) { eventInstance.changedMap(this, to.getId()); } removeClones(); if (isChunin() && !noHide) { this.hide(); } if (isHidden() && !noHide) { getClient().getSession().write(MaplePacketCreator.sendGMOperation(16, 1)); } client.getSession().write(warpPacket); map.removePlayer(this); if (client.getChannelServer().getPlayerStorage().getCharacterById(getId()) != null) { map = to; setPosition(pos); to.addPlayer(this); stats.relocHeal(); } }
7
public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource() == btAddCopy) { this.dispose(); new AddCopy(user); } else if(e.getSource() == btAddDoc) { this.dispose(); new AddDocTypeChooseFrame(user); } if(e.getSource() == btDltCopy){ this.dispose(); new DeleteCopy(user); } else if(e.getSource() == btDltDoc){ this.dispose(); new DeleteDoc(user);// need a class } else if(e.getSource() == btMdfDoc){ try { String str = JOptionPane.showInputDialog("Please enter an item ID"); new modifyDoc(user, str); }catch (NullPointerException exc) { return; } } else if(e.getSource() == btSearchDoc){ new SearchFrame(user); } else if(e.getSource() == btR){ this.dispose(); new LibraryLogInFrame(); }else if(e.getSource() == btRDoc){ this.dispose(); new ReturnInformationFrame(user); } }
9
private int processOrderList(ArrayList<Trade> trades, OrderList orders, int qtyRemaining, Order quote, boolean verbose) { String side = quote.getSide(); int buyer, seller; int takerId = quote.gettId(); int time = quote.getTimestamp(); while ((orders.getLength()>0) && (qtyRemaining>0)) { int qtyTraded = 0; Order headOrder = orders.getHeadOrder(); if (qtyRemaining < headOrder.getQuantity()) { qtyTraded = qtyRemaining; if (side=="offer") { this.bids.updateOrderQty(headOrder.getQuantity()-qtyRemaining, headOrder.getqId()); } else { this.asks.updateOrderQty(headOrder.getQuantity()-qtyRemaining, headOrder.getqId()); } qtyRemaining = 0; } else { qtyTraded = headOrder.getQuantity(); if (side=="offer") { this.bids.removeOrderByID(headOrder.getqId()); } else { this.asks.removeOrderByID(headOrder.getqId()); } qtyRemaining -= qtyTraded; } if (side=="offer") { buyer = headOrder.gettId(); seller = takerId; } else { buyer = takerId; seller = headOrder.gettId(); } Trade trade = new Trade(time, headOrder.getPrice(), qtyTraded, headOrder.gettId(),takerId, buyer, seller, headOrder.getqId()); trades.add(trade); this.tape.add(trade); if (verbose) { System.out.println(trade); } } return qtyRemaining; }
7
public TypeConvert() { }
0
public static int readVarInt(ByteBuf byteBuf) { int out = 0; int bytes = 0; byte in; while (true) { in = byteBuf.readByte(); out |= (in & 0x7F) << (bytes++ * 7); if (bytes > 5) { throw new IllegalStateException("Integer is bigger than maximum allowed!"); } if ((in & 0x80) != 0x80) { break; } } return out; }
3
public void run() { try { //Obtenemos datos como el NICKNAME entrada=new ObjectInputStream(conexion.getInputStream()); this.nickname=(String)entrada.readObject(); //Actualizamos usuarios usuarios.add(nickname); ventana.setUsuarios(usuarios); /**asdasdasdasdasd*/ salidaUsuarios=new ObjectOutputStream(conexionUsuarios.getOutputStream()); salidaUsuarios.writeObject(usuarios); //sal2=new ObjectOutputStream(conexionUsers.getOutputStream()); //sal2.writeObject(usuarios); //Informamos de la conexion salida=new ObjectOutputStream(conexion.getOutputStream()); ventana.setPanelText("Conectado con: " + this.nickname+ " desde "+conexion.getInetAddress().getHostAddress()+"\n", Color.blue); flujoSalida(2,"Conectado con: ", this.nickname+" desde "+conexion.getInetAddress().getHostAddress()); System.out.println("Conectado con: " + this.nickname+ " desde "+conexion.getInetAddress().getHostAddress()+"\n"); flujoSalidaUsuarios(usuarios,this.nickname); //Ecuchando algun mensaje entrante //entrada = new ObjectInputStream(conexion.getInputStream()); DES CifradoDes=new DES(this.clave); while (!stop) { //Obtenemos el mensaje y lo imprimimos en pantalla System.out.print("El tipo de emsanje entranre es: " ); String lectura = (String) entrada.readUTF(); System.out.println(lectura); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); Calendar cal = Calendar.getInstance(); switch (Integer.parseInt(lectura)){ case 1: lectura = CifradoDes.desencriptar((String) entrada.readUTF()); ventana.setPanelText(this.nickname+"("+dateFormat.format(cal.getTime())+")>> ",Color.magenta); ventana.setPanelText(lectura+"\n",Color.black); //Lo enviamos a los demas usuarios //flujoSalida(this.nickname+">>"+lectura,this.nickname); flujoSalida(lectura,this.nickname); break; case 4: lectura = CifradoDes.desencriptar((String) entrada.readUTF()); ventana.setPanelText(this.nickname+"("+dateFormat.format(cal.getTime())+")>> ",Color.magenta); ventana.setPanelText("ha subido el archivo "+lectura+"\n",Color.blue); //Lo enviamos a los demas usuarios //flujoSalida(this.nickname+">>"+lectura,this.nickname); flujoSalida(4,this.nickname,lectura); break; } } } catch (ClassNotFoundException ex) { Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { try { System.out.println("Controlado"); //Actualizamos usuarios usuarios.remove(nickname); ventana.setUsuarios(usuarios); ventana.setPanelText("Cerrando conexion con: " + this.nickname + " desde "+conexion.getInetAddress().getHostAddress()+"\n", Color.red); flujoSalida(3,"Cerrando conexion con: ",this.nickname+" desde "+conexion.getInetAddress().getHostAddress()+"\n"); System.out.println("Conectado conexion con: " + this.nickname + " desde "+conexion.getInetAddress().getHostAddress()+"\n"); /* try { sal2.writeObject(usuarios); } catch (IOException ex1) { Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex1); }*/ } catch(Exception e){ e.printStackTrace(); } } finally { try { entrada.close(); } catch (IOException ex) { Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex); } } }
7
public CreatePDFRaport() { }
0
public static SpMat getAddReqEdges(GraphModel gILU, SpMat m, SpMat mR, SpMat mP,Vector<Integer> order) { SpMat addM = new SpMat(m.rows(),m.cols()); //for (int i = 0; i < m.getRowDimension(); i++) { // for (int j = 0; j < m.getColumnDimension(); j++) { for(int i : order) { for(int j : order) { if(mP.contains(i, j)) { boolean isAdd = true; if(i > j) { for (Vertex v : gILU.directNeighbors(gILU.getVertex(j))) { if (v.getId() > j) { isAdd = false; break; } } } else { for (Vertex v : gILU.directNeighbors(gILU.getVertex(i))) { if (v.getId() > i) { isAdd=false; break; } } } if(isAdd) { addM.set(i, j); gILU.addEdge(new Edge(gILU.getVertex(i), gILU.getVertex(j))); } } } } return addM; }
9
public void generate_test() { boolean lowerTail = true; for (int i = 0; i < numTests;) { int N = rand.nextInt(MAX) + 1; int D = rand.nextInt(N) + 1; int n = rand.nextInt(N) + 1; int k = Math.max(rand.nextInt(Math.min(n, D)), 1); if (Hypergeometric.get().checkHypergeometricParams(k, N, D, n)) { double p = FisherExactTest.get().pValueDown(k, N, D, n, threshold); if (p < threshold) { System.out.print("\t print ( paste( 'compareFisher( " + k + ", " + N + ", " + D + ", " + n + ", ' , " + FisherExactTest.get().toR(k, N, D, n, lowerTail) + " , ');' ) );"); System.out.println(""); i++; } } } }
3
public boolean checkWord(String word) { word = word.toLowerCase(); // This is very inefficient for (int i = 0; i < m_dictionary.length; i++) { if (m_dictionary[i].equals(word)) { return true; } } return false; }
2
private void batchEstimateDataAndMemory(boolean useRuntimeMaxJvmHeap, String outputDir) throws IOException { //File mDataOutputFile = new File(outputDir, "eDataMappers.txt"); //File rDataOutputFile = new File(outputDir, "eDataReducers.txt"); File mJvmOutputFile = new File(outputDir, "eJvmMappers.txt"); File rJvmOutputFile = new File(outputDir, "eJvmReducers.txt"); if(!mJvmOutputFile.getParentFile().exists()) mJvmOutputFile.getParentFile().mkdirs(); //PrintWriter mDataWriter = new PrintWriter(new BufferedWriter(new FileWriter(mDataOutputFile))); //PrintWriter rDataWriter = new PrintWriter(new BufferedWriter(new FileWriter(rDataOutputFile))); PrintWriter mJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(mJvmOutputFile))); PrintWriter rJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(rJvmOutputFile))); //displayMapDataTitle(mDataWriter); //displayReduceDataTitle(rDataWriter); displayMapJvmCostTitle(mJvmWriter); displayReduceJvmCostTitle(rJvmWriter); for(int xmx = 1000; xmx <= 4000; xmx = xmx + 1000) { for(int ismb = 200; ismb <= 1000; ismb = ismb + 200) { for(int reducer = 9; reducer <= 18; reducer = reducer * 2) { for(int xms = 0; xms <= 1; xms++) { //--------------------------Estimate the data flow--------------------------- //-----------------for debug------------------------------------------------- //System.out.println("[xmx = " + xmx + ", xms = " + xms + ", ismb = " + // ismb + ", RN = " + reducer + "]"); //if(xmx != 4000 || ismb != 400 || reducer != 16 || xms != 1) // continue; //if(xmx != 4000 || xms != 1 || ismb != 1000 || reducer != 9) // continue; //--------------------------------------------------------------------------- Configuration conf = new Configuration(); //long newSplitSize = 128 * 1024 * 1024l; conf.set("io.sort.mb", String.valueOf(ismb)); if(xms == 0) conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m"); else conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m" + " -Xms" + xmx + "m"); conf.set("mapred.reduce.tasks", String.valueOf(reducer)); //conf.set("split.size", String.valueOf(newSplitSize)); setNewConf(conf); // -------------------------Estimate the data flow------------------------- List<Mapper> eMappers = estimateMappers(); //don't filter the mappers with small split size List<Reducer> eReducers = estimateReducers(eMappers, useRuntimeMaxJvmHeap); String fileName = conf.getConf("mapred.child.java.opts").replaceAll(" ", "") + "-ismb" + ismb + "-RN" + reducer; displayMapperDataResult(eMappers, fileName , outputDir + File.separator + "eDataflow"); displayReducerDataResult(eReducers, fileName, outputDir + File.separator + "eDataflow"); // -------------------------Estimate the memory cost------------------------- InitialJvmCapacity gcCap = computeInitalJvmCapacity(); if(!gcCap.getError().isEmpty()) { System.err.println(gcCap.getError() + " [xmx = " + xmx + ", xms = " + xms + ", ismb = " + ismb + ", RN = " + reducer + "]"); } else { //filter the estimated mappers with low split size List<MapperEstimatedJvmCost> eMappersMemory = estimateMappersMemory(eMappers, gcCap); List<ReducerEstimatedJvmCost> eReducersMemory = estimateReducersMemory(eReducers, gcCap); displayMapperJvmCostResult(eMappersMemory, gcCap, mJvmWriter); displayReducerJvmCostResult(eReducersMemory, gcCap, rJvmWriter); } } } } } mJvmWriter.close(); rJvmWriter.close(); }
7
public static Boolean isTypeAllowed(Class<?> clazz) { // Logger.getAnonymousLogger().info("checking type : " + clazz.getName()); if (clazz.isPrimitive() || getAllowedTypes().contains(clazz)) { return true; } Set<Class<?>> allowedTypes = getAllowedTypes(); for (Class<?> allowedType : allowedTypes) { if (allowedType.isAssignableFrom(clazz)) { return true; } } return false; }
7
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(ChatGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ChatGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ChatGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ChatGui.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 ChatGui().setVisible(true); } }); }
6
public synchronized int SelctUrls(String url) { int id = 0; try { ResultSet re = tags_ste.executeQuery("SELECT * from zhangyu_sca.article_urls WHERE (list_url = '" + url + "');"); re.next(); id = re.getInt("article_id"); } catch (SQLException e) { e.printStackTrace(); } return id; }
1
public Player play() { Output out1 = _player1.draw(); Output out2 = _player2.draw(); int outcome = determineWin(out1, out2); if(outcome == 0) { return null; } else if(outcome == 1) { return _player1; } return _player2; }
2
public View create(Element elem) { String kind = elem.getName(); if (kind != null) { if (kind.equals(AbstractDocument.ContentElementName)) { return new WrapLabelView(elem); } else if (kind.equals(AbstractDocument.ParagraphElementName)) { return new ParagraphView(elem); } else if (kind.equals(AbstractDocument.SectionElementName)) { return new BoxView(elem, View.Y_AXIS); } else if (kind.equals(StyleConstants.ComponentElementName)) { return new ComponentView(elem); } else if (kind.equals(StyleConstants.IconElementName)) { return new IconView(elem); } } return new WrapLabelView(elem); }
6