method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
6d5698dc-d975-4515-b71d-ddc499787b3f
3
public List<Bomb> collectBombs() { List<Bomb> bombs = new ArrayList<Bomb>(); for (Tile[] tiles : this.map) { for (int i = 0; i < tiles.length; i++) { Tile tile = tiles[i]; if (tile.getBomb() != null) { bombs.add(tile.getBomb()); } } } return bombs; }
ca3af533-2f03-490e-bf86-8d01eb1e80dd
5
public static void loadConstants() { try { //get a connection to the constants file and read it final String fileName = "file:///" + CONSTANTS_FILE_NAME; printIfDebug("Opening constants file: " + fileName); FileConnection commandFileConnection = (FileConnection) Connector.open(fileName, Connector.READ); DataInputStream commandFileStream = commandFileConnection.openDataInputStream(); StringBuffer fileContentsBuffer = new StringBuffer((int) commandFileConnection.fileSize()); //read characters from the file until end of file is reached byte[] buff = new byte[255]; while (commandFileStream.read(buff) != -1) { fileContentsBuffer.append(new String(buff)); //inefficient, but with long files necessary buff = new byte[255]; } String fileContents = fileContentsBuffer.toString(); printIfDebug("Constants file output: " + fileContents); StringTokenizer lineTokenizer = new StringTokenizer(fileContents, "\n"); CONSTANTS = new Vector(lineTokenizer.countTokens()); //for each line, split into space-separated tokens while (lineTokenizer.hasMoreTokens()) { String line = lineTokenizer.nextToken().trim(); if (line.startsWith("#")) { continue; } StringTokenizer spaceTokenizer = new StringTokenizer(line, " "); //map the first two tokens if (spaceTokenizer.countTokens() > 1) { final String key = spaceTokenizer.nextToken().trim(); final String value = spaceTokenizer.nextToken().trim(); CONSTANTS.addElement(new Constant(key, value)); printIfDebug("Put constant: " + key + ": " + value + ", of type " + Constant.TYPE_NAMES[((Constant) CONSTANTS.lastElement()).getType()]); } } } catch (Exception ex) { System.out.println("Could not load file " + CONSTANTS_FILE_NAME + ". Are you sure it is in the root directory of the cRIO?"); } }
5b3d9f31-1c4d-4c2f-a4ff-2e49ae829b43
2
@Test public void testGetLastCheckpoint()throws Exception{ Tracking trackingGet1 = new Tracking("GM605112270084510370"); trackingGet1.setSlug("dhl-global-mail"); Checkpoint newCheckpoint = connection.getLastCheckpoint(trackingGet1); Assert.assertEquals("Should be equals message", "Delivered", newCheckpoint.getMessage()); Assert.assertEquals("Should be equals city name", "BUDERIM QLD, AU", newCheckpoint.getCountryName()); Assert.assertEquals("Should be equals tag", "Delivered", newCheckpoint.getTag()); //slug is bad informed try{ Tracking trackingGet2 = new Tracking("GM605112270084510370"); trackingGet2.setSlug("dhl--mail"); connection.getLastCheckpoint(trackingGet2); //always should give an exception before this assertTrue("This never should be executed",false); }catch (Exception e){ assertTrue(e.getMessage().contains("4010")); assertTrue(e.getMessage().contains("The value of `slug` is invalid.")); } //if the trackingNumber is bad informed try{ Tracking trackingGet2 = new Tracking("ads"); trackingGet2.setSlug("dhl--mail"); connection.getLastCheckpoint(trackingGet2); //always should give an exception before this assertTrue("This never should be executed",false); }catch (Exception e){ assertEquals("It should return a exception if the slug is not informed properly" , "{\"meta\":{\"code\":4005,\"message\":\"The value of `tracking_number` is invalid.\",\"type\":\"BadRequest\"},\"data\":{\"tracking\":{\"tracking_number\":\"ads\",\"slug\":\"dhl--mail\"}}}", e.getMessage()); } }
80d3aac3-1081-4983-8429-0ece2dcd1481
7
/* */ public Object getTeleportPacket(Location loc) /* */ { /* 134 */ Class<?> PacketPlayOutEntityTeleport = Util.getCraftClass("PacketPlayOutEntityTeleport"); /* */ /* 136 */ Object packet = null; /* */ try /* */ { /* 139 */ packet = PacketPlayOutEntityTeleport.getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, Byte.TYPE, Byte.TYPE }).newInstance(new Object[] { Integer.valueOf(this.id), Integer.valueOf(loc.getBlockX() * 32), Integer.valueOf(loc.getBlockY() * 32), Integer.valueOf(loc.getBlockZ() * 32), Byte.valueOf((byte)((int)loc.getYaw() * 256 / 360)), Byte.valueOf((byte)((int)loc.getPitch() * 256 / 360)) }); /* */ } catch (IllegalArgumentException e) { /* 141 */ e.printStackTrace(); /* */ } catch (SecurityException e) { /* 143 */ e.printStackTrace(); /* */ } catch (InstantiationException e) { /* 145 */ e.printStackTrace(); /* */ } catch (IllegalAccessException e) { /* 147 */ e.printStackTrace(); /* */ } catch (InvocationTargetException e) { /* 149 */ e.printStackTrace(); /* */ } catch (NoSuchMethodException e) { /* 151 */ e.printStackTrace(); /* */ } /* */ /* 154 */ return packet; /* */ }
7a7d7059-394f-4bfd-b9b7-d1a10b94a9c7
5
public void run() { try { Map<String, String> requestHeaders = new HashMap<String, String>(); Map<String, String> formParams = new HashMap<String, String>(); formParams.put(CommunityConstants.BASE64_PUBLIC_KEY, Base64.encode(pair.getPublic().getEncoded())); formParams.put(CommunityConstants.NICKNAME, "test user"); URL url = new URL("http://127.0.0.1:8080/community"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); for (String head : requestHeaders.keySet()) { conn.setRequestProperty(head, requestHeaders.get(head)); } // add url form parameters OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); Iterator<String> params = formParams.keySet().iterator(); while (params.hasNext()) { String name = params.next(); String value = formParams.get(name); out.append(URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8")); if (params.hasNext()) { out.append("&"); } } out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println("resp line: " + line); } in.close(); System.out.println("final status code: " + conn.getResponseCode() + " / " + conn.getResponseMessage()); } catch (Exception e) { e.printStackTrace(); } }
9020ff53-52f3-434f-98c0-6451d06d5e62
8
static void prob4() { /* * A palindromic number reads the same both ways. The largest palindrome * made from the product of two 2-digit numbers is 9009 = 91 99. * * Find the largest palindrome made from the product of two 3-digit * numbers. */ long start = System.currentTimeMillis(); int max = 0; int temp; int limit = 0; for (int i = 999; i > 99; i--) if (i % 10 != 0) for (int j = 999; j > 99 && j > limit; j--) if (j % 10 != 0) { temp = i * j; if (Palindrone.isPalindrone(temp) && temp > max) { max = temp; // if we already did 10x10, then anything // less than 10, times 10 will be less than 10x10 if (j > limit) limit = j; j = 0; } } System.out.println("4: " + max); System.out.println("\tTime taken: " + (System.currentTimeMillis() - start)); }
d6f4b7d5-ce84-47fd-af4d-39aae6c41e81
1
@Override public Integer call() throws Exception { System.out.println("子线程在进行计算"); Thread.sleep(3000); int sum = 0; for(int i=0;i<100;i++) sum += i; return sum; }
4d9a7f7a-c559-4cbf-86d4-202979236a25
6
@SuppressWarnings({ "rawtypes", "unchecked" }) public static int partition(Comparable[] a, int min, int max){ int i = min; int j = max + 1; Comparable element = a[min]; while(true){ while(a[++i].compareTo(element) < 0){ if(i == max) break; } while(element.compareTo(a[--j]) < 0){ if(j == min) break; } if(i >= j) break; Comparable buff = a[i]; a[i] = a[j]; a[j] = buff; } Comparable buff = a[min]; a[min] = a[j]; a[j] = buff; return j; }
81c98a72-8b66-494d-a10f-8606321ccccb
7
private final int calcHPChange(final MapleCharacter applyfrom, final boolean primary) { int hpchange = 0; if (hp != 0) { if (!skill) { if (primary) { hpchange += alchemistModifyVal(applyfrom, hp, true); } else { hpchange += hp; } } else { // assumption: this is heal hpchange += makeHealHP(hp / 100.0, applyfrom.getStat().getTotalMagic(), 3, 5); } } if (hpR != 0) { hpchange += (int) (applyfrom.getStat().getCurrentMaxHp() * hpR); } // actually receivers probably never get any hp when it's not heal but whatever if (primary) { if (hpCon != 0) { hpchange -= hpCon; } } switch (this.sourceid) { case 4211001: // Chakra // final PlayerStats stat = applyfrom.getStat(); // int v42 = getY() + 100; // int v38 = Randomizer.rand(100, 200) % 0x64 + 100; // hpchange = (int) ((v38 * stat.getLuk() * 0.033 + stat.getDex()) * v42 * 0.002); hpchange += makeHealHP(getY() / 100.0, applyfrom.getStat().getTotalLuk(), 2.3, 3.5); break; } return hpchange; }
0b238f8a-208f-4090-8ff9-3d71fc28400b
4
public static void main (String[] args) { System.out.println("Irule! YEAR BOIIII"); System.out.println("LIKEABOSSSSS"); String name = "Dencho"; int x = 3; x = x *17; System.out.print("x is " + x); while (x > 12) { x = x -1; } while (x > 10) { x = x - 1; System.out.println("subbing"); } if (x == 10) { System.out.println("x must be 10"); } else { System.out.println("x isnt 10"); } if ((x < 30) & (name.equals("Dencho"))) { System.out.println("Gently"); } System.out.print("this line runs no matter"); }
34aa8e37-abc2-4668-980d-ba202618a899
2
public Production getSimplifiedProduction(Production production) { String lhs = (String) MAP.get(production.getLHS()); String rhs = production.getRHS(); int leftIndex, rightIndex; // Position of left and right parentheses. StringBuffer newRhs = new StringBuffer(); while ((leftIndex = rhs.indexOf('(')) != -1 && (rightIndex = rhs.indexOf(')')) != -1) { newRhs.append(rhs.substring(0, leftIndex)); String variable = rhs.substring(leftIndex, rightIndex + 1); newRhs.append(MAP.get(variable)); rhs = rhs.substring(rightIndex + 1); } newRhs.append(rhs); Production p = new Production(lhs, newRhs.toString()); return p; }
035751d2-3e7b-4a6b-90ad-35b8e525801d
6
private OrderReport processMarketOrder(Order quote, boolean verbose) { ArrayList<Trade> trades = new ArrayList<Trade>(); String side = quote.getSide(); int qtyRemaining = quote.getQuantity(); if (side =="bid") { this.lastOrderSign = 1; while ((qtyRemaining > 0) && (this.asks.getnOrders() > 0)) { OrderList ordersAtBest = this.asks.minPriceList(); qtyRemaining = processOrderList(trades, ordersAtBest, qtyRemaining, quote, verbose); } }else if(side=="offer") { this.lastOrderSign = -1; while ((qtyRemaining > 0) && (this.bids.getnOrders() > 0)) { OrderList ordersAtBest = this.bids.maxPriceList(); qtyRemaining = processOrderList(trades, ordersAtBest, qtyRemaining, quote, verbose); } }else { throw new IllegalArgumentException("order neither market nor limit: " + side); } OrderReport report = new OrderReport(trades, false); return report; }
1165a021-247e-4b25-a5ca-9b24e955d389
9
@SuppressWarnings("unchecked") public CepService(String cep) { try { URL url = new URL("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep + "&formato=xml"); Document document = getDocumento(url); Element root = document.getRootElement(); for (Iterator<Element> i = root.elementIterator(); i.hasNext();) { Element element = i.next(); if (element.getQualifiedName().equals("uf")) setEstado(element.getText()); if (element.getQualifiedName().equals("cidade")) setCidade(element.getText()); if (element.getQualifiedName().equals("bairro")) setBairro(element.getText()); if (element.getQualifiedName().equals("tipo_logradouro")) setTipo_logradouro(element.getText()); if (element.getQualifiedName().equals("logradouro")) setLogradouro(element.getText()); if (element.getQualifiedName().equals("resultado")) setResultado(Integer.parseInt(element.getText())); if (element.getQualifiedName().equals("resultado_txt")) setResultado_txt(element.getText()); } } catch (Exception ex) { ex.printStackTrace(); } }
c8f47081-1211-401c-9f0f-8dd6a1e61b05
8
protected void read(InputStream in, int maxLength) throws IOException, ParsingException { InputBuffer buffer = new InputBuffer(in, 24, 24); if (!Arrays.equals(magic, buffer.get(0, 4))) { throw new ParsingException("Unknown magic bytes: " + Arrays.toString(buffer.get(0, 4))); } byte[] ascii = buffer.get(4, 12); StringBuilder str = new StringBuilder(); for (byte b : ascii) { if (b == 0) { break; } str.append(new String(new byte[] { b }, "ASCII")); } command = str.toString(); length = Util.getInt(buffer.get(16, 4)); checksum = buffer.get(20, 4); if (length < 0) { throw new ParsingException("The length of the payload is < 0"); } if (length > maxLength) { throw new ParsingException("The payload is too long: " + length + " bytes"); } int chunkSize = 1024; if (length > 1_000_000) { chunkSize = 1024 * 1024; } else if (length > 100_000) { chunkSize = 128 * 1024; } buffer = new InputBuffer(in, chunkSize, length); if (!Arrays.equals(checksum, Digest.sha512(buffer.get(0, length), 4))) { throw new ParsingException("Wrong digest for payload!"); } payload = factory.parseP2PMessage(command, buffer); }
5a0fba71-d8c2-4dee-a0dd-d80500cfc2b1
1
private void returnStatement() { if (accept(NonTerminal.RETURN_STATEMENT)) { expression0(); expect(Token.Kind.SEMICOLON); } }
25f587dd-45d3-404a-845a-3a07ddc2b7f7
8
@Override public double getProgress() { switch (getState()) { case READY: return 0.0; case EXECUTING: case ROLLBACKING: case PAUSED: return 0.5; case EXECUTION_SUCCEEDED: case EXECUTION_FAILED: case ROLLBACK_SUCCEEDED: case ROLLBACK_FAILED: return 1.0; default: return 0.0; } }
b5cd6bd3-b8b8-46ed-8956-bd648641b780
3
public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream()); login = in.readLine(); password = in.readLine(); DbConnect DBC = new DbConnect(); state = DBC.Connect(); ResultSet result = state.executeQuery("SELECT login FROM users WHERE login = '"+login+"' AND password= '"+password+"'"); if (!result.next()){ IDcheck = 0; out.print(IDcheck); out.flush(); } else { IDcheck = 1; out.println(IDcheck); out.flush(); String s = "Server"; ChatWindow cw = new ChatWindow(socket,s); } } catch (IOException e) { System.out.println("Error connecting to the Server."); } catch (SQLException e) { System.out.println("Error connecting to the SQL Server."); } }
3f5a6a81-d374-492b-82d9-339dc9c24f34
3
public static boolean addArtist(boolean manually, String prefName, String name, String ... moreNames) { try { check(); int aid = createArtist(prefName, manually); createName(name, aid); if(moreNames != null) { for(int i = 0; i < moreNames.length; i++) { String mn = moreNames[i]; createMoreName(mn, aid, i); } } return true; } catch(Exception e) { return false; } }
55b74985-2173-4b4b-8c5c-91eebb72a7b0
7
public CoordVizualizer() { super(new BorderLayout()); mapKit = new JXMapKit(); mapKit.setName("mapKit"); mapKit.setPreferredSize(new Dimension(413, 218)); add(mapKit, BorderLayout.CENTER); mapKit.setDefaultProvider(DefaultProviders.OpenStreetMaps); mapKit.setCenterPosition(new GeoPosition(54.4248, 10.1721)); Set<Waypoint> waypoints = new HashSet<Waypoint>(); waypoints.add(home); waypoints.add(current); waypoints.add(target); WaypointPainter painter = new WaypointPainter(); painter.setRenderer(new WaypointRenderer() { public boolean paintWaypoint(Graphics2D g, JXMapViewer map, Waypoint wp) { Image icon = null; // String s = ""; if (wp == home) { icon = DataStorage.iconHome.getImage(); } else if (wp == target) { icon = DataStorage.iconTarget.getImage(); } else if (wp == current) { icon = DataStorage.iconCurrent.getImage(); // AffineTransform at = AffineTransform.getRotateInstance(30.0); // g.drawImage(icon, at, null); // icon = null; } if (icon != null) { g.drawImage(icon, AffineTransform.getTranslateInstance(-(icon.getWidth(map) / 2), -icon.getHeight(map)), map); } return true; } }); painter.setWaypoints(waypoints); //: warning: [unchecked] unchecked call to setWaypoints(java.util.Set<org.jdesktop.swingx.mapviewer.Waypoint>) as a member of the raw type org.jdesktop.swingx.mapviewer.WaypointPainter //painter.setWaypoints(waypoints); mapKit.getMainMap().setOverlayPainter(painter); /* WMSService wms = new WMSService(); wms.setLayer("BMNG"); wms.setBaseUrl("http://wms.jpl.nasa.gov/wms.cgi?"); TileFactory fact = new WMSTileFactory(wms); mapKit.setTileFactory(fact); */ /*WMSService wms = new WMSService(); wms.setLayer("0"); wms.setBaseUrl("http://gdz-dop.bkg.bund.de/ArcGIS/services/DOP/ImageServer/WMSServer?"); TileFactory fact = new WMSTileFactory(wms); mapKit.setTileFactory(fact); */ mapKit.getMainMap().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { GeoPosition geopoint = mapKit.getMainMap().convertPointToGeoPosition(e.getPoint()); //System.out.println(geopoint); if (e.getClickCount() == 2) { if (e.getButton() == 1) { // left setGeoPosition(geopoint, DataStorage.naviData.HomePosition.Latitude, DataStorage.naviData.HomePosition.Longitude); } } else { if (e.getButton() == 1) { // left setGeoPosition(geopoint, DataStorage.naviData.CurrentPosition.Latitude, DataStorage.naviData.CurrentPosition.Longitude); } else { setGeoPosition(geopoint, DataStorage.naviData.TargetPosition.Latitude, DataStorage.naviData.TargetPosition.Longitude); } } update(); } }); }
20864a99-f6dc-404f-8680-2d88cfd2f4f1
3
public double rollOut() { StateObservation rollerState = state.copy(); int thisDepth = this.m_depth; while (!finishRollout(rollerState,thisDepth)) { int action = m_rnd.nextInt(num_actions); rollerState.advance(actions[action]); thisDepth++; } double delta = value(rollerState); if(delta < bounds[0]) bounds[0] = delta; if(delta > bounds[1]) bounds[1] = delta; return delta; }
5764019b-6b82-4833-936f-8257cc0dccd0
5
public <V extends Collection<T>> V fetchContainingIntervals(V target, U queryPoint) { if (target == null) { throw new NullPointerException("target is null"); } if (queryPoint == null) { throw new NullPointerException("queryPoint is null"); } Node<U, T> node = root; while (node != null) { U temp = node.getPoint(); if (queryPoint.equals(temp)) { node.fetchIntervalsContainingNodePoint(target); node = null; } else if (queryPoint.compareTo(temp) < 0) { node.fetchIntervalsContainingPointLow(target, queryPoint, true); node = node.getLeft(); } else { node.fetchIntervalsContainingPointHigh(target, queryPoint, true); node = node.getRight(); } } return target; }
736e1cde-0b1f-494d-b6a8-e1f98a5afa08
1
private boolean jj_2_68(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_68(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(67, xla); } }
cfdaa45f-1bb2-4417-b763-4cd302597df1
9
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* * We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* * Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* * If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* * Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
38dd6c79-f0cc-4c27-a2d1-24aa089062eb
8
private void init() { if (Double.compare(getWidth(), 0) <= 0 || Double.compare(getHeight(), 0) <= 0 || Double.compare(getPrefWidth(), 0) <= 0 || Double.compare(getPrefHeight(), 0) <= 0) { setPrefSize(PREFERRED_SIZE, PREFERRED_SIZE); } if (Double.compare(getMinWidth(), 0) <= 0 || Double.compare(getMinHeight(), 0) <= 0) { setMinSize(MINIMUM_SIZE, MINIMUM_SIZE); } if (Double.compare(getMaxWidth(), 0) <= 0 || Double.compare(getMaxHeight(), 0) <= 0) { setMaxSize(MAXIMUM_SIZE, MAXIMUM_SIZE); } }
e510693b-f89d-456e-b72a-fd703b2d41b8
7
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
5e8c4940-3426-410e-8d4e-2d659bade19b
7
public static void populate() { Random rand = Randomizer.getRandom(); field.clear(); for(int row = 0; row < field.getDepth(); row++) { for(int col = 0; col < field.getWidth(); col++) { if(rand.nextDouble() <= FOX_CREATION_PROBABILITY) { Location location = new Location(row, col); Fox fox = new Fox(false, field, location); actors.add(fox); } else if(rand.nextDouble() <= HUNTER_CREATION_PROBABILITY) { Location location = new Location (row, col); Hunter hunter = new Hunter(false, field, location); actors.add(hunter); } else if(rand.nextDouble() <= RABBIT_CREATION_PROBABILITY) { Location location = new Location(row, col); Rabbit rabbit = new Rabbit(false, field, location); actors.add(rabbit); } else if(rand.nextDouble() <= ALLIGATOR_CREATION_PROBABILITY) { Location location = new Location(row, col); Alligator alligator = new Alligator(false, field, location); actors.add(alligator); } else if (rand.nextDouble() <= GRASS_CREATION_PROBABILITY) { Location location = new Location(row, col); Grass grass = new Grass(field, location); actors.add(grass); } // else leave the location empty. } } }
94aaaeeb-aac5-4ac7-be3c-ae2a7fe8533d
6
private Rule _NextRule(String nonterm){ HashSet<Rule> prog_rules = m_mapping.get(nonterm); Rule rule = new Rule(); m_possible_lexems = new HashSet<ArrayList<String>>(); for(Rule cur_rule : prog_rules) { ArrayList<String> terminals = new ArrayList<String>(); HashSet<String> cur_set = m_table.get(cur_rule); if(cur_set.isEmpty() == false) { for(String terminal : cur_set) { terminals.add(terminal); } m_possible_lexems.add(terminals); } if(cur_set.contains(m_token.value)) { rule = cur_rule; return rule; } } for(Rule ext_rule : prog_rules){ if(ext_rule.IsEpsilonRule()) { rule = ext_rule; return rule; } } return rule; }
3e1b01d7-ea38-4119-9755-78a6c69ba783
2
public void addSample(double value) { if(value < min) { min = value; } if(value > max) { max = value; } sum += value; squared_sum += value * value; num_samples++; }
327f3535-01b6-462a-8fcb-135c932a2f7d
9
public void updateNeighbors() throws RemoteException { neighborsTable = new HashMap<String, Double[]>(); double distValue; List<String> listOfOffices = registry.list(); try { Double maxDistance = 0.0; Object removeNodeName = null; Iterator<String> iter = listOfOffices.iterator(); while (iter.hasNext()) { GPSOfficeRef neighbor = (GPSOfficeRef) registry.lookup(iter .next()); distValue = this.calculateDistance(neighbor); // Adds the first 3 the neighbors. if ((distValue != 0) && (neighborsTable.size() < 3)) { Double[] tempXY = new Double[3]; tempXY[0] = neighbor.getX(); tempXY[1] = neighbor.getY(); tempXY[2] = distValue; neighborsTable.put(neighbor.getOfficeName(), tempXY); } // Removes the neighbor that has maximum distance else if ((distValue != 0) && (neighborsTable.size() == 3)) { maxDistance = 0.0; Set<String> nodes = neighborsTable.keySet(); Iterator<String> nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Object nodeName = nodeIterator.next(); Double[] nodeValues = neighborsTable.get(nodeName); if (nodeValues[2] > maxDistance) { maxDistance = nodeValues[2]; removeNodeName = nodeName; } } // Replaces the neighbor node having maximum distance if (distValue < maxDistance) { Double[] tempXY = new Double[3]; tempXY[0] = neighbor.getX(); tempXY[1] = neighbor.getY(); tempXY[2] = distValue; neighborsTable.put(neighbor.getOfficeName(), tempXY); neighborsTable.remove(removeNodeName); } } } } catch (NotBoundException ex) { ex.printStackTrace(); } }
f3a48c1e-531f-409d-8e85-1da6adcc3463
3
private void jButtonFilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFilesActionPerformed Logger.getLogger(UserInterface.class.getName()).log(Level.FINE, "FileChooser"); JFileChooser f = new JFileChooser(); f.setMultiSelectionEnabled(true); if (f.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File[] fs = f.getSelectedFiles(); for (File fi : fs) { this.user.getFiles().add(new SignatureFile(fi)); } this.model.fireTableDataChanged(); } try { DataBase.getInstance().save(); } catch (Exception ex) { Logger.getLogger(UserInterface.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButtonFilesActionPerformed
ecad6dab-17ea-44d8-bc2a-f6313ad542e2
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 { javax.swing.UIManager.LookAndFeelInfo[] installedLookAndFeels=javax.swing.UIManager.getInstalledLookAndFeels(); for (int idx=0; idx<installedLookAndFeels.length; idx++) if ("Nimbus".equals(installedLookAndFeels[idx].getName())) { javax.swing.UIManager.setLookAndFeel(installedLookAndFeels[idx].getClassName()); break; } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Main.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() { Main main; try { main = new Main(); main.setLocationRelativeTo(null); main.setVisible(true); main.showTVFormatFrame(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.WARNING, null, ex); } } }); }
ed96c203-c3a0-41b1-b48b-8789dd0f8653
8
public void zip(File source) { try { File[] files = source.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { zip(files[i]); } else { FileInputStream fis = new FileInputStream(files[i]); bis = new BufferedInputStream(fis); int avail = bis.available(); byte[] buffer = new byte[avail]; if (avail > 0) { bis.read(buffer, 0, avail); } String entryName = files[i].getAbsolutePath().substring(sourcecpy.getAbsolutePath().length()+1).replace("\\", "/"); if (entryName.contains("_aux.class")) { entryName = entryName.replace("_aux.class", "aux.class"); } //Write file in JAR file JarEntry ze = new JarEntry(entryName); zipOut.putNextEntry(ze); int length = (int)files[i].length() ; zipOut.write(buffer, 0, length); Install.detState(val += addi); zipOut.closeEntry(); } } } } catch (Exception ex) { Install.errors+=getError(ex)+"\n\n"; } finally { try { if(bis != null) bis.close(); } catch (Exception ex) {} } }
d0b7da82-28cd-4f7f-9c56-e9ee448f89f7
6
public void downloadFiles() { recursiveDelete(new File(OS.getFolderFile(), "bin")); File downloadDir = new File(OS.getFolderFile(), "bin"); downloadDir.mkdirs(); File nativesDir = new File(downloadDir, "natives"); nativesDir.mkdirs(); List<DownloadFile> files = new ArrayList<DownloadFile>(); files.add(new DownloadFile("http://s3.amazonaws.com/MinecraftDownload/minecraft.jar", "minecraft.jar", downloadDir)); files.add(new DownloadFile("http://s3.amazonaws.com/MinecraftDownload/lwjgl_util.jar", "lwjgl_util.jar", downloadDir)); files.add(new DownloadFile("http://s3.amazonaws.com/MinecraftDownload/lwjgl.jar", "lwjgl.jar", downloadDir)); files.add(new DownloadFile("http://s3.amazonaws.com/MinecraftDownload/jinput.jar", "jinput.jar", downloadDir)); switch (OS.getOS()) { case WINDOWS: files.add(new DownloadFile("http://s3.amazonaws.com/MinecraftDownload/windows_natives.jar", "windows_natives.jar", nativesDir, true)); break; case LINUX: files.add(new DownloadFile("http://s3.amazonaws.com/MinecraftDownload/linux_natives.jar", "linux_natives.jar", nativesDir, true)); break; case MAC: files.add(new DownloadFile("http://s3.amazonaws.com/MinecraftDownload/macos_natives.jar", "macos_natives.jar", nativesDir, true)); break; default: break; } for (DownloadFile df : files) { try { progressTextField.setText("Downloading " + df.fileName); download(df); if (df.extract) { extract(df.fileName, df.path); } } catch (IOException ex) { ex.printStackTrace(System.out); } } }
1e456e9f-1b61-47b7-8d30-39f5f3239c94
4
public void removeTaxis(int taxis) { int i = 0; try { int loops = 0; while (i < taxis) { loops++; if (items.get(loops) instanceof Taxi) { if (!((MovingMapItem) items.get(loops)).dying()) { ((MovingMapItem) items.get(loops)).kill(); i++; } } } } catch (ArrayIndexOutOfBoundsException e) { return; /* Out of bounds */ } }
d6690ddd-bd37-40bd-95c7-1d5955d737e4
8
public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_RIGHT: if (gameBoard.isValidMove(Direction.RIGHT)) { gameBoard.moveSide(Direction.RIGHT); repaint(); } break; case KeyEvent.VK_LEFT: if (gameBoard.isValidMove(Direction.LEFT)) { gameBoard.moveSide(Direction.LEFT); repaint(); } break; case KeyEvent.VK_SPACE: if (gameBoard.isValidMove(Direction.ROTATE)) { gameBoard.rotateBlock(); gameBoard.updateBoard(); repaint(); } break; case KeyEvent.VK_DOWN: if(speed == 1) speed = 6; break; default: break; } }
fdfc4dd2-5d26-47ae-be70-3ac1f823885f
4
private void radixSort0(int[] a, int i, int low, int high) { if (i < 0) return; for (int j = low; j < high; j++) registers[getDigit(a[j], i)].offer(a[j]); //printInfo(i); int index = low; for (Queue register : registers) { int low2 = index; while (!register.isEmpty()) { set(index++, (Integer) register.poll()); } int high2 = index; addRun(i - 1, low2, high2); } }
0fa94120-5e68-4e0a-9549-1c57643b9f8a
7
public void listeningPort(){ BufferedReader entradaCliente; DataOutputStream salidaServer; String peticion = ""; int tamano = 0; try (ServerSocket puertoServidor = new ServerSocket(PUERTO)) { Socket puerto = puertoServidor.accept(); entradaCliente = new BufferedReader(new InputStreamReader( puerto.getInputStream())); salidaServer = new DataOutputStream(puerto.getOutputStream()); String parametros = "", linea = ""; int indiceLinea = 0; while((linea = entradaCliente.readLine()) != null){ if(linea.length() == 0){ break; } if(indiceLinea != 0){ peticion = peticion + "\n"; } if(linea.startsWith("Content-Length: ")){ tamano = Integer.parseInt(linea.substring(16)); } indiceLinea++; peticion = peticion + linea; } parametros = leerParametros(tamano, entradaCliente); System.out.println(peticion); System.out.println(parametros); HttpResponse response = responseRequest(peticion); if(response.status() == 200 && !parametros.equals("")){ parameterManager.load(parametros); } salidaServer.writeUTF(response.render()); System.out.println(response.render()); salidaServer.close(); } catch (IOException ex) { Logger.getLogger(WebServer.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error: " + ex.getMessage()); } }
e50f5845-cdf8-4f5b-84f1-7893472419d3
9
public Model method202(int i) { if (stackIDs != null && i > 1) { int j = -1; for (int k = 0; k < 10; k++) if (i >= stackAmounts[k] && stackAmounts[k] != 0) j = stackIDs[k]; if (j != -1) return forID(j).method202(1); } Model model = Model.method462(modelID); if (model == null) return null; if (editedModelColor != null) { for (int l = 0; l < editedModelColor.length; l++) model.method476(editedModelColor[l], newModelColor[l]); } return model; }
22b4d4d9-d718-427e-9d81-355fab5acc6e
7
public static List<Double> changeOfCoords(List<Poi> oldPoiList, List<Poi> newPoiList){ List<Double> changes = new ArrayList<Double>(); HashMap<String, Poi> newPoiMap = new HashMap<String, Poi>(); for (Poi new_poi : newPoiList) { newPoiMap.put(new_poi.getId(), new_poi); } for(Poi old_poi : oldPoiList){ if(old_poi.hasCoord()){ // old POI has coords Poi new_poi = newPoiMap.get(old_poi.getId()); if(new_poi != null){ // and remains in the new quarter if(new_poi.hasCoord()){ // also have coords in the new quarter if( old_poi.getLat() != new_poi.getLat() || old_poi.getLon() != new_poi.getLon()) { // a change in coords System.out.println("old POI : "+ old_poi); System.out.println("new POI : "+ new_poi); changes.add(distance(old_poi.getLat(), old_poi.getLon(), new_poi.getLat(), new_poi.getLon())); } } } } } return changes; }
3f6831aa-6ae6-4e85-807c-bddb731c5aec
2
public Main(){ try{ Display.setDisplayMode(new DisplayMode(800, 500)); Display.setResizable(false); Display.setTitle("Hexagon Mapping"); PixelFormat pf = new PixelFormat().withSamples(4).withDepthBits(24); Display.create(pf); width = 800; height = 500; AL.create(); }catch(LWJGLException e){ e.printStackTrace(); } init(); while(!Display.isCloseRequested()){ render(); Display.sync(60); Display.update(); } Display.destroy(); AL.destroy(); System.exit(0); }
b11bdd55-f81b-4995-99fe-a2e3fcbfcedd
5
public Response serve(IHTTPSession session) { Map<String, String> header = session.getHeaders(); Map<String, String> parms = session.getParms(); String uri = session.getUri(); if (!quiet) { System.out.println(session.getMethod() + " '" + uri + "' "); Iterator<String> e = header.keySet().iterator(); while (e.hasNext()) { String value = e.next(); System.out.println(" HDR: '" + value + "' = '" + header.get(value) + "'"); } e = parms.keySet().iterator(); while (e.hasNext()) { String value = e.next(); System.out.println(" PRM: '" + value + "' = '" + parms.get(value) + "'"); } } for (File homeDir : getRootDirs()) { // Make sure we won't die of an exception later if (!homeDir.isDirectory()) { return createResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "INTERNAL ERRROR: given path is not a directory (" + homeDir + ")."); } } return respond(Collections.unmodifiableMap(header), uri); }
cba5ca9c-9977-4ef1-a178-e5fd73bac30e
1
public void playFanFare() throws InterruptedException{ try { in = new FileInputStream(fanFare); as = new AudioStream(in); ap.player.start(as); } catch(Exception e) { System.out.println("Got an IOException: " + e.getMessage()); e.printStackTrace(); } Thread.sleep(fanFareLen); }
dd0cadf1-daed-4762-9bfd-3dc134e4795f
1
public World getWorld(){ if(server != null)return server.getWorld(); return null; }
286ca07b-0d29-4e91-807c-5426a1ac935d
4
@Override public boolean equals(Object obj) { if(obj == null) { return false; } if(getClass() != obj.getClass()) { return false; } final TerminalPosition other = (TerminalPosition) obj; if(this.row != other.row) { return false; } if(this.column != other.column) { return false; } return true; }
447643d3-9dd9-4864-a4e3-f4274a484fe0
0
public void setCount(int value) { this._count = value; }
8368b1df-6a36-48a6-88aa-3b132c3022b4
5
public static BigInteger check() { for (BigInteger a : primes) { for (BigInteger b : primes) { for (int i = 0; i < 80; i++) { int sum = i * i + a.intValue() * i + b.intValue(); BigInteger test = new BigInteger(String.valueOf(sum)); if (!sprimes.contains(test)) { if (i > max) { max = i; result = a.multiply(b); System.out.println(max); } break; } } } } return result; }
4b9ef6f0-b225-4a98-9ddf-efb171b80d39
3
public static Stack<Integer> sortStack(Stack<Integer> s){ Stack<Integer> r = new Stack<Integer>(); while(!s.isEmpty()){ Integer e = s.pop(); while(!r.isEmpty() && r.peek() > e){ s.push(r.pop()); } r.push(e); } return r; }
b6f92951-700d-46d3-8871-4a7a319cd8f7
1
public static final int GetLenToPosState(int len) { len -= 2; if (len < 4) return len; return 3; }
3ef6623c-1c65-482d-a49f-35c67535dcef
5
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html>\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); out.write(" <title>JSP Page</title>\n"); out.write(" </head>\n"); out.write(" <body>\n"); out.write(" <h1>Hello World!</h1>\n"); out.write(" \n"); out.write(" "); String ruta="src=http://localhost:8090/hhh/tres.jpg" ; out.write("\n"); out.write(" <img "); out.print( ruta ); out.write(" width='250' height='250' >\n"); out.write(" <form action=\"Foto\" method=\"POST\" > \n"); out.write(" \n"); out.write(" <input type=\"text\" name=\"n1\" value=\"\" />\n"); out.write(" <input type=\"text\" name=\"n2\" value=\"\" /> \n"); out.write(" <br> <br>\n"); out.write(" <input type=\"submit\" value=\"Aceptar\" name=\"tipo\"/>\n"); out.write(" <input type=\"submit\" value=\"Cancelar\" name=\"tipo\"/>\n"); out.write(" </form>\n"); out.write(" </body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
184cc62a-0ccd-406a-8d77-e40df74752ac
4
@SuppressWarnings("static-access") @EventHandler(priority = EventPriority.HIGH) public void onMobDeath (EntityDeathEvent event) { Random rand = new Random(); int dropAmount = rand.nextInt(3); Entity entity = event.getEntity(); World world = event.getEntity().getWorld(); if (entity instanceof Zombie) { Zombie wraith = (Zombie) entity; Location wraithLoc = wraith.getLocation(); if (MMWraith.isWraith(wraith)) { try { world.playSound(wraithLoc, Sound.ENDERMAN_SCREAM, 1.0F, - 0.005F); world.createExplosion(wraithLoc, - 1.0F); event.getDrops().clear(); if (entity.getLastDamageCause().getCause().equals(DamageCause.ENTITY_ATTACK)) { ItemMeta meta; ItemStack stack = new ItemStack(Material.SOUL_SAND, dropAmount); meta = (ItemMeta) stack.getItemMeta(); meta.setDisplayName(ChatColor.RED + "Trapped Souls"); meta.addEnchant(Enchantment.ARROW_INFINITE, 10, true); stack.setItemMeta(meta); world.dropItemNaturally(wraithLoc, stack); event.setDroppedExp(15); } } catch (Exception ex) { return; } } } }
d8f7d6f4-fcbf-4557-a8a0-32dcca23b77b
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(test.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 test().setVisible(true); } }); }
7598de40-a9fb-48da-9a7d-527710cd421a
1
public void update() { bgX += speedX; if (bgX <= -2160) { bgX += 4320; } }
6ceed340-8c28-4965-9166-c0c4ebe2ddbb
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SpecificationSubModel other = (SpecificationSubModel) obj; if (featureSpecSet == null) { if (other.featureSpecSet != null) return false; } else if (!featureSpecSet.equals(other.featureSpecSet)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
2d4c3e6b-0824-4cd5-833a-5b595b955e45
0
public void setContent(String content) { this.content = content; }
ab773ce4-1939-4790-a3e1-5f4cfee38af0
3
private void getDataFromEvent(Sim_event ev) { IO_data io = (IO_data) ev.get_data(); // if the sender is not part of the overall network topology // whereas this entity is, then need to return back the data, // since it is not compatible. if (link_ != null) { // outName = "Output_xxx", where xxx = sender entity name String outName = GridSim.getEntityName( ev.get_src() ); // NOTE: this is a HACK job. "Output_" has 7 chars. So, // the idea is to get only the entity name by removing // "Output_" word in the outName string. String name = outName.substring(7); // if the sender is not system GIS then ignore the message if (GridSim.getEntityId(name) != GridSim.getGridInfoServiceEntityId()) { // sends back the data to "Input_xxx", where // xxx = sender entity name. If not sent, then the sender // will wait forever to receive this data. As a result, // the whole simulation program will be hanged or does not // terminate successfully. int id = GridSim.getEntityId("Input_" + name); super.sim_schedule(id, 0.0, ev.get_tag(), io); // print an error message System.out.println(super.get_name() + ".body(): Error - " + "incompatible message protocol."); System.out.println(" Sender: " + name + " is not part " + "of this entity's network topology."); System.out.println(" Hence, sending back the received data."); System.out.println(); return; } } // NOTE: need to have a try-catch statement. This is because, // if the above if statement holds, then Input_receiver will send // back to Input_sender without going through Output_receiver entity. // Hence, a try-catch is needed to prevent exception of wrong casting. try { // Simulate Transmission Time after Receiving // Hold first then dispatch double senderBaudRate = ( (Output) Sim_system.get_entity(ev.get_src()) ).getBaudRate(); // NOTE: io is in byte and baud rate is in bits. 1 byte = 8 bits // So, convert io into bits double minBaudRate = Math.min(baudRate_, senderBaudRate); double communicationDelay = GridSimRandom.realIO( (io.getByteSize() * NetIO.BITS) / minBaudRate); // NOTE: Below is a deprecated method for SimJava 2 //super.sim_hold(communicationDelay); super.sim_process(communicationDelay); // receiving time } catch (Exception e) { // .... empty } // Deliver Event to the entity (its parent) to which // it is acting as buffer super.sim_schedule( inPort_, GridSimTags.SCHEDULE_NOW, ev.get_tag(), io.getData() ); }
a308233a-cda4-4a0f-82d8-90640729317d
4
public static void renderNormalBlock(float x, float y, float z, boolean clear, int id, int rendermode) { // GL11.glTranslatef(x, y, z); if (clear) { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); GL11.glLoadIdentity(); }// GL20.glUseProgram(0); if (id == 1) { // GL11.glColor3f(0.2f, 1.0f, 0.3f); } else if (id == 2) { // GL11.glColor3f(0.5f, 0.5f, 0.5f); } // Bind the texture // GL13.glActiveTexture(GL13.GL_TEXTURE0); // System.out.println(texIds[id]); GL11.glBindTexture(GL11.GL_TEXTURE_2D, id); if (!GL11.glIsEnabled(GL11.GL_CULL_FACE)) { GL11.glEnable(GL11.GL_CULL_FACE); } // displayListSolid = GL11.glGenLists(1); // GL11.glNewList(displayListSolid, GL11.GL_COMPILE); //GL11.glBegin(GL11.GL_QUADS); GL11.glBegin(rendermode); GL11.glColor3f(1.0f, 1.0f, 1.0f); GL11.glNormal3f(0, 1, 0); GL11.glTexCoord2d(0.0f, 0.0f); GL11.glVertex3f(1.0f + x, 1.0f + y, -1.0f + z); GL11.glTexCoord2d(1.0f, 0.0f); GL11.glVertex3f(-1.0f + x, 1.0f + y, -1.0f + z); GL11.glTexCoord2d(1.0f, 1.0f); GL11.glVertex3f(-1.0f + x, 1.0f + y, 1.0f + z); GL11.glTexCoord2d(0.0f, 1.0f); GL11.glVertex3f(1.0f + x, 1.0f + y, 1.0f + z); GL11.glNormal3f(0, -1, 0); GL11.glColor3f(0.35f, 0.35f, 0.35f); GL11.glTexCoord2d(0.0f, 0.0f); GL11.glVertex3f(1.0f + x, -1.0f + y, 1.0f + z); GL11.glTexCoord2d(1.0f, 0.0f); GL11.glVertex3f(-1.0f + x, -1.0f + y, 1.0f + z); GL11.glTexCoord2d(1.0f, 1.0f); GL11.glVertex3f(-1.0f + x, -1.0f + y, -1.0f + z); GL11.glTexCoord2d(0.0f, 1.0f); GL11.glVertex3f(1.0f + x, -1.0f + y, -1.0f + z); GL11.glNormal3f(0, 0, 1); GL11.glColor3f(0.8f, 0.8f, 0.8f); GL11.glTexCoord2d(0.0f, 0.0f); GL11.glVertex3f(1.0f + x, 1.0f + y, 1.0f + z); GL11.glTexCoord2d(1.0f, 0.0f); GL11.glVertex3f(-1.0f + x, 1.0f + y, 1.0f + z); GL11.glTexCoord2d(1.0f, 1.0f); GL11.glVertex3f(-1.0f + x, -1.0f + y, 1.0f + z); GL11.glTexCoord2d(0.0f, 1.0f); GL11.glVertex3f(1.0f + x, -1.0f + y, 1.0f + z); GL11.glNormal3f(0, 0, -1); GL11.glColor3f(0.5f, 0.5f, 0.5f); GL11.glTexCoord2d(1.0f, 1.0f); GL11.glVertex3f(1.0f + x, -1.0f + y, -1.0f + z); GL11.glTexCoord2d(0.0f, 1.0f); GL11.glVertex3f(-1.0f + x, -1.0f + y, -1.0f + z); GL11.glTexCoord2d(0.0f, 0.0f); GL11.glVertex3f(-1.0f + x, 1.0f + y, -1.0f + z); GL11.glTexCoord2d(1.0f, 0.0f); GL11.glVertex3f(1.0f + x, 1.0f + y, -1.0f + z); GL11.glNormal3f(1, 0, 0); GL11.glColor3f(0.6f, 0.6f, 0.6f); GL11.glTexCoord2d(0.0f, 0.0f); GL11.glVertex3f(-1.0f + x, 1.0f + y, 1.0f + z); GL11.glTexCoord2d(1.0f, 0.0f); GL11.glVertex3f(-1.0f + x, 1.0f + y, -1.0f + z); GL11.glTexCoord2d(1.0f, 1.0f); GL11.glVertex3f(-1.0f + x, -1.0f + y, -1.0f + z); GL11.glTexCoord2d(0.0f, 1.0f); GL11.glVertex3f(-1.0f + x, -1.0f + y, 1.0f + z); GL11.glNormal3f(-1, 0, 0); GL11.glColor3f(0.7f, 0.7f, 0.7f); GL11.glTexCoord2d(0.0f, 0.0f); GL11.glVertex3f(1.0f + x, 1.0f + y, -1.0f + z); GL11.glTexCoord2d(1.0f, 0.0f); GL11.glVertex3f(1.0f + x, 1.0f + y, 1.0f + z); GL11.glTexCoord2d(1.0f, 1.0f); GL11.glVertex3f(1.0f + x, -1.0f + y, 1.0f + z); GL11.glTexCoord2d(0.0f, 1.0f); GL11.glVertex3f(1.0f + x, -1.0f + y, -1.0f + z); GL11.glEnd(); //GL11.glEndList(); //GL11.glPolygonMode(GL11.GL_FRONT, GL11.GL_FILL); /*float size = 1.0F; GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2d(0.0f * size, 0.0f * size); GL11.glVertex3f(-1.0f * size, -1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 0.0f * size); GL11.glVertex3f(1.0f * size, -1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 1.0f * size); GL11.glVertex3f(1.0f * size, 1.0f * size, 1.0f * size); GL11.glTexCoord2d(0.0f * size, 1.0f * size); GL11.glVertex3f(-1.0f * size, 1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 0.0f * size); GL11.glVertex3f(-1.0f * size, -1.0f * size, -1.0f * size); GL11.glTexCoord2d(1.0f * size, 1.0f * size); GL11.glVertex3f(-1.0f * size, 1.0f * size, -1.0f * size); GL11.glTexCoord2d(0.0f * size, 1.0f * size); GL11.glVertex3f(1.0f * size, 1.0f * size, -1.0f * size); GL11.glTexCoord2d(0.0f * size, 0.0f * size); GL11.glVertex3f(1.0f * size, -1.0f * size, -1.0f * size); GL11.glTexCoord2d(0.0f * size, 1.0f * size); GL11.glVertex3f(-1.0f * size, 1.0f * size, -1.0f * size); GL11.glTexCoord2d(0.0f * size, 0.0f * size); GL11.glVertex3f(-1.0f * size, 1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 0.0f * size); GL11.glVertex3f(1.0f * size, 1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 1.0f * size); GL11.glVertex3f(1.0f * size, 1.0f * size, -1.0f * size); GL11.glTexCoord2d(1.0f * size, 1.0f * size); GL11.glVertex3f(-1.0f * size, -1.0f * size, -1.0f * size); GL11.glTexCoord2d(0.0f * size, 1.0f * size); GL11.glVertex3f(1.0f * size, -1.0f * size, -1.0f * size); GL11.glTexCoord2d(0.0f * size, 0.0f * size); GL11.glVertex3f(1.0f * size, -1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 0.0f * size); GL11.glVertex3f(-1.0f * size, -1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 0.0f * size); GL11.glVertex3f(1.0f * size, -1.0f * size, -1.0f * size); GL11.glTexCoord2d(1.0f * size, 1.0f * size); GL11.glVertex3f(1.0f * size, 1.0f * size, -1.0f * size); GL11.glTexCoord2d(0.0f * size, 1.0f * size); GL11.glVertex3f(1.0f * size, 1.0f * size, 1.0f * size); GL11.glTexCoord2d(0.0f * size, 0.0f * size); GL11.glVertex3f(1.0f * size, -1.0f * size, 1.0f * size); GL11.glTexCoord2d(0.0f * size, 0.0f * size); GL11.glVertex3f(-1.0f * size, -1.0f * size, -1.0f * size); GL11.glTexCoord2d(1.0f * size, 0.0f * size); GL11.glVertex3f(-1.0f * size, -1.0f * size, 1.0f * size); GL11.glTexCoord2d(1.0f * size, 1.0f * size); GL11.glVertex3f(-1.0f * size, 1.0f * size, 1.0f * size); GL11.glTexCoord2d(0.0f * size, 1.0f * size); GL11.glVertex3f(-1.0f * size, 1.0f * size, -1.0f * size); GL11.glEnd();*/ }
356ce56b-a466-4854-9f19-8c6e1fb0e4a3
0
public void setEventName(String eventName) { this.eventName = eventName; }
340fe41c-15a6-461e-bf90-e6e17c0def90
0
public void addAdj(TrieNode node){ adj[getIndex(node.ch)]=node; }
49b5b385-c4e8-4751-bd68-11c688409391
6
@Test public void testNull() { RedBlackTree<Integer> tree = new RedBlackTree<Integer>(); try { tree.insert(null); Assert.fail(); } catch (NullPointerException e) { } try { tree.getPredecessor(null); Assert.fail(); } catch (NullPointerException e) { } try { tree.getSuccessor(null); Assert.fail(); } catch (NullPointerException e) { } Assert.assertNull(tree.delete(null)); Assert.assertNull(tree.getNode(null)); Assert.assertFalse(tree.contains(null)); tree.insert(0); try { tree.insert(null); Assert.fail(); } catch (NullPointerException e) { } try { tree.getPredecessor(null); Assert.fail(); } catch (NullPointerException e) { } try { tree.getSuccessor(null); Assert.fail(); } catch (NullPointerException e) { } Assert.assertNull(tree.delete(null)); Assert.assertNull(tree.getNode(null)); Assert.assertFalse(tree.contains(null)); }
1db79bc6-2660-4334-a6ae-341f738606cc
2
public void replaceCards(Card oldCard, Card newCard){ // We need to find the index of the old card for(int i = 0; i < this.cards.size(); i++) { if(this.cards.get(i).equals(oldCard)) { // Set the new object this.cards.set(i, newCard); } } }
f4ade8f7-4103-4c67-845b-b142e20c792c
4
public static void main(String[] args) throws InterruptedException { Thread.currentThread().setName("Startup"); try { LOG.info("The \"Java GWCAConstants\" (version {}) is starting", Version.getVersion()); addShutdownHook(); // Fill in the PID here gwcaConnection = new NamedPipeGWCAConnection(new File("\\\\.\\pipe\\GWCA_" + 4252)); gwcaConnection.open(); UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // open jframe with some combobox and stuff JFrame window = new JFrame("JGWCACommander"); window.setSize(325, 140); window.setResizable(false); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setLayout(null); // make sure the window appears in the middle of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int w = window.getSize().width; int h = window.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; window.setLocation(x, y); window.setVisible(true); cb = new JComboBox(GWCAOperation.values()); cb.setBounds(5, 5, 310, 25); window.getContentPane().add(cb); wTextField = new JTextField(); wTextField.setBounds(5, 35, 155, 25); window.getContentPane().add(wTextField); lTextField = new JTextField(); lTextField.setBounds(5, 60, 155, 25); window.getContentPane().add(lTextField); wLabel = new JLabel(); wLabel.setBounds(170, 35, 145, 25); window.getContentPane().add(wLabel); lLabel = new JLabel(); lLabel.setBounds(170, 60, 145, 25); window.getContentPane().add(lLabel); JButton sendButton = new JButton("Send"); sendButton.setBounds(5, 85, 105, 25); window.getContentPane().add(sendButton); cbType = new JComboBox(new String[]{HEX, FLOAT, INT}); cbType.setBounds(230, 85, 100, 25); window.getContentPane().add(cbType); sendButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { send(); } }); JButton sendAndReceiveButton = new JButton("Send & Receive"); sendAndReceiveButton.setBounds(110, 85, 105, 25); window.getContentPane().add(sendAndReceiveButton); sendAndReceiveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { send(); receive(); } }); window.repaint(); //cb.getSelectedItem(); LOG.info("The \"Java GWCAConstants\" started"); while (true) { Thread.sleep(Long.MAX_VALUE); } } catch (Throwable throwable) { LOG.error("Initializing the \"Java GWCAConstants\" failed because: ", throwable); } finally { try { if (gwcaConnection != null) { gwcaConnection.close(); } } catch (IOException ex) { LOG.warn("Failed to close the connection: ", ex); } } }
6b888bda-ec47-4c44-a0da-887feb854ffe
3
@Override public Set<Election> getNominationsForUser(User user) { Set<Election> electionsNominated = new HashSet<Election>(); Collection<Election> col = electionMap.values(); Iterator<Election> it = col.iterator(); while (it.hasNext()) { DnDElection el = (DnDElection) it.next(); if (el.getElectionState() == ElectionState.NOMINATIONS_OPEN && el.getNomineeSet().contains(user)) electionsNominated.add(el); } return electionsNominated; }
6e74a75f-dbe2-4b3a-a929-8d51c0f6bc95
0
public double[] getBbox() { return bbox; }
f4a8bcd7-a77f-4ae4-ac08-b4c223da9f70
1
private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } }
59b8493a-74ce-42c2-9bb3-a9f04ba65f77
3
public static int hashCode(final Node node) { class Int { int value = 0; } ; final Int hash = new Int(); node.visit(new TreeVisitor() { public void visitExprStmt(final ExprStmt stmt) { hash.value = 1; } public void visitIfCmpStmt(final IfCmpStmt stmt) { hash.value = stmt.comparison() + stmt.trueTarget().hashCode() + stmt.falseTarget().hashCode(); } public void visitIfZeroStmt(final IfZeroStmt stmt) { hash.value = stmt.comparison() + stmt.trueTarget().hashCode() + stmt.falseTarget().hashCode(); } public void visitInitStmt(final InitStmt stmt) { hash.value = 2; } public void visitGotoStmt(final GotoStmt stmt) { hash.value = stmt.target().hashCode(); } public void visitLabelStmt(final LabelStmt stmt) { hash.value = stmt.label().hashCode(); } public void visitMonitorStmt(final MonitorStmt stmt) { hash.value = stmt.kind(); } public void visitPhiJoinStmt(final PhiJoinStmt stmt) { hash.value = 3; } public void visitPhiCatchStmt(final PhiCatchStmt stmt) { hash.value = 4; } public void visitCatchExpr(final CatchExpr expr) { // Catches are not equivalent. hash.value = expr.hashCode(); } public void visitStackManipStmt(final StackManipStmt stmt) { hash.value = stmt.kind(); } public void visitRetStmt(final RetStmt stmt) { hash.value = 5; } public void visitReturnExprStmt(final ReturnExprStmt stmt) { hash.value = 6; } public void visitReturnStmt(final ReturnStmt stmt) { hash.value = 7; } public void visitAddressStoreStmt(final AddressStoreStmt stmt) { hash.value = 8; } public void visitStoreExpr(final StoreExpr expr) { hash.value = 9; } public void visitJsrStmt(final JsrStmt stmt) { hash.value = 10; } public void visitSwitchStmt(final SwitchStmt stmt) { hash.value = 11; } public void visitThrowStmt(final ThrowStmt stmt) { hash.value = 12; } public void visitArithExpr(final ArithExpr expr) { hash.value = expr.operation(); } public void visitArrayLengthExpr(final ArrayLengthExpr expr) { hash.value = 13; } public void visitArrayRefExpr(final ArrayRefExpr expr) { hash.value = 14; } public void visitCallMethodExpr(final CallMethodExpr expr) { // Calls are never equal. hash.value = expr.hashCode(); } public void visitCallStaticExpr(final CallStaticExpr expr) { // Calls are never equal. hash.value = expr.hashCode(); } public void visitCastExpr(final CastExpr expr) { hash.value = expr.castType().hashCode(); } public void visitConstantExpr(final ConstantExpr expr) { if (expr.value() == null) { hash.value = 0; } else { hash.value = expr.value().hashCode(); } } public void visitFieldExpr(final FieldExpr expr) { hash.value = expr.field().hashCode(); } public void visitInstanceOfExpr(final InstanceOfExpr expr) { hash.value = expr.checkType().hashCode(); } public void visitLocalExpr(final LocalExpr expr) { if (expr.def() != null) { hash.value = expr.def().hashCode(); } else { hash.value = 0; } } public void visitNegExpr(final NegExpr expr) { hash.value = 16; } public void visitNewArrayExpr(final NewArrayExpr expr) { hash.value = expr.hashCode(); } public void visitNewExpr(final NewExpr expr) { hash.value = expr.hashCode(); } public void visitNewMultiArrayExpr(final NewMultiArrayExpr expr) { hash.value = expr.hashCode(); } public void visitZeroCheckExpr(final ZeroCheckExpr expr) { hash.value = 15; } public void visitRCExpr(final RCExpr expr) { hash.value = 17; } public void visitUCExpr(final UCExpr expr) { hash.value = 18 + expr.kind(); } public void visitReturnAddressExpr(final ReturnAddressExpr expr) { hash.value = 21; } public void visitSCStmt(final SCStmt stmt) { hash.value = 23; } public void visitSRStmt(final SRStmt stmt) { hash.value = 22; } public void visitShiftExpr(final ShiftExpr expr) { hash.value = expr.dir(); } public void visitStackExpr(final StackExpr expr) { if (expr.def() != null) { hash.value = expr.def().hashCode(); } else { hash.value = 0; } } public void visitStaticFieldExpr(final StaticFieldExpr expr) { hash.value = expr.field().hashCode(); } public void visitNode(final Node node) { throw new RuntimeException("No method for " + node); } }); return hash.value; }
ddb28d7a-f804-4cf6-806d-bb0f09a42398
0
public String toString(String input) { return name + calc(input); }
6addc850-e5c9-46c8-9789-1d0663ddd63d
7
public static boolean handle(SyncSettings settings) throws UnknownHostException, IOException { HttpRequestor rq = settings.getRequestorFor(SyncPage.NEW); Request r = rq.getRequest(); buildRequest(settings, r); // only actually request if necessary int minSize = settings.isUsingPassword() ? 1 : 0; if (r.getPostVars().size() > minSize) { Response resp = rq.request(); VariableList vars = new VariableList(); Request.parseUrlEncodedVars(resp.getBody(), vars); // TODO consider users exists error w/ --join option if (vars.isSet("error")) { // go ahead and stop everything... this is probably // a client-side input error StaticMessageHandler.getInstance().setBody( "Synchronization returned the following error: " + vars.getValue("error") ); StaticMessageHandler.getInstance().setRefresh(null); return false; } // success! do what the server tells us ;) if (vars.isSet("uo")) { // update user ids ListVariable oldIds = (ListVariable) vars.get("uo"); ListVariable newIds = (ListVariable) vars.get("un"); if (oldIds.size() != newIds.size()) { System.out.println("Failed: user id count mismatch] "); return true; } // build the correct data type Profile.getInstance().updateUserIds( buildIdDataList(oldIds, newIds) ); } if (vars.isSet("so")) { // update series ids ListVariable oldIds = (ListVariable) vars.get("so"); ListVariable newIds = (ListVariable) vars.get("sn"); if (oldIds.size() != newIds.size()) { System.out.println("Failed: series id count mismatch] "); return true; } Profile.getInstance().updateSeriesIds( buildIdDataList(oldIds, newIds) ); } } // we successfully sync'd; save the date Profile.getInstance().updateSyncTime(SyncPage.NEW); return true; }
c827578b-6ea2-4709-b929-a240b5f4137c
2
public void uglyjoglhack() throws InterruptedException { try { rdr = true; display(); } catch (GLException e) { if (e.getCause() instanceof InterruptedException) { throw ((InterruptedException) e.getCause()); } else { e.printStackTrace(); throw (e); } } finally { rdr = false; } }
cb10aa0f-56d8-4afb-b639-bf962702e49b
1
private static void postOrderTraversal(Node root) { if (root == null) return; postOrderTraversal(root.left); postOrderTraversal(root.right); System.out.println(root.v); }
d63364fe-28e6-484c-b88c-421bffded83d
8
private boolean edge_adj(Edge e1,Edge e2) { if(e1.source.getId()==e2.source.getId() && e1.target.getId()==e2.target.getId()) return false; else if(e1.target.getId()==e2.source.getId() && e1.source.getId()==e2.target.getId()) return false; else if(e1.source.getId() == e2.source.getId()) return true; else if(e1.source.getId() == e2.target.getId()) return true; else if(e1.target.getId() == e2.source.getId()) return true; else if(e1.target.getId() == e2.target.getId()) return true; return false; }
2d23b1a1-c7aa-4cbb-bea5-f84057c0e725
2
private boolean validCommand(String command) { String[][] items = this.menuItems; for (String[] item : this.menuItems) { if (item[0].equals(command)) { return true; } } return false; }
1facfe9e-f63b-4656-a84d-fea1dbe538c5
3
public boolean hasTransitionsInCorrectForm(Automaton automaton) { Transition[] transitions = automaton.getTransitions(); for (int k = 0; k < transitions.length; k++) { if (!isPushLambdaTransition(transitions[k]) && !isPushTwoTransition(transitions[k])) { return false; } } return true; }
4de39a46-7b41-4128-a716-48adbd7a49d9
5
public void write(){ try { log.info("Writing to "+ to +" file"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("highscores"); doc.appendChild(rootElement); int size = list.size()<=5 ? list.size() : 5; for(int i=0;i<size;i++){ Element highscore = doc.createElement("highscore"); rootElement.appendChild(highscore); Element name = doc.createElement("name"); name.appendChild(doc.createTextNode(list.get(i).getName())); highscore.appendChild(name); String tmp = list.get(i).getMoney() + ""; Element money = doc.createElement("money"); money.appendChild(doc.createTextNode(tmp)); highscore.appendChild(money); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); String home=System.getProperty("user.home"); File prop = new File(home, ".roulettegame"); prop.mkdir(); StreamResult result = new StreamResult(new File(prop,to)); transformer.transform(source, result); log.info("Writing successful"); } catch (ParserConfigurationException e) { log.error("ParserConfigurationException caught"); log.error(e.toString()); } catch(TransformerConfigurationException e){ log.error("TransformerConfigurationException caught"); log.error(e.toString()); } catch(TransformerException e){ log.error("TransformerException caught"); log.error(e.toString()); } }
cc1111fd-cc36-4505-a607-52fdedc4aa2b
9
protected boolean fireAndHandleEvent(WordTokenizer tokenizer, SpellCheckEvent event) { fireSpellCheckEvent(event); String word = event.getInvalidWord(); //Work out what to do in response to the event. switch (event.getAction()) { case SpellCheckEvent.INITIAL: break; case SpellCheckEvent.IGNORE: break; case SpellCheckEvent.IGNOREALL: ignoreAll(word); break; case SpellCheckEvent.REPLACE: tokenizer.replaceWord(event.getReplaceWord()); break; case SpellCheckEvent.REPLACEALL: String replaceAllWord = event.getReplaceWord(); if (!autoReplaceWords.containsKey(word)) { autoReplaceWords.put(word, replaceAllWord); } tokenizer.replaceWord(replaceAllWord); break; case SpellCheckEvent.ADDTODICT: String addWord = event.getReplaceWord(); if (!addWord.equals(word)) tokenizer.replaceWord(addWord); userdictionary.addWord(addWord); break; case SpellCheckEvent.CANCEL: return true; default: throw new IllegalArgumentException("Unhandled case."); } return false; }
e0b5ba3f-f75f-4d46-9e92-8345532fee4c
9
private void postPlugin(final boolean isPing) throws IOException { // The plugin's description file containg all of the plugin data such as name, version, author, etc final PluginDescriptionFile description = plugin.getDescription(); // Construct the post data final StringBuilder data = new StringBuilder(); data.append(encode("guid")).append('=').append(encode(guid)); encodeDataPair(data, "version", description.getVersion()); encodeDataPair(data, "server", Bukkit.getVersion()); encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); encodeDataPair(data, "revision", String.valueOf(REVISION)); // If we're pinging, append it if (isPing) { encodeDataPair(data, "ping", "true"); } // Acquire a lock on the graphs, which lets us make the assumption we also lock everything // inside of the graph (e.g plotters) synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); // Because we have a lock on the graphs set already, it is reasonable to assume // that our lock transcends down to the individual plotters in the graphs also. // Because our methods are private, no one but us can reasonably access this list // without reflection so this is a safe assumption without adding more code. for (Plotter plotter : graph.getPlotters()) { // The key name to send to the metrics server // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); // The value to send, which for the foreseeable future is just the string // value of plotter.getValue() final String value = Integer.toString(plotter.getValue()); // Add it to the http post data :) encodeDataPair(data, key, value); } } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName()))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data.toString()); writer.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response == null || response.startsWith("ERR")) { throw new IOException(response); //Throw the exception } else { // Is this the first update this hour? if (response.contains("OK This is your first update this hour")) { synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right }
1e62ae26-99fd-4a74-bc89-68af497241af
7
public byte[] extractFile(FAT32DIRElement f32DIRElement) { int countFileClusters = 0; if (f32DIRElement.getDIR_FileSize() < BPB_BytsPerSec) { countFileClusters = 1; } else { countFileClusters = f32DIRElement.getDIR_FileSize() / BPB_BytsPerSec + 1; } //счетчик кластеров файла для правильной записи байтов в выходной массив bytesOfF32DIRElement int c = 0; bytesOfF32DIRElement = new byte[BPB_BytsPerSec * countFileClusters]; // считывание первый кластер файла byte[] bTemp = readCluster(f32DIRElement.getDIR_FstClusFULL()); for (int i = 0; i < BPB_BytsPerSec; i++) { bytesOfF32DIRElement[i + c * BPB_BytsPerSec] = bTemp[i]; } // вычисление смещения в таблице FAT calcThisFATEntOffset(f32DIRElement.getDIR_FstClusFULL()); byte[] bCheckEOF = new byte[4]; int beginOffset = thisFATSecNum * BPB_BytsPerSec + thisFATEntOffset; int endOffset = thisFATSecNum * BPB_BytsPerSec + thisFATEntOffset + 4; for (int j = beginOffset; j < endOffset; j++) { bCheckEOF[j - beginOffset] = imageBytes[j]; } int resultEOF = byteArrayToInt(bCheckEOF); // если кластер не последний то продолжаем искать кластеры по таблице FAT // и записывать их в выходной массив байтов bytesOfF32DIRElement if (resultEOF < 0x0FFFFFFF) { do { c++; bTemp = readCluster(resultEOF); for (int i = 0; i < BPB_BytsPerSec; i++) { bytesOfF32DIRElement[i + c * BPB_BytsPerSec] = bTemp[i]; } calcThisFATEntOffset(resultEOF); bCheckEOF = new byte[4]; beginOffset = thisFATSecNum * BPB_BytsPerSec + thisFATEntOffset; endOffset = thisFATSecNum * BPB_BytsPerSec + thisFATEntOffset + 4; for (int j = beginOffset; j < endOffset; j++) { bCheckEOF[j - beginOffset] = imageBytes[j]; } resultEOF = byteArrayToInt(bCheckEOF); } while (resultEOF < 0x0FFFFFFF); } return bytesOfF32DIRElement; }
6f2cd92c-6e08-462c-b886-4c769120fcfa
2
public int getDividerMaximum() { if (isFull()) { return Math.max((mHorizontal ? mWidth : mHeight) - Dock.DIVIDER_SIZE, 0); } return 0; }
e7e5012a-9fe2-439c-90b7-7d505b0ad1bc
4
public void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) { if (semiMajorAxis < 0) throw new RuntimeException("ellipse semimajor axis can't be negative"); if (semiMinorAxis < 0) throw new RuntimeException("ellipse semiminor axis can't be negative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*semiMajorAxis); double hs = factorY(2*semiMinorAxis); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); }
e4114db0-0297-4bb4-80ba-4e15be785265
4
public void closePromoteConnection(){ try { //Rollback any outstanding transactions - there shouldn't be any, so this is probably an internal mistake //If this rollback isn't performed, closing the connection issues a commit which is potentially dangerous if(isTransactionActive(mPromoteConnection)){ mPromoteConnection.rollback(); Logger.logWarning("Uncommitted data detected on promote connection - rolling back"); } mPromoteConnection.close(); if(mSysDBAPromoteConnection != null){ //Clean up the SYSDBA connection if it was created if(isTransactionActive(mSysDBAPromoteConnection)){ mSysDBAPromoteConnection.rollback(); Logger.logWarning("Uncommitted data detected on promote SYSDBA connection - rolling back"); } mSysDBAPromoteConnection.close(); } } catch (SQLException e) { throw new ExFatalError("Error when disconnecting from database promote connection", e); } }
1d10cda0-0e07-4814-9c85-7c916a38da7d
0
public ArrayList<Account> pay(Account seller, String amount, Account buyer) { buyer.pay(amount); seller.receive(amount); ArrayList<Account> accounts = new ArrayList<Account>(); accounts.add(buyer); accounts.add(seller); return accounts; }
b96ad5ad-074b-4bff-a0ef-d427e3a9491e
9
public void addYoungerLab(){ TD tD1 = new TD(1); TD tD2 = new TD(2); TD tD3 = new TD(3); if(!this.getListofLabs().containsKey(1) && this.getListoflessons().containsKey(1)){ this.getListofLabs().put(1, tD1); System.out.println("You attended the first lab."); }else if(!this.getListofLabs().containsKey(2) && this.getListoflessons().containsKey(2)){ this.getListofLabs().put(2, tD2); System.out.println("You attended the second lab."); }else if(!this.getListofLabs().containsKey(3) && this.getListoflessons().containsKey(3)){ this.getListofLabs().put(3, tD3); System.out.println("You attended the third lab."); }else if(this.getListoflessons().containsKey(1) && this.getListoflessons().containsKey(2) && this.getListoflessons().containsKey(3)){ System.out.println("You already have attended to all OOP labs, the exam is waiting for you."); }else { System.out.println("You can't assist to this OOP lab session, you don't have the associated lesson."); } }
938f7197-824a-4281-8854-283908e9adc3
3
public void moveLeft() { if (units1.size() == 6) { QMessageBox.warning(this, "Nie można przenieść jednostek", "Bohater może mieć maksymalnie 6 jednostek"); } else if (units2.size() == 0) { QMessageBox.warning(this, "Nie można przenieść jednostek", "Bohater nie ma żadnych jednostek"); } else if (list2.currentRow() == -1) { QMessageBox.warning(this, "Nie można przenieść jednostek", "Nie wybrano jednostki"); } else { core.GroupOfUnits unit = units2.get(list2.currentRow()); unit.setOwner(hero1); addUnit(unit, units1, list1); units2.remove(list2.currentRow()); list2.takeItem(list2.currentRow()); } }
bc7edf77-85db-4d6e-9149-3d525ad6a4b7
8
@Override public void startBehavior(PhysicalAgent forMe) { if((forMe!=null)&&(forMe instanceof MOB)) { if(stomachR==null) stomachR = CMClass.getLocale("StdRoom"); lastKnownEaterM=(MOB)forMe; lastKnownLocationR=((MOB)forMe).location(); if(lastKnownLocationR!=null) stomachR.setArea(lastKnownLocationR.getArea()); stomachR.setDisplayText(L("The Stomach of @x1",forMe.name())); stomachR.setName(L("the stomach of @x1",forMe.name())); stomachR.setDescription(L("You are in the stomach of @x1. It is wet with digestive acids, and the walls are grinding you to a pulp. You have been Swallowed whole and are being digested.",forMe.name())); stomachR.addNonUninvokableEffect(CMClass.getAbility("Prop_NoRecall")); stomachR.addNonUninvokableEffect(CMClass.getAbility("Prop_NoTeleportOut")); final ExtendableAbility A=(ExtendableAbility)CMClass.getAbility("ExtAbility"); final WeakReference<MOB> eater=new WeakReference<MOB>(lastKnownEaterM); stomachR.addNonUninvokableEffect(A.setAbilityID("MOBEaterStomachWatcher").setMsgListener(new MsgListener(){ @Override public void executeMsg(Environmental myHost, CMMsg msg) { if(A.affecting() instanceof Room) { if((eater.get()==null)||(eater.get().amDestroyed())||(eater.get().amDead())) { CMLib.map().emptyRoom((Room)A.affecting(), null, true); } } } @Override public boolean okMessage(Environmental myHost, CMMsg msg) { return true; } })); } }
081fc9ab-3383-490e-80ca-3553881dc26d
7
public static final boolean checkTrashOkazari(Body b) { if(b.hasOkazari()) return false; if(b.isVerySad()) return false; Obj found = null; int minDistance = b.getEyesight(); int wallMode = b.getAgeState().ordinal(); // 飛行可能なら壁以外は通過可能 if(b.canflyCheck()) { wallMode = AgeState.ADULT.ordinal(); } for (ObjEX t: Trash.objEXList) { int distance = Translate.distance(b.getX(), b.getY(), t.getX(), t.getY() - t.getH()/6); if (minDistance > distance) { if (Terrarium.acrossBarrier(b.getX(), b.getY(), t.getX(), t.getY() - t.getH()/6, Terrarium.MAP_BODY[wallMode])) { continue; } found = t; minDistance = distance; } } if (found != null) { EventLogic.addBodyEvent(b, new GetTrashOkazariEvent(b, null, found, 1), null, null); return true; } return false; }
807e0008-9b1c-4a54-b58c-7e76d594ca75
2
public static Vector<Place> getPlacesDisponibles (String numS, String date) throws BDException { Vector<Place> res = new Vector<Place>(); String requete = "select norang, noplace, numz from lesplaces MINUS select lestickets.norang, lestickets.noplace, numz from LesTickets, lesplaces where lestickets.noplace = lesplaces.noplace and lestickets.norang=lesplaces.norang and numS = "+numS+" and dateRep = to_date('"+date+"','dd/mm/yyyy hh24:mi') ORDER BY norang, noplace"; Statement stmt = null; ResultSet rs = null; Connection conn = null; try { conn = BDConnexion.getConnexion(); BDRequetesTest.testRepresentation(conn, numS, date); stmt = conn.createStatement(); rs = stmt.executeQuery(requete); while (rs.next()) { res.addElement(new Place(rs.getInt(1), rs.getInt(2), rs.getInt(3))); } } catch (SQLException e) { throw new BDException("Problème dans l'interrogation des places (Code Oracle : "+e.getErrorCode()+")"); } finally { BDConnexion.FermerTout(conn, stmt, rs); } return res; }
b02b2209-2f9b-4b08-9f39-d813834c05f4
7
public void viewAccepted(View view) { if(bridge_view != null && bridge_view.getViewId().equals(view.getViewId())) return; int prev_members=bridge_view != null? bridge_view.size() : 0; bridge_view=view; switch(view.size()) { case 1: // the remote cluster disappeared, remove all of its addresses from the view if(prev_members > 1 && view.getMembers().iterator().next().equals(bridge.getAddress())) { remote_view=null; View new_global_view=generateGlobalView(local_view, null); sendViewOnLocalCluster(null, new_global_view, false, null); } break; case 2: startRemoteViewFetcher(); break; default: // System.err.println("View size of > 2 is invalid: view=" + view); break; } }
b7376c69-0995-40a3-80f5-9fa9a7f4a72d
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(pharmacie_modifier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(pharmacie_modifier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(pharmacie_modifier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(pharmacie_modifier.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 pharmacie_modifier().setVisible(true); } }); }
b42b802f-0fe8-4764-ad6c-fe52df23fcdc
0
@Override public int attack(double agility, double luck) { System.out.println("I tried to do a special attack but I haven't set it so I failed at this turn..."); return 0; }
ba06c355-fdc2-4669-9f24-2c9cd367cbcf
3
protected void loadPrestigeList(){ //print all prestige buttons prestigeContainer.clear(); for(int classId : DDOCharacter.getTakenClasses()){//loop over all possible prestige classes if(DDOCharacter.prestigeToClassMap.containsValue(classId)){ //check to see if there is any valid Set<String> prestigeSet = getKeysByValue(DDOCharacter.prestigeToClassMap, classId);//fetch those who match our classes for(String prestige : prestigeSet){ new PrestigeTitle(prestige, prestigeContainer); //add them to the ui } } } }
39373843-0ba5-4e80-bd09-dbe7ced98022
2
public boolean vaincu(){ int actifs = 0; for (int i=0; i<recensement(); i++) if (!soldats[i].estMort()) return(false); return(true); }
7f60bd76-459a-4499-8751-1726e736b9ae
9
public void update() throws SteamCondenserException, TimeoutException { SourceServer ss = new SourceServer(sock.getAddress(), sock.getPort()); Map<String, Object> info = ss.getServerInfo(); Map<String, String> rules = ss.getRules(); Map<String, SteamPlayer> players = ss.getPlayers(); Map<String, Object> maps = new HashMap<String, Object>(); maps.put("ping", ss.getPing()); maps.put("info", info); maps.put("rules", ss.getRules()); maps.put("players", ss.getPlayers()); StringBuilder sb = new StringBuilder().append("\n"); String ln = "------------------------------------------------------------------------\n"; sb.append(ln); sb.append(this.toString().toUpperCase()).append("\n"); sb.append(ln); for (Map.Entry<String, Object> entry : maps.entrySet()) { sb.append(ln); String k = entry.getKey(); Object v = entry.getValue(); if (v instanceof Map) { Map<?, ?> m = ((Map<?, ?>) v); sb.append(entry.getKey().toUpperCase()).append("\n"); sb.append(ln); for (Map.Entry<?, ?> subEntry : m.entrySet()) { sb.append(subEntry.getKey()).append(" = ").append(subEntry.getValue()).append("\n"); } sb.append(ln); } else { sb.append(k).append(" = ").append(v).append("\n"); } sb.append("\n"); } LOG.log(Level.FINE, sb.toString()); this.name = (String) info.get("serverName"); }
eeb150a2-edfd-4777-a5a0-b2d2d4425ce0
8
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { String eol = System.getProperty("line.separator", "\n"); StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
ebae89bd-2f72-4535-b5f3-2014821a6065
5
public void draw() { timer--; if (timer == 0) { //if a player died reset all players and detonate all bombs if (BombermanGame.players.stream().anyMatch(player -> !player.living)) { BombermanGame.players.forEach(Player::resetPosition); for (Bomb b : BombermanGame.bombs) { b.isDetonated = true; } } isDetonated = true; } else if (timer == 20) { this.destroyBoxes(); } else if (timer < 20) { //kill player instantly BombermanGame.players.forEach(this::destroyPlayer); super.renderExplosion(); } else { super.render("bomb"); } }
51d87f80-231c-4a19-8ebd-a1ca28ca31f2
0
@Before public void init(){ MockitoAnnotations.initMocks(this); }
f57cd709-6c32-4b4b-9088-5fe6b221ed18
8
private boolean handlePlaceAllowed(Player player, Block block, Material type) { if (WorldRegionsPlugin.getInstanceConfig().ENABLE_ALLOWED_PLACE && WGCommon.willFlagApply(player, WorldRegionsFlags.ALLOWED_PLACE)) { // Disabled? if (WGCommon.areRegionsDisabled(player.getWorld())) return true; // Bypass? if (!WGCommon.willFlagApply(player, WorldRegionsFlags.ALLOWED_PLACE)) return true; // Get blocked Object blocked = RegionUtil.getFlag(WorldRegionsFlags.ALLOWED_PLACE, block.getLocation()); if (blocked == null) return true; // Check BlockList list = (BlockList) blocked; if (type == Material.STATIONARY_WATER) type = Material.WATER; if (type == Material.STATIONARY_LAVA) type = Material.LAVA; if (list.contains(type)) { return true; } return false; } return true; }
b306b685-a219-4532-9099-b2c4cb604c15
6
public void refresh() { GlobalLogger.getLogger().logp(Level.INFO, "CalendarPanel", "refresh", "Refresh called."); // We need to go through the task list and update all items that match // the current date // Clear it out first itemsToPaint.clear(); for (Scheduleable t : Timeflecks.getSharedApplication() .getFilteringManager().getFilteredTaskList()) { if (t.isScheduled()) { // Same day will just return false if they are null if (sameDay(t.getStartTime(), this.getDate())) { // They are on the same day itemsToPaint.add(t); } } } for (Scheduleable t : Timeflecks.getSharedApplication().getTaskList() .getEvents()) { if (t.isScheduled()) { // Same day will just return false if they are null if (sameDay(t.getStartTime(), this.getDate())) { // They are on the same day itemsToPaint.add(t); } } } // Now we have the list of items to paint, we want to make sure that // they are painted in paintComponent. this.repaint(); }
97a0c155-7f26-40eb-b8fe-a1b481000f4d
5
public Difficulty difficulty(String functionString){ Difficulty difficulty; if (functionString != null){ if (functionString.toLowerCase().equals("easy")){ difficulty = Difficulty.EASY; }else if (functionString.toLowerCase().equals("hard")){ difficulty = Difficulty.HARD; }else if (functionString.toLowerCase().equals("normal")){ difficulty = Difficulty.NORMAL; }else if (functionString.toLowerCase().equals("peaceful")){ difficulty = Difficulty.PEACEFUL; }else{ difficulty = Difficulty.NORMAL; } }else{ difficulty = Difficulty.NORMAL; } return difficulty; }
af6ca0ca-e522-4e68-86cd-18da230526f1
2
public static void copyFolder(String srcFileDir, String destFileDir, String includePattern, String excludePattern) { File srcFile = new File(srcFileDir); File destFile = new File(destFileDir); Project project = new Project(); Copy copy = new Copy(); copy.setProject(project); copy.setTodir(destFile); FileSet fileSet = new FileSet(); fileSet.setDir(srcFile); if (!StringUtil.isNullOrEmpty(includePattern)) fileSet.setIncludes(includePattern); if (!StringUtil.isNullOrEmpty(excludePattern)) fileSet.setExcludes(excludePattern); copy.addFileset(fileSet); copy.execute(); }
bdd68f52-093e-43da-8935-551295672091
6
public boolean match(Sim_event ev) { // checks for errors first if (ev == null || lfn_ == null) { return false; } boolean result = false; try { // find an event with a matching tag first if (ev.get_tag() == tag_) { Object obj = ev.get_data(); // get the data // if the event's data contains the correct data if (obj instanceof Object[]) { Object[] array = (Object[]) obj; String name = (String) array[0]; // if the data contains the correct ID or value if (lfn_.equals(name)) { result = true; } } } } catch (Exception e) { result = false; } return result; }
22d1ef86-3b69-45f9-a97c-0cae32155b48
2
public void addChildren(int x) { if(x >= 3) { propChildren[x] = new PropQuad(this, new Rectangle2D.Double(container.getX() + (container.getWidth()/2), container.getY() + (container.getHeight()/2), container.getWidth()/2, container.getHeight()/2), props, rects, flatRects); } else { if(x < 2) { propChildren[x] = new PropQuad(this, new Rectangle2D.Double(container.getX() + (x * (container.getWidth()/2)), container.getY(), container.getWidth()/2, container.getHeight()/2), props, rects, flatRects); } else { propChildren[x] = new PropQuad(this, new Rectangle2D.Double(container.getX(), container.getY() + (container.getHeight()/2), container.getWidth()/2, container.getHeight()/2), props, rects, flatRects); } addChildren(x+1); } }