text
stringlengths
14
410k
label
int32
0
9
public void removeOrganization(String key) { try { Organization org = organizations.get(key); // Delete all subOrganizations if ( !org.getAllSubOrganizations().isEmpty() && org.getAllSubOrganizations().size() > 0 ) { Enumeration<String> subOrgs = org.getAllSubOrganizations().keys(); while ( subOrgs.hasMoreElements() ) { String subOrg = (String) subOrgs.nextElement(); removeOrganization(subOrg); } } Enumeration<String> orgRoleNames = org.getAllAgentRoles().keys(); AgentRole orgRole = null; while( orgRoleNames.hasMoreElements() ) { String orgRoleName = (String) orgRoleNames.nextElement(); orgRole = org.getAgentRole(orgRoleName); GenericAgent agent = orgRole.getPlayer(); Enumeration<String> aRoleNames = agent.getAllAgentRoles().keys(); AgentRole aRole = null; boolean hasOtherOrgs = false; // Cancel the role with agents while ( aRoleNames.hasMoreElements() ) { String aRoleName = (String) aRoleNames.nextElement(); aRole = agent.getAgentRole(aRoleName); if ( aRole.getOwner() != org ) { aRole.getOwner().getContainerController().acceptNewAgent(agent.getName(), agent); hasOtherOrgs = true; break; } } // When agent have not other organizations, it will be deleted if( !hasOtherOrgs ) removeAgent( agent.getName() ); // Removes the instance of AgentRole org.removeAgentRole( orgRoleName ); } // Delete the container on JADE and JAMDER org.getContainerController().kill(); organizations.remove(key); } catch(ControllerException exception) { exception.printStackTrace(); } }
8
public ArrayList<TreeNode> generateTrees(int n) { ArrayList<TreeNode>[] trees = new ArrayList[n +1]; trees[0] = new ArrayList<TreeNode>(); trees[0].add(null); if (n == 0) return trees[0]; trees[1] = new ArrayList<TreeNode>(); TreeNode node = new TreeNode(1); node.left = node.right = null; trees[1].add(node); for (int i = 2; i <= n; i++) { trees[i] = new ArrayList<TreeNode>(); for (int j = 1; j<= i; j++) { for (TreeNode left : trees[j-1]){ for ( TreeNode right : trees[i - j]) { TreeNode ele = new TreeNode(j); ele.left = copy(left,0); ele.right = copy(right, j); trees[i].add(ele); } } } } return trees[n]; }
5
public static void main(String args[]){ Scanner sc = new Scanner(System.in); int N; while(true) { N = sc.nextInt(); if(N==0) break; String str = sc.next(); boolean zFound = false; if(str.contains("Z")) zFound = true; int recentR=N+N,recentD=N; int minDist = N+1; for(int i=0;i<N && !zFound && minDist!=1;i++) { if(str.charAt(i)=='D') { recentD = i; minDist = Math.min(minDist , Math.abs(recentD-recentR)); } else if(str.charAt(i)=='R') { recentR = i; minDist = Math.min(minDist , Math.abs(recentD-recentR)); } } if(zFound) System.out.println(0); else System.out.println(minDist); } }
9
public PropertyHandler(File propertyFile) { this.file = propertyFile; if (propertyFile.exists()) { FileInputStream inputStream = null; try { inputStream = new FileInputStream(propertyFile); this.properties.load(inputStream); } catch (IOException e) { MaintenanceServer.LOGGER.warning("Failed to load " + propertyFile); this.saveProperties(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // Swallow } } } } else { this.saveProperties(); } }
4
public static List<Episode> getAllEpisodes(String urlString, int season) throws TvDbException { List<Episode> episodeList = new ArrayList<>(); Episode episode; NodeList nlEpisode; Node nEpisode; Element eEpisode; Document doc = DOMHelper.getEventDocFromUrl(urlString); nlEpisode = doc.getElementsByTagName(EPISODE); for (int loop = 0; loop < nlEpisode.getLength(); loop++) { nEpisode = nlEpisode.item(loop); if (nEpisode.getNodeType() == Node.ELEMENT_NODE) { eEpisode = (Element) nEpisode; episode = parseNextEpisode(eEpisode); if ((episode != null) && (season == -1 || episode.getSeasonNumber() == season)) { // Add the episode only if the season is -1 (all seasons) or matches the season episodeList.add(episode); } } } return episodeList; }
5
public static boolean mapAndEnqueueVariableP(Stella_Object variable, Stella_Object localvalue, KeyValueMap mapping) { if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(variable), Logic.SGT_LOGIC_PATTERN_VARIABLE)) { { PatternVariable variable000 = ((PatternVariable)(variable)); { Stella_Object mapstovalue = mapping.lookup(variable000); if (mapstovalue == null) { mapstovalue = Logic.nativeValueOf(variable000); if (mapstovalue != null) { mapping.insertAt(variable000, mapstovalue); } } if (mapstovalue != null) { return ((localvalue == null) || (Stella_Object.eqlP(mapstovalue, localvalue) || (Logic.skolemP(localvalue) || Logic.skolemP(mapstovalue)))); } else if (localvalue != null) { mapping.insertAt(variable000, localvalue); } else { { Skolem skolem = Logic.createVariableOrSkolem(variable000.skolemType, null); mapping.insertAt(variable000, skolem); } } } } } else { } return (true); }
8
public CASResponse cas(String key, Object value, int ttlSec, long cas, long timeoutMiliSec) throws TimeoutException, com.quickserverlab.quickcached.client.MemcachedException{ try{ Future <net.spy.memcached.CASResponse> f = getCache(). asyncCAS(key, cas, ttlSec, value, getCache().getTranscoder()); try { net.spy.memcached.CASResponse cv = (net.spy.memcached.CASResponse) f.get(timeoutMiliSec, TimeUnit.MILLISECONDS); if(cv != null){ if(cv.equals(net.spy.memcached.CASResponse.OK)){ return CASResponse.OK; }else if(cv.equals(net.spy.memcached.CASResponse.EXISTS)){ return CASResponse.EXISTS; }else if(cv.equals(net.spy.memcached.CASResponse.NOT_FOUND)){ return CASResponse.NOT_FOUND; } else { return CASResponse.ERROR; } }else{ return CASResponse.ERROR; } }catch(CancellationException ce){ throw new com.quickserverlab.quickcached.client.MemcachedException("CancellationException "+ ce); }catch(ExecutionException ee){ throw new com.quickserverlab.quickcached.client.MemcachedException("ExecutionException "+ ee); }catch(InterruptedException ie){ throw new com.quickserverlab.quickcached.client.MemcachedException("InterruptedException " + ie); }catch(java.util.concurrent.TimeoutException te){ throw new TimeoutException("Timeout "+te); }finally{ f.cancel(false); } }catch(IllegalStateException ise){ throw new com.quickserverlab.quickcached.client.MemcachedException("IllegalStateException "+ ise); } }
9
@Override public String execute(SessionRequestContent request) throws ServletLogicException { String page = (String) request.getSessionAttribute(JSP_PAGE); resaveParamsCitySelected(request); request.setAttribute(JSP_CURR_ID_HOTEL, "0"); String currCity = request.getParameter(JSP_CURR_ID_CITY); if (currCity != null && !currCity.isEmpty()){ Integer idCity = Integer.decode(currCity); if (idCity > 0) { request.setAttribute(JSP_ID_CITY, idCity); } new HotelCommand().formHotelList(request); } return page; }
3
private JFileChooser getJFileChooser(){ if (this.jFileChooser == null){ this.jFileChooser = new JFileChooser(); } return this.jFileChooser; }
1
@Test public void testOutputFutureMeetings() throws IOException { Calendar thisDate = new GregorianCalendar(2015,3,2); cm.addFutureMeeting(contacts, thisDate); cm.addNewPastMeeting(contacts, new GregorianCalendar(2013,5,3), "meeting"); cm.flush(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("contacts.txt")); List inputData = null; try { inputData = (ArrayList) ois.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { ois.close(); } catch (IOException ex){ ex.printStackTrace(); } } List<Meeting> futureMeetingList = (ArrayList) inputData.get(0); assertTrue(futureMeetingList.get(0).getDate().compareTo(thisDate) == 0); }
2
@Override public boolean equals(Object other) { if ((other == null) || !(other instanceof Pair<?,?>)) { return false; } return ((Pair<?, ?>)other).first.equals(first) && ((Pair<?, ?>)other).second.equals(second); }
9
public boolean upload(String sourceFile, String destFile, String group, UserToken token) { if (destFile.charAt(0) != '/') { destFile = "/" + destFile; } try { Envelope message = null, response = null; message = new Envelope("UPLOADF"); message.addObject(destFile); message.addObject(group); message.addObject(token); // Add requester's token output.writeObject(message); FileInputStream fis = new FileInputStream(sourceFile); response = (Envelope) input.readObject(); if (response.getMessage().equals("READY")) { System.out.printf("Meta data upload successful\n"); } else { System.out.printf("Upload failed: %s\n", response.getMessage()); fis.close(); return false; } do { byte[] buf = new byte[4096]; if (response.getMessage().compareTo("READY") != 0) { System.out.printf("Server error: %s\n", response.getMessage()); fis.close(); return false; } message = new Envelope("CHUNK"); int n = fis.read(buf); // can throw an IOException if (n > 0) { System.out.printf("."); } else if (n < 0) { System.out.println("Read error"); fis.close(); return false; } message.addObject(buf); message.addObject(new Integer(n)); output.writeObject(message); response = (Envelope) input.readObject(); } while (fis.available() > 0); fis.close(); if (response.getMessage().compareTo("READY") == 0) { message = new Envelope("EOF"); output.writeObject(message); response = (Envelope) input.readObject(); if (response.getMessage().compareTo("OK") == 0) { System.out.printf("\nFile data upload successful\n"); } else { System.out.printf("\nUpload failed: %s\n", response.getMessage()); return false; } } else { System.out.printf("Upload failed: %s\n", response.getMessage()); return false; } } catch (Exception e1) { System.err.println("Error: " + e1.getMessage()); e1.printStackTrace(System.err); return false; } return true; }
9
@Override public void method3() { System.out.println("ClassA method3()"); }
0
private ArrayList<Edge> getCoast() { try { //Get time, Connection and ResultSet Long time = System.currentTimeMillis(); Edge edge = null; String sql = "SELECT * FROM [jonovic_dk_db].[dbo].[correctedCoastLine];"; Connection con = cpds.getConnection(); PreparedStatement pstatement = con.prepareStatement(sql); ResultSet rs = executeQuery(pstatement); time -= System.currentTimeMillis(); System.out.println("Time spent fetching elements: " + -time * 0.001 + " seconds..."); int i = 0; //Add edges to edge ArrayList, and count percentage for loading screen. while (rs.next()) { Point2D startNode = new Point2D.Double(rs.getDouble(1), rs.getDouble(2)); Point2D endNode = new Point2D.Double(rs.getDouble(3), rs.getDouble(4)); edge = new Edge(new Node(startNode),new Node(endNode), 74, "", 0, Double.MAX_VALUE, Double.MAX_VALUE); edge.setMidNode(); edges.add(edge); i++; //edgesDownloadedPct += (double) 1 / 812301; } System.out.println("Total edges: " + i); } catch (SQLException ex) { printSQLException(ex); } finally { closeConnection(cons, pstatements, resultsets); } Collections.sort(edges); edgesDownloadedPct = 1; return edges; }
2
private void printDirectReplies( Long parentId ) throws IOException { convFileWriter.write(parentId.toString()); if( !adjacencyList.containsKey(parentId)) return; long numOfReplies = adjacencyList.get(parentId).size(); if(numOfReplies == 0) return; convFileWriter.write('('); for( Long childId: adjacencyList.get(parentId)) { printDirectReplies(childId); if( numOfReplies > 1 ) convFileWriter.write(','); numOfReplies--; } convFileWriter.write(')'); }
4
private boolean checkPath(String path) { String[] parts = path.split("/"); if(parts.length != this.path.size()) return false; for(int i = 0; i < parts.length; i++) { PathPart pathPart = this.path.get(i); if(!pathPart.isVariable && !pathPart.name.equals(parts[i])) return false; } return true; }
4
public static double[] convert(List<Double> l) { double[] d = new double[l.size()]; for (int i = 0; i < d.length; i++) { d[i] = l.get(i); } return d; }
1
public int evalMove(Move m, State s, int depth) { if (depth == 0) { // cutting off search -> evaluate resulting state return evalState(s.tryMove(m), s); } else { // minimax-search // update the state State newstate = s.tryMove(m); // get a list of possible moves from newstate MyList moves = newstate.findMoves(); // shuffle so we don't always find the same maximum Collections.shuffle(moves); // return utility of state if there are no new moves if (moves.size() == 0) return evalState(newstate, s); // Iterate over all moves Iterator it = moves.iterator(); // We already know there is at least one move, so use it to // initialize minimaxvalue int minimaxvalue = evalMove((Move) it.next(), newstate, depth - 1); // now the rest of the moves while (it.hasNext()) { Move newmove = (Move) it.next(); int eval = evalMove(newmove, newstate, depth - 1); // if this is our turn, save the maximumvalue, otherwise // the mimimumvalue if (newstate.whoseTurn().equals(me)) // our turn minimaxvalue = Math.max(minimaxvalue, eval); else // opponent's turn minimaxvalue = Math.min(minimaxvalue, eval); } return minimaxvalue; } }
4
@SuppressWarnings("unchecked") public Action<Class<?>, Member> findAction(Action<Class<?>, Member> action) { try { VisitorAdapter<Class<?>, Member> v = new VisitorAdapter.ActionVisitor<Class<?>, Member>() { private String peek = getCommandLine().peek(); @Override public void visit(Action<Class<?>, Member> grp) { if (!getMode().isIgnored(grp)) if (getRecognizer().isActionValid(peek, grp) >= 0) { throw new VisitorAdapter.FoundCommand(grp); } } }; action.startVisit(v); } catch (VisitorAdapter.FoundCommand e) { return (Action<Class<?>, Member>) e.cmd; } return null; }
9
public mxICell decodeCell(Node node, boolean restoreStructures) { mxICell cell = null; if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { // Tries to find a codec for the given node name. If that does // not return a codec then the node is the user object (an XML node // that contains the mxCell, aka inversion). mxObjectCodec decoder = mxCodecRegistry .getCodec(node.getNodeName()); // Tries to find the codec for the cell inside the user object. // This assumes all node names inside the user object are either // not registered or they correspond to a class for cells. if (!(decoder instanceof mxCellCodec)) { Node child = node.getFirstChild(); while (child != null && !(decoder instanceof mxCellCodec)) { decoder = mxCodecRegistry.getCodec(child.getNodeName()); child = child.getNextSibling(); } String name = mxCell.class.getSimpleName(); decoder = mxCodecRegistry.getCodec(name); } if (!(decoder instanceof mxCellCodec)) { String name = mxCell.class.getSimpleName(); decoder = mxCodecRegistry.getCodec(name); } cell = (mxICell) decoder.decode(this, node); if (restoreStructures) { insertIntoGraph(cell); } } return cell; }
7
private boolean fileToPjt(int dId, FileType fileTyp) throws InvalidFormatException, OpenXML4JException, XmlException, IOException, SAXException, ParserConfigurationException { boolean result = false; String strText = ""; // Auswahl Methode je nach Dateityp switch (fileTyp) { case DOC: { strText = parseDoc(); result = true; break; } case DOCX: { strText = parseDocx(); result = true; break; } case PDF: { strText = parsePDF(); result = true; break; } case HTML: { strText = parseHTML(dId); result = true; break; } case TXT: { strText = parseTXT(dId); result = true; break; } default: { break; } } BufferedWriter bufferedWriter = null; try { File file = new File(Control.ROOT_FILES + dId + ".pjt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file.getAbsoluteFile()); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(strText); bufferedWriter.close(); } catch (IOException e) { _logger.debug(e.getMessage(), e); } finally { // writer soll auf jeden Fall geschlossen werden if (bufferedWriter != null) { bufferedWriter.close(); } } return result; }
8
public static <F,T> Adapter<F,T> getAdapter(Class<F> fromType, Class<T> toType) throws AdapterNotFoundException { if(fromType == null || toType == null) { throw getException(fromType, toType); } //If the types passed in are primitive, convert to wrapped types to find //the appropriate adapter fromType = getWrapper(fromType); toType = getWrapper(toType); if(fromType.equals(toType)) { return sSameTypeAdapter; } Adapter<F,T> adapter = (Adapter<F,T>)sAdapters.get( new ClassPair<F,T>(fromType, toType)); if(adapter == null) { //No adapter found...check some special cases //If either type is an enum then check for the generic enum case Class f = fromType.isEnum() ? Enum.class : fromType; Class t = toType.isEnum() ? Enum.class : toType; adapter = (Adapter<F,T>)sAdapters.get(new ClassPair<F,T>(f, t)); if(adapter == null) { throw getException(fromType, toType); } } return adapter; }
7
public static boolean isSkeletonWarriorDiamond ( SkeletonWarriorDiamond MMSkeletonWarriorDiamond) { if (MMSkeletonWarriorDiamond instanceof Skeleton) { Skeleton SkeletonWarriorDiamond = (Skeleton) MMSkeletonWarriorDiamond; if (SkeletonWarriorDiamond.getEquipment().getChestplate() .equals(new ItemStack(311))) { return true; } } return false; }
2
private void jComboBoxTipoClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTipoClienteActionPerformed try{ if(jComboBoxTipoCuenta.getSelectedIndex()==0 && jComboBoxTipoCliente.getSelectedIndex()==0){ tipoCuenta=1; tipoCliente=1; tablaCuentaAhorroClienteFisico(); }else{ if(jComboBoxTipoCuenta.getSelectedIndex()==0 && jComboBoxTipoCliente.getSelectedIndex()==1){ tipoCuenta=1; tipoCliente=2; tablaCuentaAhorroClienteJuridico(); }else{ if(jComboBoxTipoCuenta.getSelectedIndex()==1 && jComboBoxTipoCliente.getSelectedIndex()==0){ tipoCuenta=2; tipoCliente=1; tablaCuentaCorrienteClienteFisico(); }else{ tipoCuenta=2; tipoCliente=2; tablaCuentaCorrienteClienteJuridico(); } } } }catch (SQLException ex) { Logger.getLogger(ClienteConsulta.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jComboBoxTipoClienteActionPerformed
7
public void printIO(){ String s = "I:"; for(int i=0; i<inputNo; i++) s+=" "+inputNodes[i].getActivation(); s+="\nO:"; for(int i=0; i<outputNo; i++) s+=" "+outputNodes[i].getYAccuali()*scale; s+="\nH:"; for(int i=0; i<outputNo; i++){ s+=" "+outputNodes[i].getActivation()*scale; } System.out.print(s+"\n\n"); }
3
@Test public void testArrayOfArrays() throws Exception { PersistenceManager persist = new PersistenceManager(driver, database, login, password); persist.dropTable(Object.class); int arraySize = 5; ComplexObject co = new ComplexObject(); SimplestObject[][][] array = new SimplestObject[arraySize][arraySize][1]; for (int x = 0; x < array.length; x++) { for (int y = 0; y < array[x].length; y++) { array[x][y][0] = new SimplestObject(); } } co.setObject(array); co.setSimplestObject(new SimplestObject()); persist.saveObject(co); ComplexObject co2 = new ComplexObject(); SimplestObject[][][] array2 = new SimplestObject[1][][]; array2[0] = array[0]; co2.setObject(array2); persist.saveObject(co2); persist.close(); persist = new PersistenceManager(driver, database, login, password); List<ComplexObject> cos = persist.getObjects(new ComplexObject()); assertEquals(2, cos.size()); co = cos.get(0); co2 = cos.get(1); if(co.getSimplestObject()==null) { co = cos.get(1); co2 = cos.get(0); } SimplestObject[][][] resArray = (SimplestObject[][][]) co.getObject(); assertTrue(resArray != null); assertEquals(arraySize, resArray.length); assertEquals(arraySize, resArray[0].length); assertEquals(1, resArray[0][0].length); for (int x = 0; x < resArray.length; x++) { for (int y = 0; y < resArray[0].length; y++) { assertTrue(resArray[x][y][0] != null); } } SimplestObject[][][] resArray2 = (SimplestObject[][][]) co2.getObject(); assertTrue(resArray != resArray2); assertArrayEquals(resArray[0], resArray2[0]); persist.close(); }
5
public boolean isInArea(Location l) { double x = l.getX(); double y = l.getY(); double z = l.getZ(); return x > minPoint.x && x < maxPoint.x && z > minPoint.z && z < maxPoint.z && y > minPoint.y && y < maxPoint.y; }
5
private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed try { messageLabel.setText(""); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "oracle"); Statement s = con.createStatement(); String Name = name.getText(); String IATA = iata.getText(); if (Name.equals("Airline Name") || IATA.equals("IATA Code")) { messageLabel.setText("All fields are mandatory!"); con.close(); return; } ResultSet rs = s.executeQuery("select alname,al_iata from airline"); while (rs.next()) { if (rs.getString(1).equals(Name) || rs.getString(2).equals(IATA)) { messageLabel.setText("Airline already exists!"); con.close(); return; } } s.executeUpdate("insert into airline values(airline_id.nextval,'" + Name + "','" + IATA + "')"); iata.setText("IATA Code"); name.setText("Airline Name"); cancelButton.setVisible(true); javax.swing.JOptionPane.showMessageDialog(this, "Entered"); con.close(); } catch (SQLException se) { System.out.println(se); javax.swing.JOptionPane.showMessageDialog(this, "Airline name -max 40\nAirline IATA -max 2characters"); cancelButton.setVisible(true); } }//GEN-LAST:event_okActionPerformed
6
private static void combine(int a[], int low, int mid, int high){ int lowPointer = low; int highPointer = high; int [] lower = new int[mid-low+1]; int [] higher = new int[high - mid-1 +1]; System.out.println("High : " + high + " Mid : " + mid + " Low : " + low); int count = 0; for(int i =low ; i<= mid ; i++ ){ lower[count ++] = a[i] ; } count = 0; for(int i=mid+1; i <= high ; i++ ){ higher[count ++] = a[i]; } int i =0; int j =0; count = low; while(i < lower.length && j < higher.length){ if(lower[i] < higher[j] ){ a[count ++ ] = lower[i]; i++; }else{ a[count ++ ] = higher[j]; j++; } } if(i<lower.length){ for(int k = i ; k < lower.length ; k++){ a[count++] = lower[i++]; System.out.println(k); } } if(j<higher.length){ for(int k = j ; k < higher.length ; k++){ a[count++] = higher[j++]; System.out.println(k); } } System.out.println("hello"); }
9
private void destroyWall(EnvironmentWall wall, Line2D destroyedPart) { boolean originalWallUsed; double cellWidth, cellHeight, oldWallX2, oldWallY2, newWallX1, newWallY1, newWallX2, newWallY2; Vector2D wallDirection; EnvironmentWall newWall; wallDirection = wall.getWallDirection(); originalWallUsed = false; oldWallX2 = wall.x2; oldWallY2 = wall.y2; if(wall.x1 != destroyedPart.getX1() || wall.y1 != destroyedPart.getY1()) { //First part of the remaining wall (we update the wall coordinates) wall.x2 = destroyedPart.getX1() - wallDirection.getDirectionX(); wall.y2 = destroyedPart.getY1() - wallDirection.getDirectionY(); originalWallUsed = true; } if(oldWallX2 != destroyedPart.getX2() || oldWallY2 != destroyedPart.getY2()) { //Second part of the remaining wall if(!originalWallUsed) { //We can update the wall coordinates because the first part of the wall is completely destroyed wall.x1 = this.correctXCoordinate(destroyedPart.getX2() + 2 * wallDirection.getDirectionX()); wall.y1 = this.correctYCoordinate(destroyedPart.getY2() + 2 * wallDirection.getDirectionY()); } else { //We need to create a new wall and remove the old wall in cell's references cellWidth = this.configuration.getEnvironment().getCellWidth(); cellHeight = this.configuration.getEnvironment().getCellHeight(); newWallX1 = this.correctXCoordinate(destroyedPart.getX2() + 2 * wallDirection.getDirectionX()); newWallY1 = this.correctYCoordinate(destroyedPart.getY2() + 2 * wallDirection.getDirectionY()); newWallX2 = oldWallX2; newWallY2 = oldWallY2; newWall = new EnvironmentWall(newWallX1, newWallY1, newWallX2, newWallY2, true); this.walls.add(newWall); for(Cell cell: GeometryUtils.getGridCellsCrossedByLine(newWall, cellWidth, cellHeight)) { this.environment[cell.getRow()][cell.getColumn()].remove(wall); this.environment[cell.getRow()][cell.getColumn()].add(newWall); } } } else if(!originalWallUsed) { //The wall is completely removed this.walls.remove(wall); } }
7
public boolean shouldTurnOn(int x, int y) { for (ShapeWithRelativeCoordinates component : shapes) { int relativeX = x - component.topX; int relativeY = y - component.topY; if (component.shape instanceof Circle) { if (((Circle) component.shape).isPixelActivated(relativeX, relativeY)) return true; } if (component.shape instanceof Rectangle) { if (((Rectangle) component.shape).isPixelOn(relativeX, relativeY)) return true; } if (component.shape instanceof CompositeShape) { if (((CompositeShape) component.shape).shouldTurnOn(relativeX, relativeY)) return true; } } return false; }
7
public void writeWord(int word) throws IOException { if((word & 0xffff) != word) { throw new IllegalArgumentException("Argument is not a 16 bit word: "+word); } if(littleEndian) { out.write(word & 0x00ff); out.write((word & 0xff00) >> 8); } else { out.write((word & 0xff00) >> 8); out.write(word & 0x00ff); } wordsWritten++; }
2
public Trivia() { System.out.println("> loading challenges..."); easyTrivia = new ArrayList<Challenge>(); mediumTrivia = new ArrayList<Challenge>(); hardTrivia = new ArrayList<Challenge>(); gameChallenges = new ArrayList<Challenge>(); randy = new Random(); // read in each file, every odd line is a question, even lines are corresponding answers try { // easy trivia Scanner read = new Scanner(new File("chal/easy_trivia.txt")); while (read.hasNextLine()) { String q = read.nextLine(); if (!read.hasNextLine()) break; String a = read.nextLine(); easyTrivia.add(new Challenge(q, a, "<html><center>EASY TRIVIA<br>1 POINT</center></html>")); } System.out.println(">> " + easyTrivia.size() + " easy trivia loaded"); // medium trivia read = new Scanner(new File("chal/medium_trivia.txt")); while (read.hasNextLine()) { String q = read.nextLine(); if (!read.hasNextLine()) break; String a = read.nextLine(); mediumTrivia.add(new Challenge(q, a, "<html><center>MEDIUM TRIVIA<br>2 POINTS</center></html>")); } System.out.println(">> " + mediumTrivia.size() + " medium trivia loaded"); // hard trivia read = new Scanner(new File("chal/hard_trivia.txt")); while (read.hasNextLine()) { String q = read.nextLine(); if (!read.hasNextLine()) break; String a = read.nextLine(); hardTrivia.add(new Challenge(q, a, "<html><center>HARD TRIVIA<br>3 POINTS</center></html>")); } System.out.println(">> " + hardTrivia.size() + " hard trivia loaded"); // game challenges read = new Scanner(new File("chal/game_challenges.txt")); while (read.hasNextLine()) { String q = read.nextLine(); gameChallenges.add(new Challenge(q, "Game Challenge", "<html><center>GAME CHALLENGE<br>4 POINTS</center></html>")); } System.out.println(">> " + gameChallenges.size() + " game challenges loaded"); read.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
8
private Object binarySearchNames(int firstIndex, int lastIndex, String name) { if (firstIndex > lastIndex) return NOT_FOUND; int pivot = firstIndex + ((lastIndex - firstIndex) / 2); pivot &= 0xFFFFFFFE; // Clear LSB to ensure even index //System.out.print("binarySearchNames [ " + firstIndex + ", " + lastIndex + " ] pivot: " + pivot + " size: " + namesAndValues.size() + " compare " + name + " to " + namesAndValues.get(pivot).toString() + " ... "); int cmp = namesAndValues.get(pivot).toString().compareTo(name); if (cmp == 0) { //System.out.println("nEQUAL"); Object ob = namesAndValues.get(pivot + 1); if (ob instanceof Reference) ob = library.getObject((Reference) ob); return ob; } else if (cmp > 0) { //System.out.println("nLESSER"); return binarySearchNames(firstIndex, pivot - 1, name); } else if (cmp < 0) { //System.out.println("nGREATER"); return binarySearchNames(pivot + 2, lastIndex, name); } return NOT_FOUND; }
5
public Contact(String firstName, String lastName, PhoneNumber... phoneNumbers) { super(NextIdGenerator.getNextId(Contact.class)); this.firstName = firstName; this.lastName = lastName; this.phoneNumbers = hasPhoneNumbers(phoneNumbers) ? null : Lists.newArrayList(Arrays.asList(phoneNumbers)); ensureRequiredFieldsAreProvided(getMandatoryFields()); }
1
private String[] getCaps(final Plugin plugin) { final Class<? extends Plugin> spawnClass = plugin.getClass(); final Method[] methods = spawnClass.getMethods(); // Search for proper method for (final Method method : methods) { // Init methods will be marked by the corresponding annotation. final Capabilities caps = method.getAnnotation(Capabilities.class); if (caps != null) { Object result = null; try { result = method.invoke(plugin, new Object[0]); } catch (final IllegalArgumentException e) { // } catch (final IllegalAccessException e) { // } catch (final InvocationTargetException e) { // } if (result != null && result instanceof String[]) return (String[]) result; } } return new String[0]; }
8
public void render(Screen screen) { Entity.sortMobsList(); for(int i = 0; i < Entity.getMobSize(); i++) { if(!(Entity.getIndexedMob(i).getIsOnStage()) && Entity.getIndexedMob(i).getYCoord() < SpriteSheets.mainStage.getYSheetSize() / 2) { Entity.getIndexedMob(i).render(screen); } } screen.renderLevel(); for(int i = 0; i < Entity.getMobSize(); i++) { if(Entity.getIndexedMob(i).getIsOnStage() || !(Entity.getIndexedMob(i).getIsOnStage()) && Entity.getIndexedMob(i).getYCoord() > SpriteSheets.mainStage.getYSheetSize() / 2) { Entity.getIndexedMob(i).render(screen); } } for(int i = 0; i < Entity.getProjectilesSize(); i++) { Entity.getIndexedProjectile(i).render(screen); } for(int i = 0; i < Entity.getParticleSize(); i++) { Entity.getIndexedParticle(i).render(screen); } }
9
private void loadWordList( DefaultListModel data ){ UserDictionaryProvider provider = SpellChecker.getUserDictionaryProvider(); if( provider != null ) { Iterator<String> userWords = provider.getWords( SpellChecker.getCurrentLocale() ); if( userWords != null ) { ArrayList<String> wordList = new ArrayList<String>(); while(userWords.hasNext()){ String word = userWords.next(); if( word != null && word.length() > 1 ) { wordList.add( word ); } } // Liste alphabetical sorting with the user language Collections.sort( wordList, Collator.getInstance() ); for(String str : wordList){ data.addElement( str ); } } } }
6
public void setTimestamp(Long timestamp) { this.timestamp = timestamp; }
0
private Method findMethodByPrefix(Class<?> sourceClass, String prefix, String postfix) { String shortName = listenerType.getName(); if (listenerType.getPackage() != null) { shortName = shortName.substring(listenerType.getPackage().getName() .length() + 1); } String methodName = prefix + shortName + postfix; try { if ("get".equals(prefix)) { //$NON-NLS-1$ return sourceClass.getMethod(methodName); } } catch (NoSuchMethodException nsme) { return null; } Method[] methods = sourceClass.getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(methodName)) { Class<?>[] paramTypes = methods[i].getParameterTypes(); if (paramTypes.length == 1) { return methods[i]; } } } return null; }
8
public final boolean method66(int i, Interface18 interface18) { anInt5438++; if (!(interface18 instanceof Class296)) { return false; } Class296 class296_3_ = (Class296) interface18; if (anInt5431 != class296_3_.anInt5431) { return false; } if (class296_3_.anInt5432 != anInt5432) { return false; } if ((anInt5427 ^ 0xffffffff) != (class296_3_.anInt5427 ^ 0xffffffff)) { return false; } if ((class296_3_.anInt5433 ^ 0xffffffff) != (anInt5433 ^ 0xffffffff)) { return false; } if (anInt5435 != class296_3_.anInt5435) { return false; } if ((anInt5434 ^ 0xffffffff) != (class296_3_.anInt5434 ^ 0xffffffff)) { return false; } if (i != 28071) { anInt5431 = 7; } if (!class296_3_.aBoolean5440 == aBoolean5440) { return false; } return true; }
9
public void processBet(PackReplyOldBetHop message) { // faz o cal. do Sbet // faz a adicao do par <chave, valor> // chave = num de caminhos, valor = numero de nodos // descendentes com 'aquela' quantidade de caminho if(sonsPathMap.containsKey(message.getPath())){ sonsPathMap.put(message.getPath(), sonsPathMap.get(message.getPath()) + 1); }else{ sonsPathMap.put(message.getPath(), 1); } double tmp = 0.0; for(Entry<Integer, Integer> e : sonsPathMap.entrySet()) // faz o calculo do Sbet tmp = tmp + (e.getValue() * ((double) this.pathsToSink / e.getKey())); setsBet(tmp); }
2
public void attPrepEnd(){ battle.setState(Battle.BATTLE_SUPPORT_PHASE); //we check if the player can add an influence token if (territory1.getTroup().getEffectif()>0 || territory1.getInfluenceToken() || (territory1 instanceof HomeLand && ((HomeLand) territory1).originalOwner(territory1.getFamily()))){ if(battle.checkSupport()){//in case there is no support available, start the battle directly battle.startBattle(); } state=ModelState.BATTLE; }else{//the player have the possiblity to use a influence befor the begin of the battle state=ModelState.USE_INF_TOKEN; } updateLabel(); }
5
public int sandinate(int X, int Y, int R) { int toReturn = 0; // long time = System.nanoTime(); for (int i1 = Math.max(X-(R+1),0); i1 < Math.min(X+(R+1),w); i1 ++) { for (int i2 = Math.max(Y-(R+1),0); i2 < Math.min(Y+(R+1),h); i2 ++) { if (Math.round(Math.sqrt(Math.pow(i1-X,2)+Math.pow(i2-Y,2))) < (R/2)+.1&&cellData[i1][i2]==SAND) { cellData[i1][i2]=AIR; toReturn++; } } } return toReturn; }
4
@Override public SondageReponse find(int id) { SondageReponse found = null; PreparedStatement pst = null; ResultSet rs = null; try { pst=this.connect().prepareStatement("select * from SondageReponse where id= ?"); pst.setInt(1, id); rs=pst.executeQuery(); System.out.println("recherche individuelle réussie"); if (rs.next()) { found = new SondageReponse(rs.getInt("id"), rs.getInt("id_sondage"), rs.getInt("choix"), rs.getInt("nombreChoix")); } } catch (SQLException ex) { Logger.getLogger(SondageDao.class.getName()).log(Level.SEVERE, "recherche individuelle echoué", ex); }finally{ try { if (rs != null) rs.close(); } catch (SQLException ex) { Logger.getLogger(SondageDao.class.getName()).log(Level.SEVERE, "liberation result set echoué", ex); } try { if (pst != null) pst.close(); } catch (SQLException ex) { Logger.getLogger(SondageDao.class.getName()).log(Level.SEVERE, "liberation prepared statement echoué", ex); } } return found; }
6
public Period(int year, int month) { this.year = year; this.month = month; this.locations = new ArrayList<DataPoint>(); }
0
private void acquiereLock(Lock fistLock, Lock seconlock) throws InterruptedException { boolean gotFirstLock = false; boolean gotSecondLock = false; while (true) { try { gotFirstLock = fistLock.tryLock(); gotSecondLock = seconlock.tryLock(); } finally { if (gotFirstLock && gotSecondLock) { return; } if (gotFirstLock) { fistLock.unlock(); } if (gotSecondLock) { seconlock.unlock(); } } Thread.sleep(1); } }
5
private void receive() { receiver = new Thread() { @Override public void run() { while (true) { try { byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, data.length); datagramSocket.receive(packet); analyse(packet); } catch (Exception e) { e.printStackTrace(); } } } }; receiver.start(); }
2
public void LueTiedotTiedostosta(){ String menossaMappiin = ""; try { menossaMappiin = kasittelija.lueTiedostoSanaKerrallaan(); } catch (NullPointerException e){ System.out.println("Nyt tapahtui jotain kummallista ja tiedostoa ei löydy"); //tähän jotain fiksua joskus } String luettu = kasittelija.lueTiedostoSanaKerrallaan(); while (!luettu.equals("TIEDOSTON LOPPU")){ try { int arvo = Integer.parseInt(luettu); opiskelut.put(menossaMappiin, arvo); } catch (Exception e){ menossaMappiin = luettu; } luettu = kasittelija.lueTiedostoSanaKerrallaan(); } }
3
public static void main(String[] args) { // default values int portNumber = 1500; String serverAddress = "localhost"; String userName = "Anonymous"; // depending of the number of arguments provided we fall through switch(args.length) { // > javac Client username portNumber serverAddr case 3: serverAddress = args[2]; // > javac Client username portNumber case 2: try { portNumber = Integer.parseInt(args[1]); } catch(Exception e) { System.out.println("Invalid port number."); System.out.println("Usage is: > java Client [username] [portNumber] [serverAddress]"); return; } // > javac Client username case 1: userName = args[0]; // > java Client case 0: break; // invalid number of arguments default: System.out.println("Usage is: > java Client [username] [portNumber] {serverAddress]"); return; } // create the Client object Client client = new Client(serverAddress, portNumber, userName); // test if we can start the connection to the Server // if it failed nothing we can do if(!client.start()) return; // wait for messages from user Scanner scan = new Scanner(System.in); // loop forever for message from the user while(true) { System.out.print("> "); // read message from user String msg = scan.nextLine(); // logout if message is LOGOUT if(msg.equalsIgnoreCase("LOGOUT")) { client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, "")); // break to do the disconnect break; } // message WhoIsIn else if(msg.equalsIgnoreCase("WHOISIN")) { client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, "")); } else { // default to ordinary message client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, msg)); } } // done disconnect client.disconnect(); }
9
private void jbtnClose_ActionPerformed() { if (this.socket != null && ! this.socket.isClosed()) { try { this.socket.close(); } catch(Exception e) { EzimMain.showError(e.getMessage()); EzimLogger.getInstance().warning(e.getMessage(), e); } } this.saveConf(); this.unregDispose(); }
3
private void handleKeyPress(final int key) { switch (key) { case KeyEvent.VK_LEFT: player.setDirection(Player.Directions.WEST); break; case KeyEvent.VK_UP: player.setDirection(Player.Directions.NORTH); break; case KeyEvent.VK_RIGHT: player.setDirection(Player.Directions.EAST); break; case KeyEvent.VK_DOWN: player.setDirection(Player.Directions.SOUTH); break; case KeyEvent.VK_SPACE: Bullet bullet; switch (player.getPlayerBullet()){ case SINGLE: bullet = new Bullet(SINGLE_BULLET_TILE, player.getPos(), 1); break; case DOUBLE: bullet = new Bullet(DOUBLE_BULLET_TILE, player.getPos(), 2); break; case TRIPLE: bullet = new Bullet(TRIPLE_BULLET_TILE, player.getPos(), 3); break; default: bullet = new Bullet(SINGLE_BULLET_TILE, player.getPos(), 1); break; } setGameboardState(bullet.getPos().getX(), bullet.getPos().getY(), bullet.getTile()); break; default: // Don't change direction if another key is pressed break; } }
8
public static void generateCaseRuleWoSlot(Vector cases, Symbol className, Symbol slotName) { { int numCases = cases.length(); Surrogate kind = Logic.getDescription(className).surrogateValueInverse; List caseNames = List.newList(); Surrogate slot = Logic.getDescription(slotName).surrogateValueInverse; Vector slotValues = Vector.newVector(numCases); Logic.clearCases(); { LogicObject renamed_Case = null; Vector vector000 = cases; int index000 = 0; int length000 = vector000.length(); Cons collect000 = null; for (;index000 < length000; index000 = index000 + 1) { renamed_Case = ((LogicObject)((vector000.theArray)[index000])); if (collect000 == null) { { collect000 = Cons.cons(Logic.objectName(renamed_Case), Stella.NIL); if (caseNames.theConsList == Stella.NIL) { caseNames.theConsList = collect000; } else { Cons.addConsToEndOfConsList(caseNames.theConsList, collect000); } } } else { { collect000.rest = Cons.cons(Logic.objectName(renamed_Case), Stella.NIL); collect000 = collect000.rest; } } } } { LogicObject renamed_Case = null; Vector vector001 = cases; int index001 = 0; int length001 = vector001.length(); Symbol caseName = null; Cons iter000 = caseNames.theConsList; int i = Stella.NULL_INTEGER; int iter001 = 0; for (;(index001 < length001) && (!(iter000 == Stella.NIL)); index001 = index001 + 1, iter000 = iter000.rest, iter001 = iter001 + 1) { renamed_Case = ((LogicObject)((vector001.theArray)[index001])); caseName = ((Symbol)(iter000.value)); i = iter001; { Stella_Object val = LogicObject.getSlotValue(renamed_Case, slot); (slotValues.theArray)[i] = val; Logic.smartUpdateProposition(Cons.cons(slotName, Cons.cons(caseName, Cons.cons(val, Stella.NIL))), Logic.KWD_RETRACT_TRUE); } } } { OutputFileStream fptr = OutputFileStream.newOutputFileStream("current-cases.ste"); fptr.nativeStream.println("(in-package \"STELLA\")"); { int i = Stella.NULL_INTEGER; int iter002 = 0; int upperBound000 = numCases - 1; Symbol caseName = null; Cons iter003 = caseNames.theConsList; for (;(iter002 <= upperBound000) && (!(iter003 == Stella.NIL)); iter002 = iter002 + 1, iter003 = iter003.rest) { i = iter002; caseName = ((Symbol)(iter003.value)); LogicObject.buildCaseFromInstance(((LogicObject)((cases.theArray)[i])), kind); fptr.nativeStream.println("(add-case " + caseName + ")"); } } } Logic.buildCaseRule(kind); { Stella_Object val = null; Vector vector002 = slotValues; int index002 = 0; int length002 = vector002.length(); Symbol caseName = null; Cons iter004 = caseNames.theConsList; for (;(index002 < length002) && (!(iter004 == Stella.NIL)); index002 = index002 + 1, iter004 = iter004.rest) { val = (vector002.theArray)[index002]; caseName = ((Symbol)(iter004.value)); Logic.smartUpdateProposition(Cons.cons(slotName, Cons.cons(caseName, Cons.cons(val, Stella.NIL))), Logic.KWD_ASSERT_TRUE); } } } }
9
public synchronized boolean commitReservation(ReservationMessage message) { int resId = message.getReservationID(); ServerReservation sRes = null; String msg = "Reservation # " + resId + " cannot be committed because it "; // Tries to find the reservation in the lists if(reservTable.containsKey(resId)) { sRes = reservTable.get(resId); } else if(expiryTable.containsKey(resId)) { sRes = expiryTable.get(resId); if(sRes.getReservationStatus() == ReservationStatus.CANCELLED) { logger.info(msg + "has previously been cancelled by the allocation policy."); } else if (sRes.getReservationStatus() == ReservationStatus.FINISHED) { logger.info(msg + "has finished."); } else { logger.info(msg + "is in the expiry list."); } return false; } else { logger.info(msg + "could not be found."); return false; } // sets the reservation to committed if it has not been set before if(sRes.getReservationStatus() == ReservationStatus.NOT_COMMITTED) { sRes.setStatus(ReservationStatus.COMMITTED); // then send this into itself to start the reservation super.sendInternalEvent(sRes.getStartTime() - GridSim.clock(), ConservativeBackfill.UPT_SCHEDULE); } //-------------- FOR DEBUGGING PURPOSES ONLY -------------- visualizer.notifyListeners(this.get_id(), ActionType.ITEM_STATUS_CHANGED, true, sRes); //---------------------------------------------------------- return true; }
5
public Card.Suit chooseSuit(Deck deck, Card.Suit prevSuit, PlayerHuman playerHuman) { boolean shouldAvoid = false; for (Card i : playerHuman.lastCards) { if (playerHuman.cards.size() == 1 && i != null && i.num() == 1) shouldAvoid = true; } if (! shouldAvoid) return Agonia.findDominantSuit(cards); CardArray tempCards = new CardArray(); for (Card i : cards) if (! (i.suit() == prevSuit)) tempCards.add(i); return Agonia.findDominantSuit(tempCards); }
7
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just rained hell fire!"); return random.nextInt((int) agility) * 2; } return 0; }
1
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Ship other = (Ship) obj; // just use the type so that you can have only one type // in a hash set if (this.type != other.type) { return false; } // if (this.orientation != other.orientation) { // return false; // } // if (!Objects.equals(this.startPoint, other.startPoint)) { // return false; // } return true; }
3
public void dispose() { colorManager.dispose(); super.dispose(); }
0
@Override public void onUpdate(World apples) { if (radius>=maxradius) { alive = false; } switch (apples.random.nextInt(5)) { default: case 0: c = Color.red; break; case 1: c = Color.orange; break; case 2: c = Color.yellow; break; case 3: c = new Color(252,111,16); break; case 4: c = new Color(242,0,0); break; } c = new Color(c.getRed(),c.getGreen(),c.getBlue(),(radius/(maxradius>0?maxradius:1))*255); radius+=speed; }
7
private void LoadDocuments(String str, String filepath) throws IOException { str = str.replace("\n", " "); str = str.replace("\r", " "); String[] docs = str.split("</DOC>"); for (int i = 0; i < docs.length; i++) { String s = docs[i].trim(); if (s.length() > 0) { try { Document d = new Document(); d.FileName = filepath; d.DataCreazione = extractDateParse(s, "DD"); if (d.DataCreazione == null) { WriteError(ErrorCode.TagNotFound_DD); d.DataCreazione = extractDateParse(s, "DATE"); if (d.DataCreazione == null) { throw new ParseException("", 0); } } d.Id = extract(s, "DOCNO"); d.TestoOriginale = extract(s, "TEXT"); if (d.TestoOriginale == "") { d.TestoOriginale = extract(s, "LP"); } this.documents.add(d); } catch(ParseException ex) { WriteError(ErrorCode.TagNotFound_DATE, filepath); } catch(Exception ex) { WriteError(ErrorCode.Undefined); } } } }
7
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { //first goal is to be able to receive and process //a well formatted XML moveTwo piggybacked on a POST //this gives me a raw stream to payload of Post request Scanner in = new Scanner(req.getInputStream()); StringBuffer input = new StringBuffer(); //peel off XML message a line at a time while (in.hasNext()) input.append(in.next()); //convert to String for convenience String inputAsString = input.toString(); //parse the XML and marshal the java Move_Two object Move_Two moveTwo = processInput(inputAsString); //now create the response PrintWriter out = res.getWriter(); //at this pont we want to return an XML document //that represents the moveTwo "response" to one or both //clients /* <moveResponse> <status>confimed</status> <mover> player ID here </mover> <loc> loc value here </loc> </moveResponse> */ //A good first test is to just veryify that you can //successfully send back any XML string. From there //building up simple response is trivial and can be //done at the level of String building or, if you prefer, //DOM objects converted to Strings //test xml just to show that we can do it. //no significance to this moveTwo definition. just mechanics. out.println("<moveTwo> <location>" + "hello" + "</location> </moveTwo>"); out.flush(); out.close(); }
1
private void sendeAenderungenAnAlle() throws RemoteException { ArrayList<ClientPaket> paketListe = new ArrayList<ClientPaket>(); for(String name : _connectedClients.keySet()) { paketListe.add(_spiel.packePaket(name)); } for(ClientPaket paket : paketListe) { ClientInterface client = _connectedClients.get(paket .getSpielerName()); if(client != null) client.zeigeAn(paket); } }
3
public String searchByName(final String name) throws IOException { if (!notebookCache.containsKey(name)) { return null; } return notebookCache.get(name).toString(); }
1
private boolean method320(int i, int j, int k) { int l = anIntArrayArrayArray445[i][j][k]; if(l == -anInt448) return false; if(l == anInt448) return true; int i1 = j << 7; int j1 = k << 7; if(method324(i1 + 1, anIntArrayArrayArray440[i][j][k], j1 + 1) && method324((i1 + 128) - 1, anIntArrayArrayArray440[i][j + 1][k], j1 + 1) && method324((i1 + 128) - 1, anIntArrayArrayArray440[i][j + 1][k + 1], (j1 + 128) - 1) && method324(i1 + 1, anIntArrayArrayArray440[i][j][k + 1], (j1 + 128) - 1)) { anIntArrayArrayArray445[i][j][k] = anInt448; return true; } else { anIntArrayArrayArray445[i][j][k] = -anInt448; return false; } }
6
public static void startLoadingDataBase() { Thread loadDB = new Thread(new Runnable() { @Override public void run() { if (!Database.loaded) EarningsTest.db = new Database( EarningsTest.PATH_SOURCE.getText()); JComponentFactory.addReportsTab(); } }); loadDB.start(); }
1
private static XMPNode followXPathStep( XMPNode parentNode, XMPPathSegment nextStep, boolean createNodes) throws XMPException { XMPNode nextNode = null; int index = 0; int stepKind = nextStep.getKind(); if (stepKind == XMPPath.STRUCT_FIELD_STEP) { nextNode = findChildNode(parentNode, nextStep.getName(), createNodes); } else if (stepKind == XMPPath.QUALIFIER_STEP) { nextNode = findQualifierNode( parentNode, nextStep.getName().substring(1), createNodes); } else { // This is an array indexing step. First get the index, then get the node. if (!parentNode.getOptions().isArray()) { throw new XMPException("Indexing applied to non-array", XMPError.BADXPATH); } if (stepKind == XMPPath.ARRAY_INDEX_STEP) { index = findIndexedItem(parentNode, nextStep.getName(), createNodes); } else if (stepKind == XMPPath.ARRAY_LAST_STEP) { index = parentNode.getChildrenLength(); } else if (stepKind == XMPPath.FIELD_SELECTOR_STEP) { String[] result = Utils.splitNameAndValue(nextStep.getName()); String fieldName = result[0]; String fieldValue = result[1]; index = lookupFieldSelector(parentNode, fieldName, fieldValue); } else if (stepKind == XMPPath.QUAL_SELECTOR_STEP) { String[] result = Utils.splitNameAndValue(nextStep.getName()); String qualName = result[0]; String qualValue = result[1]; index = lookupQualSelector( parentNode, qualName, qualValue, nextStep.getAliasForm()); } else { throw new XMPException("Unknown array indexing step in FollowXPathStep", XMPError.INTERNALFAILURE); } if (1 <= index && index <= parentNode.getChildrenLength()) { nextNode = parentNode.getChild(index); } } return nextNode; }
9
public String getCp() { return cp; }
0
public synchronized void handleEachAndClassAbility(Map<String, AbilityMapping> ableMap, Map<String,Map<String,AbilityMapping>> allQualMap, String ID) { if(eachClassSet == null) { eachClassSet = new SLinkedList<AbilityMapping>(); final Map<String,AbilityMapping> eachMap=allQualMap.get("EACH"); final Map<String,AbilityMapping> allAllMap=allQualMap.get("ALL"); for(final AbilityMapping mapped : eachMap.values()) { if(CMSecurity.isAbilityDisabled(mapped.abilityID().toUpperCase())) continue; final AbilityMapping able = mapped.copyOf(); eachClassSet.add(able); } for(final AbilityMapping mapped : allAllMap.values()) { if(CMSecurity.isAbilityDisabled(mapped.abilityID().toUpperCase())) continue; final AbilityMapping able = mapped.copyOf(); able.ID("All"); Map<String, AbilityMapping> allMap=completeAbleMap.get("All"); if(allMap == null) { allMap=new SHashtable<String,AbilityMapping>(); completeAbleMap.put("All",allMap); } able.allQualifyFlag(true); mapAbilityFinal(able.abilityID(), allMap, able); } } for (final AbilityMapping abilityMapping : eachClassSet) { final AbilityMapping able=abilityMapping.copyOf(); able.ID(ID); able.allQualifyFlag(true); mapAbilityFinal(able.abilityID(), ableMap, able); } }
7
void moveinterpret (String s, boolean fromhere) { StringParser p = new StringParser(s); String c = p.parseword(); int p1 = p.parseint(); int p2 = p.parseint(); int p3 = p.parseint(); int p4 = p.parseint(); int p5 = p.parseint(); int p6 = p.parseint(); if (c.equals("board")) { PGF = new PartnerGoFrame(this, Global .resourceString("Partner_Game"), fromhere?p1: -p1, p2, p3 * 60, p4 * 60, p5, p6); PGF.setHandicap(); } else if (PGF != null && c.equals("b")) { PGF.black(p1, p2); PGF.settimes(p3, p4, p5, p6); } else if (PGF != null && c.equals("w")) { PGF.white(p1, p2); PGF.settimes(p3, p4, p5, p6); } else if (PGF != null && c.equals("pass")) { PGF.pass(); PGF.settimes(p1, p2, p3, p4); } Moves .append(new ListElement(new PartnerMove(c, p1, p2, p3, p4, p5, p6))); }
8
public static void smoosh(int[] ints) { // Fill in your solution here. (Ours is fourteen lines long, not counting // blank lines or lines already present in this file.) int inputlen=0; if(ints!=null) inputlen=ints.length; int i; for(i=(inputlen-1);i>0;i--){ if(ints[i]==ints[i-1]){ ints[i-1]=ints[i]; ints[i]=-1; } } //Arrays.sort(ints); // for(int j=0;i<(inputlen-1)/2;i++){ // ints[j]=ints[inputlen-j]; // } }
3
@Override public void execute(HttpServletRequest request, HttpServletResponse response) { String xmlPath = ResourceManager.INSTANCE .getPropertyRealPath("xml_path"); String categoriesXsltPath = ResourceManager.INSTANCE .getPropertyRealPath("categories_xslt"); String subcategoriesXsltPath = ResourceManager.INSTANCE .getPropertyRealPath("subcategories_xslt"); String goodsXsltPath = ResourceManager.INSTANCE .getPropertyRealPath("goods_xslt"); String pageName = request.getParameter(AttributeHandler.PAGE); String productSubcategory = null; String productCategory = null; String requestedXSLTFilename = categoriesXsltPath; switch (pageName) { case AttributeHandler.CATEGORIES: requestedXSLTFilename = categoriesXsltPath; break; case AttributeHandler.SUBCATEGORIES: productCategory = request .getParameter(AttributeHandler.PRODUCT_CATEGORY); productSubcategory = request .getParameter(AttributeHandler.PRODUCT_SUBCATEGORY); requestedXSLTFilename = subcategoriesXsltPath; break; case AttributeHandler.GOODS: requestedXSLTFilename = goodsXsltPath; productCategory = request .getParameter(AttributeHandler.PRODUCT_CATEGORY); productSubcategory = request .getParameter(AttributeHandler.PRODUCT_SUBCATEGORY); break; } try { // Generate the transformer. Transformer transformer = StylesheetCache .newTransformer(requestedXSLTFilename); if (productSubcategory != null && productCategory != null) { transformer.setParameter(AttributeHandler.PRODUCT_CATEGORY, productCategory); transformer.setParameter(AttributeHandler.PRODUCT_SUBCATEGORY, productSubcategory); } // Perform the transformation, sending the output to the response. lock.readLock().lock(); try (PrintWriter out = response.getWriter();) { Source xmlSource = new StreamSource( new URL("file", "", xmlPath).openStream()); transformer.transform(xmlSource, new StreamResult(out)); } finally { lock.readLock().unlock(); } } catch (TransformerException e) { logger.error( "Error in executing show back command during transformation", e); } catch (IOException e) { logger.error( "Error in executing show back command during stream creation", e); } }
7
@Override public void run() { if (isFiltered) { return; } StringBuilder builder = new StringBuilder(); builder.append(visitTime); if (status == 200) { builder.append(",").append("ok"); builder.append(",").append(requestUrl); builder.append(",").append(requestMethod); builder.append(",").append(requestBytes); builder.append(",").append(requestPureHeaderBytes); builder.append(",").append(requestValidBytes); builder.append(",").append(responseBytes); builder.append(",").append(responseValidBytes); builder.append(",").append(requestBytes + responseBytes); builder.append(",").append(responseTimeMills); } else { builder.append(",").append("failed"); if (requestUrl != null && requestUrl.length() > 0) { builder.append(",").append(requestUrl); } else { builder.append(","); } if (requestMethod != null && requestMethod.length() > 0) { builder.append(",").append(requestMethod); } else { builder.append(","); } builder.append(",").append(",").append(",").append(",").append(",").append(",").append(","); if (failMsg != null) { builder.append(",").append(failMsg); } else { builder.append(",").append(status); } } log.info(builder); }
7
public void usingKeySetAndIterator(Map<Integer, String> map){ Iterator<Integer> itr = map.keySet().iterator(); while(itr.hasNext()){ Integer intgr = itr.next(); System.out.println("Key: "+intgr); } }
1
public static ArrayList<Planet> forPlanet(PlanetWars pw){ // Tested ArrayList<Planet> asw = new ArrayList<Planet>(2); asw.add(null); asw.add(null); // Find the biggest fleet to attack with int maxShips = 0; for (Planet p : pw.MyPlanets()){ if (p.NumShips() > maxShips){ maxShips = p.NumShips(); asw.add(0,p); } } // Find the destination with best distance to be captured (distance help to be sure to capture the planet on neutral ones) int maxDist = 0; try { for (Planet p : pw.NotMyPlanets()){ int dist = (int) Helper.distance(asw.get(0),p); if (dist > maxDist && Helper.WillCapture(asw.get(0),p)) { maxDist = dist; asw.add(1,p); } } } catch (Exception e){ System.out.println(e); } return asw; }
6
public boolean setSpeed(double vX, double vY) { if (Buffer.findSprite(this) != null) { Buffer.findSprite(this).setSpeed(vX, vY); return true; } else { return false; } }
1
public void run() { if(isMaster) { //wait for all participants, then initialize all files loadConfig(); System.out.println("Waiting on all participants..."); int participants = Integer.parseInt(filesystem_config.get("participants")); while (cServer.connections.size() < participants) { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.println("All participants connected, initializing file system"); int rep = Integer.parseInt(filesystem_config.get("replication_factor")); try { splitUpFiles(rep,filenames); } catch (IOException e) { System.out.println("Could not split up files"); System.exit(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
5
public static void main(String args[]) { List_Homework_database MList = new List_Homework_database(); /* 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(add_new_user.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(add_new_user.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(add_new_user.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(add_new_user.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 add_new_user().setVisible(true); } }); }
6
public int evalRPN(String[] tokens) { Stack<Integer> ops = new Stack<>(); int eval = 0, op1 = 0, op2 = 0; for(String token : tokens) { if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) { op2 = ops.pop(); op1 = ops.pop(); switch(token) { case "+": eval = op1 + op2; break; case "-": eval = op1 - op2; break; case "*": eval = op1 * op2; break; case "/": eval = op1 / op2; break; } ops.push(eval); } else { ops.push(Integer.valueOf(token)); } } return ops.pop(); }
9
public static void Command(CommandSender sender, String[] args) { if(sender.hasPermission("gm.creative.others")) { Player target = Bukkit.getPlayer(args[1]); if(target != null) { if (target.getGameMode() != GameMode.CREATIVE) { target.setGameMode(GameMode.CREATIVE); if(sender instanceof Player) { me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, (Player) sender, target, true, false, false, null); me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, (Player) sender, target, false, true, false, null); } else { me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, null, target, true, false, false, null); me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, null, target, false, true, false, null); } } else { if(sender instanceof Player) me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, (Player) sender, target, true, false, false, null); else me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, null, target, true, false, false, null); } } else { if(sender instanceof Player) me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Error 404: Player Not Found").toString(), sender, (Player) sender, null, true, false, false, args[0]); else me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Error 404: Player Not Found").toString(), sender, null, null, true, false, false, args[0]); } } else { if(sender instanceof Player) me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, (Player) sender, null, true, false, false, null); else me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, null, null, true, false, false, null); } }
7
public void createChart() { pieChartModel=new PieChartModel(); setPriority("emerg"); Long emerg= getFacilityCount(); if(emerg!=0) pieChartModel.set("Emergency", emerg); setPriority("Alert"); Long alert= getFacilityCount(); if(alert!=0) pieChartModel.set("Alert",alert); setPriority("crit"); Long crit= getFacilityCount(); if(crit!=0) pieChartModel.set("Critical", crit); setPriority("err"); Long err= getFacilityCount(); if(err!=0) pieChartModel.set("error",err); setPriority("warning"); Long warning= getFacilityCount(); if(warning!=0) pieChartModel.set("Warning",warning); setPriority("notice"); Long notice= getFacilityCount(); if(notice!=0) pieChartModel.set("Notice",notice); setPriority("info"); Long info= getFacilityCount(); if(info!=0) pieChartModel.set("Information",info); setPriority("debug"); Long debug= getFacilityCount(); if(debug!=0) pieChartModel.set("Debug",debug); }
8
@BeforeClass public static void init() { snzipExecutable = TestUtil.findSnzipExecutable(); if(snzipExecutable == null) { throw new IllegalStateException("No executable snzip file found in bin directory"); } testdataDirectory = TestUtil.directoriesToFile("resources", "testdata"); if(!testdataDirectory.exists() || !testdataDirectory.isDirectory() || testdataDirectory.listFiles().length == 0) { throw new IllegalStateException("Test data directory \"" + testdataDirectory.getAbsolutePath() + " does not exist, is not a directory or is empty"); } TestUtil.deleteRecursive(new File("tmp")); }
4
public void run() { while(true){ try{ Thread.sleep(200); } catch(InterruptedException e){ } Displayable curr = display.current; if(curr instanceof Screen) { Screen scr = (Screen) curr; if(scr.ticker != null){ String t = scr.ticker.getString(); t = t.substring(step % t.length()) + " --- " + t; step ++; if(scr.tickerComponent.location == null){ scr.titleComponent.setText(scr.title + " "+t); scr.titleComponent.repaint(); } else { scr.tickerComponent.setText(t); scr.tickerComponent.setInvisible(false); scr.tickerComponent.repaint(); } } else if(step != 0){ step = 0; if(scr.tickerComponent.location == null){ scr.titleComponent.setText(scr.title); scr.titleComponent.repaint(); } else{ scr.tickerComponent.setInvisible(true); scr.container.repaint(); } } } } }
7
public boolean testReverse() throws PersistitException { setPhase("b"); _ex.clear().append(Key.AFTER); int index1 = _total - 1; int index2; while (_ex.previous() && !isStopped()) { index2 = (int) (_ex.getKey().decodeLong()); for (int i = index1; i > index2; i--) { if (_checksum[i] != -1) { return false; } } index1 = index2 - 1; final int cksum = checksum(_ex.getValue()); if ((index2 < 0) || (index2 >= _total)) { return false; } if (cksum != _checksum[index2]) { return false; } } for (int i = index1; i >= 0; i--) { if (_checksum[i] != -1) { return false; } } return true; }
9
public static boolean insertar(Recurso r) throws SQLException { // Deshabilitamos el autocommit para poder hacer rollback en caso de // error en alguna inserción (tocamos varias tablas) // ConnectionManager.connection.setAutoCommit(false); // Al insertar un nuevo recurso este se marca como disponible por defecto String queryRecurso = "INSERT INTO recurso (id, isbn, titulo, fecha, genero, num_ejemplar, estado_conserva, tipo, disponibilidad)" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)"; String queryLibro = "INSERT INTO recurso_libro (id, autor, editorial)" + "VALUES (?, ?, ?)"; String queryOptico = "INSERT INTO recurso_optico (id, autor)" + "VALUES (?, ?)"; String queryRevista = "INSERT INTO recurso_revista (id, editorial, fasciculo)" + "VALUES (?, ?, ?)"; try { if (r instanceof Libro) { ConnectionManager.executeSentence(queryRecurso, r.getID(), r.getISBN(), r.getTitulo(), r.getFechaEdicion(), r.getGenero(), r.getNumEjemplar(), r.getEstadoConservacion(), "Libro"); ConnectionManager.executeSentence(queryLibro, r.getID(), ((Libro) r).getAutor(), ((Libro) r).getEditorial()); } else if (r instanceof Revista) { ConnectionManager.executeSentence(queryRecurso, r.getID(), r.getISBN(), r.getTitulo(), r.getFechaEdicion(), r.getGenero(), r.getNumEjemplar(), r.getEstadoConservacion(), "Revista"); ConnectionManager.executeSentence(queryRevista, r.getID(), ((Revista) r).getEditorial(), ((Revista) r).getNumFasciculo()); } else if (r instanceof CdDvd) { ConnectionManager.executeSentence(queryRecurso, r.getID(), r.getISBN(), r.getTitulo(), r.getFechaEdicion(), r.getGenero(), r.getNumEjemplar(), r.getEstadoConservacion(), "Optico"); ConnectionManager.executeSentence(queryOptico, r.getID(), ((CdDvd) r).getAutor()); } } catch (Exception e) { System.out.println("Error: " + e.getMessage()); return false; } return true; }
4
private double run_model(Model model, List<Output> out, File folder, String simName, double[] x) throws Exception { Map<String, Object> parameter = model.getParameter(); Object comp = model.getComponent(); // spatial params ParameterData[] pd = Step.create(params, parameter); for (int i = 0; i < pd.length; i++) { pd[i].generateValues(x[i]); } for (int i = 0; i < pd.length; i++) { String name = pd[i].getName(); double[] val = pd[i].getDataValue(); parameter.put(name, toValue(name, val, parameter)); } ComponentAccess.callAnnotated(comp, Initialize.class, true); // setting the input data; boolean success = ComponentAccess.setInputData(parameter, comp, log); if (!success) { throw new RuntimeException("There are Parameter problems. Simulation exits."); } ComponentAccess.adjustOutputPath(folder, comp, log); for (Output e : out) { e.setup(comp, folder, simName); } // execute phases and be done. log.config("Exec ..."); ComponentAccess.callAnnotated(comp, Execute.class, false); log.config("Finalize ..."); ComponentAccess.callAnnotated(comp, Finalize.class, true); for (Output e : out) { e.done(); } return ObjFunc.calculateObjectiveFunctionValue(ofs, startMonthOfYear, sens_start, sens_end, folder); }
5
static void setPlayerSelecting(String name, boolean b) { if(b){ if(!playersSelect.containsKey(name)) { Location[] locarray = new Location[2]; playersSelect.put(name, locarray); } } else { Protect.log.info("No more sel"); if(playersSelect.containsKey(name)) { playersSelect.remove(name); } } }
3
synchronized void backward(float[] in, float[] out){ if(_x.length<n/2){ _x=new float[n/2]; } if(_w.length<n/2){ _w=new float[n/2]; } float[] x=_x; float[] w=_w; int n2=n>>>1; int n4=n>>>2; int n8=n>>>3; // rotate + step 1 { int inO=1; int xO=0; int A=n2; int i; for(i=0; i<n8; i++){ A-=2; x[xO++]=-in[inO+2]*trig[A+1]-in[inO]*trig[A]; x[xO++]=in[inO]*trig[A+1]-in[inO+2]*trig[A]; inO+=4; } inO=n2-4; for(i=0; i<n8; i++){ A-=2; x[xO++]=in[inO]*trig[A+1]+in[inO+2]*trig[A]; x[xO++]=in[inO]*trig[A]-in[inO+2]*trig[A+1]; inO-=4; } } float[] xxx=mdct_kernel(x, w, n, n2, n4, n8); int xx=0; // step 8 { int B=n2; int o1=n4, o2=o1-1; int o3=n4+n2, o4=o3-1; for(int i=0; i<n4; i++){ float temp1=(xxx[xx]*trig[B+1]-xxx[xx+1]*trig[B]); float temp2=-(xxx[xx]*trig[B]+xxx[xx+1]*trig[B+1]); out[o1]=-temp1; out[o2]=temp1; out[o3]=temp2; out[o4]=temp2; o1++; o2--; o3++; o4--; xx+=2; B+=2; } } }
5
public String[] Myself(boolean place) { try{ driver.get(baseUrl + "/content/lto/2013.html"); //global landing page driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div[3]/ul/li[10]/a")).click(); //Singapore landing page - Order Now button driver.findElement(By.xpath("/html/body/div[3]/div/div/div/div[3]/div/div[3]/div/div/a")).click(); //buyer select radio button driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/form/div/div/div/span")).click(); //buyer select continue button driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/form/div/div[3]/div/div/div/p")).click(); //buyer page info driver.findElement(By.id("distributorID")).clear(); driver.findElement(By.id("distributorID")).sendKeys("US8128558"); driver.findElement(By.id("email")).clear(); driver.findElement(By.id("email")).sendKeys("test@test.com"); //driver.findElement(By.cssSelector("a.selector")).click(); //driver.findElement(By.xpath("//div[@id='mobile_1_rightcol']/div/ul/li[2]")).click(); driver.findElement(By.id("mobile_2")).clear(); driver.findElement(By.id("mobile_2")).sendKeys("456"); driver.findElement(By.id("mobile_3")).clear(); driver.findElement(By.id("mobile_3")).sendKeys("456"); driver.findElement(By.id("nameOfPerson")).clear(); driver.findElement(By.id("nameOfPerson")).sendKeys("Test User"); driver.findElement(By.id("address_address1")).clear(); driver.findElement(By.id("address_address1")).sendKeys("75 West Center Street"); driver.findElement(By.id("address_address2")).clear(); driver.findElement(By.id("address_address2")).sendKeys("Test Address"); driver.findElement(By.id("address_postalCode")).clear(); driver.findElement(By.id("address_postalCode")).sendKeys("8460"); driver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div/div/div/p/a")).click(); //Buyer validation page driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/div/div/div/form/div/div/div/a")).click(); //product page driver.findElement(By.id("checkout")).click(); if (isElementPresent(By.className("shopError"))) { results[0] = "Singapore: Failed: Myself \n" + "URL: " + driver.getCurrentUrl() + "\n" + "Error: " + driver.findElement(By.className("shopError")).getText(); return results; } //shop app try{ Thread.sleep(100); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } driver.findElement(By.cssSelector("option[value=\"addPaymentType0\"]")).click(); driver.findElement(By.id("paymentNumber_id")).clear(); driver.findElement(By.id("paymentNumber_id")).sendKeys("4111111111111111"); driver.findElement(By.id("paymentName_id")).clear(); driver.findElement(By.id("paymentName_id")).sendKeys("bob"); driver.findElement(By.id("paymentSecurityNumber")).clear(); driver.findElement(By.id("paymentSecurityNumber")).sendKeys("456"); driver.findElement(By.xpath("/html/body/form/div/div[7]/div/div[5]/div/div/div/div[6]/div[3]/div[2]/button")).click(); try{ Thread.sleep(5000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (place) { driver.findElement(By.xpath("/html/body/form/div/div[12]/div/button")).click(); if (isElementPresent(By.className("shopError"))) { results[0] = "Singapore: Failed: Myself\n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Error: " + driver.findElement(By.className("shopError")).getText(); return results; } if (!isElementPresent(By.id("productinformation-complete"))) { results[0] = "Singapore: Failed: Order was not completed"; return results; } results[1] = driver.findElement(By.xpath("/html/body/form/div/div[2]/h2")).getText(); } results[0] = "Singapore: Passed"; return results; } catch (Exception e) { results[0] = "Singapore: Buy for Myself \n"+ "URL: " + driver.getCurrentUrl() + "\n" + "Script Error: " + e; return results; } }
7
private void initNetwork(String name, double baudRate, Link link) { // Every GridSim entity with network has its own input/output channels. // Connect this entity "input" port to its input buffer "in_port" NetIO in = null; // Packet Level networking if (GridSimCore.NETWORK_TYPE == GridSimTags.NET_PACKET_LEVEL) { in = new Input("Input_" + name, baudRate); out_ = new Output("Output_" + name, baudRate); } // Flow Level networking else if (GridSimCore.NETWORK_TYPE == GridSimTags.NET_FLOW_LEVEL) { in = new FlowInput("Input_" + name, baudRate); out_ = new FlowOutput("Output_" + name, baudRate); } // Use Finite network buffer else if (GridSimCore.NETWORK_TYPE == GridSimTags.NET_BUFFER_PACKET_LEVEL) { in = new FnbInput("Input_" + name, baudRate); out_ = new FnbOutput("Output_" + name, baudRate); } Sim_system.link_ports(name, "input", "Input_" + name, "input_buffer"); Sim_system.link_ports(name, "output", "Output_" + name, "output_buffer"); if (link != null) { in.addLink(link); out_.addLink(link); } }
4
public void updateStaff(){ Scanner sc = new Scanner(System.in); boolean bol = false; do{ System.out.println("Enter the ID of the staff who need to be update:"); int employee_id = inputInteger(); Staff toUpdateStaff = staffManager.getStaffbyID(employee_id); System.out.println("Choose which one to update:\n\t1.Staff's Name\n\t" + "2.Staff's Gender\n\t3.Staff's Job Title\n\t4.Back"); switch(inputInteger()){ case 1: System.out.println("Enter the new name"); String newName = sc.nextLine(); toUpdateStaff.setStaffName(newName); break; case 2: System.out.println("Enter the correct Gender (m for male, f for female): "); String gender; boolean corrGender; while (true) { gender = sc.next(); if (gender.equals("m") || gender.equals("f")) { corrGender = gender.equals("m"); break; } System.out.print("Invalid gender, try again: "); } toUpdateStaff.setGender(corrGender); break; case 3: System.out.println("Enter the new Job Title:"); String newJobTitle = sc.nextLine(); toUpdateStaff.setJobTitle(newJobTitle); break; case 4: break; } System.out.println("Update one more staff?('y' to continue)"); bol =sc.next().equals("y"); sc.nextLine(); }while(bol); }
8
@Override @SuppressWarnings("unchecked") public Object read(Class type, CommandInvocation invocation) throws ReaderException { if (invocation.getManager().hasReader(type)) { return invocation.getManager().read(type, type, invocation); } if (Enum.class.isAssignableFrom(type)) { Enum<?>[] enumConstants = ((Class<? extends Enum<?>>)type).getEnumConstants(); String token = invocation.currentToken().replace(" ", "_").toUpperCase(); for (Enum<?> anEnum : enumConstants) { if (anEnum.name().equals(token)) { invocation.consume(1); return anEnum; } } throw new ReaderException("Could not find \"" + invocation.currentToken() + "\" in Enum"); } throw new UnsupportedOperationException(); }
8
public void resumeGame() throws InterruptedException { boolean test = false; if (test || m_test) { System.out.println("Game :: resumeGame() BEGIN"); } setWindow(new GameWindow(this)); setScores(); getWindow().displayPlayerTurn(m_playerTurn); getWindow().updateScore(m_player1Score, m_player2Score); setTurnCount(m_player1Score + m_player2Score); getWindow().updateScore(m_player1Score, m_player2Score); setTurnCount(m_player1Score + m_player2Score); if (getPlayerTurn().equals(PlayerTurn.PLAYER1)){ getPlayer1().isYourMove(); } else { getPlayer2().isYourMove(); } //startTimer(); if (test || m_test) { System.out.println("Game :: resumeGame() END"); } }
5
@Override public boolean move(int x, int y, int xf, int yf) { if (canMove(x, y)) { for (int[] hint : getHints(x, y)) { if ((xf == hint[0]) && (yf == hint[1])) { //se arrivo in fondo, devo creare un damone if (((xf == 0) || (xf == 8 - 1)) && (tabellone[x][y] < 3)) { tabellone[xf][yf] = tabellone[x][y] + 2; justDamone = true; } else { tabellone[xf][yf] = tabellone[x][y]; } tabellone[x][y] = VUOTO; return true; } } } return false; }
7
private List<Position> getAdjacentPositions(Position pos, int width, int height) { ArrayList<Position> neighbours = new ArrayList<Position>(); for (Direction mov : Direction.values()) { Position newPos = mov.newPosition(pos); if (isValidPosition(newPos, width, height)) { neighbours.add(newPos); } } return neighbours; }
2
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed Transferable clipboardContent = getToolkit().getSystemClipboard().getContents(this); if ((clipboardContent != null) && (clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) { try { String tempString; tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor); jTextField2.setText(tempString); } catch (Exception e) { e.printStackTrace(); } } }//GEN-LAST:event_jButton4ActionPerformed
3
private void log(String prefix, String message) { String log = buildMessage(prefix, message); System.out.println(log); if (outputStream != null) { try { outputStream.write((log + "\r\n").getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2
public Object trapMethodcall(int identifier, Object[] args) throws Throwable { try { Method[] m = getReflectiveMethods(); return m[identifier].invoke(null, args); } catch (java.lang.reflect.InvocationTargetException e) { throw e.getTargetException(); } catch (java.lang.IllegalAccessException e) { throw new CannotInvokeException(e); } }
2
@Override protected void finalize() { if (resource.removeReference() && !fileName.isEmpty()) { loadedTextures.remove(fileName); } }
2
public String getKeyName() { return this.value; }
0
public void populateLibrary(int numSpecies, int numNodes, int numBondingSites){ Molecule nullMolecule = new Molecule(); if(!reuse){ library.add(new Network(0)); for(int i=1; i<numSpecies; i++){ library.add(new Network(numNodes, i, numBondingSites)); library.get(i).setMol(new Molecule(i, nullMolecule, nullMolecule)); progress("Adding...", i, numSpecies); } progress("Adding...", numSpecies, numSpecies); for(int i=0; i<numSpecies; i++){ DataOutput out = new DataOutput("/data/library/"+i+".txt"); progress("Saving...", i, numSpecies); try{ out.writeToFile(library.get(i)); }catch(IOException e){System.out.println("Could not write file.");} } progress("Saving...", numSpecies, numSpecies); } else{ for(int i=0; i<numSpecies; i++){ progress("Retrieving...", i, numSpecies); DataOutput in = new DataOutput(path+i+".txt"); try{ library.add(in.readFile()); library.get(0).setPop(0); }catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); } } progress("Retrieving...", numSpecies, numSpecies); } }
7