method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
fb78aaee-fb98-4f0c-8d52-8e1fe32627a7
1
public void ClearCell(int x, int y, int cellState) { if(cells[x][y].IsConstant()) { return; } SetValueAndState(x, y, cells[x][y].current, cellState); repaint(); }
9eea6b9e-bf46-4640-9d82-976eb9e7c007
6
private double calcPotAtX(double psiL, double xDistance){ double potAtX = 0.0D; if(this.chargeSame){ //symmetric elctrolyte double kappa = Math.sqrt(2.0D*Fmath.square(Fmath.Q_ELECTRON*this.chargeValue)*Fmath.N_AVAGADRO*this.electrolyteConcn/(Fmath.EPSILON_0*this.epsilon*Fmath.K_BOLTZMANN*this.tempK)); double expPart = Math.exp(this.expTerm*this.chargeValue*psiL/2.0D); double gamma = (expPart - 1.0D)/(expPart + 1.0D); double gammaExp = gamma*Math.exp(-kappa*xDistance); potAtX = 2.0D*Math.log((1.0D + gammaExp)/(1.0D - gammaExp))/(this.expTerm*this.chargeValue); } else{ // asymmetric electrolye // Create instance of integration function FunctionPatX func = new FunctionPatX(); func.numOfIons = this.numOfIons; func.termOne = 2.0D*Fmath.N_AVAGADRO*Fmath.K_BOLTZMANN*this.tempK/(Fmath.EPSILON_0*this.epsilon); func.expTerm = this.expTerm ; func.bulkConcn = this.bulkConcn; func.charges = this.charges; int nPointsGQ = 2000; // number of points in the numerical integration // bisection procedure double psiXlow = 0.0; double pFuncLow = xDistance - Integration.trapezium(func, psiXlow, psiL, nPointsGQ); double psiXhigh = psiL; double pFuncHigh = xDistance - Integration.trapezium(func, psiXhigh, psiL, nPointsGQ); if(pFuncHigh*pFuncLow>0.0D)throw new IllegalArgumentException("root not bounded"); double check = Math.abs(xDistance)*1e-2; boolean test = true; double psiXmid = 0.0D; double pFuncMid = 0.0D; int nIter = 0; while(test){ psiXmid = (psiXlow + psiXhigh)/2.0D; pFuncMid = xDistance - Integration.trapezium(func, psiXmid, psiL, nPointsGQ); if(Math.abs(pFuncMid)<=check){ potAtX = psiXmid; test = false; } else{ nIter++; if(nIter>10000){ System.out.println("Class: GouyChapmanStern\nMethod: getPotentialAtX\nnumber of iterations exceeded in outer bisection\ncurrent value of psi(x) returned"); potAtX = psiXmid; test = false; } else{ if(pFuncLow*pFuncMid>0.0D){ psiXlow = psiXmid; pFuncLow = pFuncMid; } else{ psiXhigh = psiXmid; pFuncHigh = pFuncMid; } } } } } return potAtX; }
f41d3cd3-af26-4732-8f66-102847650498
1
private ArrayList<String> arrayToLowercase(ArrayList<String> array) { for (int i = 0; i < array.size(); i++) { array.set(i, array.get(i).toLowerCase().trim()); } return array; }
3eb50967-1494-40a9-9832-613a99872db3
3
public VortexSpaceSet(String savefile, int savesize) { this.vortexSpaces = new VortexSpace[savesize]; System.out.println(savefile); String[] spaceList = savefile.split("\n"); if (savefile.length() == 0) { return; } for (int i=0; i<spaceList.length; i++) { //last empty line not counted System.out.println(i + ": " + spaceList[i]); if (spaceList[i].split(" ")[2].matches("[\\p{ASCII}]")) { makeRoom(spaceList[i]); } else { makeYard(spaceList[i]); } } }
154dbeab-ef2e-4ca3-9519-c6301f6c8dcb
8
public void calc() { if(operator== "+") { firstNum += secondNum; } if(operator == "-"){ firstNum -= secondNum; } if(operator == "*") { firstNum *= secondNum; } // division by non-zero if((operator == "/") && secondNum != 0.0) { firstNum /= secondNum; } // division by zero if((operator == "/") && secondNum == 0.0) { display.setText("ERROR"); // reset firstNum = 0.0; secondNum = 0.0; operators = true; doClear = true; } // if the calculation did not yield an ERROR if (!(display.getText().equals("ERROR"))) { // set ready for new number operators = true; // it's OK to enter a decimal point again decPoint = false; // clicking the equals-button right now does nothing secondEquals = true; // display formatted result display.setText(String.valueOf(format(firstNum))); // the result of the calculation is now the first operand in // subsequent calculations secondNum = firstNum; } }
b3d71eff-8f13-419a-9f9c-959cb93d300c
0
CheckListBoxModel(Object[] items) { this.items = items; }
0205d661-2962-4126-9fdd-28f8b7744ed7
3
public String generate() { StringBuffer buffer = new StringBuffer(); int amt = min; if (min != max) { Random rand = new Random(); if (max >= 0) { amt += rand.nextInt(max - min + 1); } else { amt += rand.nextInt(parent.getUndefinedMax()); } } for (int i = 1; i <= amt; i++) { buffer.append(doGenerate()); } return buffer.toString(); }
c17933cd-dd03-469e-87a6-6d20c5812f1c
5
public static void SetUpPlayers(ArrayList<Player> players, Deck deck, int numPlayers) { log.entering("SetupPlayers", "Main"); if(numPlayers < 2 || numPlayers > 10) { System.exit(345); } for (int i = 0; i < numPlayers; i++) { /*if(i == 0 ) players.add(new Human("Job", i)); else*/ players.add(new Robot("Com"+i, i)); } for (int i = 0; i < 7; i++) { for (Player current : players) { current.GetCard(deck.DrawNext()); } } log.exiting("SetupPlayers", "Main"); }
b8060ea8-fa86-407e-95d8-6f4e9c7d2e60
1
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((values == null) ? 0 : values.hashCode()); return result; }
56a7e831-501e-4153-888a-a7a5d94925bd
3
private boolean nextItemIs(ByteBuffer buf, String match) throws IOException { // skip whitespace int c = nextNonWhitespaceChar(buf); for (int i = 0; i < match.length(); i++) { if (i > 0) { c = buf.get(); } if (c != match.charAt(i)) { return false; } } return true; }
824f6d5d-29da-48b7-9d1f-3838e2f683a7
7
public void run(int gameSecondsTimeout){ try { Thread.sleep(500); } catch(InterruptedException e){} Debug.info("waiting for graphics engine to connect"); while(true){ try { Thread.sleep(100); } catch (InterruptedException e){} if(graphicsContainer.get() != null){ break; } } graphicsContainer.get().thinktime = roundTimeMilliseconds; Debug.info("got graphics engine connection"); Debug.info("waiting for " + minUsers + " users to connect"); int waitIteration = 0; while(true){ waitIteration++; try { Thread.sleep(500); } catch(InterruptedException e){} if(globalClients.size() == minUsers){ Debug.info("Got " + minUsers + " users, starting the round"); break; } } Debug.debug("Initializing game"); gameMainloop(); }
4d0eaa44-ac1b-4581-955f-e38bb0647912
4
private boolean addWordBruteForceSequentially(String word) { for(int i=0;i<N;i++) { if(addWordInRow(word, i)) { return true; } } for(int i=0;i<M;i++) { if(addWordInCol(word, i)) { return true; } } return false; }
ee97d850-6a61-40c2-814f-55e2026fcf77
3
private boolean checkHaveInteraction(String stype) { ArrayList<SpriteData> allSprites = currentGame.getSpriteData(); for (SpriteData sprite : allSprites) { if (getInteraction(stype, sprite.name).size() > 0) { return true; } if (getInteraction(sprite.name, stype).size() > 0) { return true; } } return false; }
419ac332-35a6-4c57-81da-2318a313268e
4
private static void fxmlOutput(Node node, StringBuilder code) { String nodeClass = node.getClass().getSuperclass().getSimpleName(); code.append(" <").append(nodeClass); GObject gObj = (GObject) node; code.append(" fx:id=\"").append(gObj.getFieldName()).append("\" "); for (PanelProperty property : gObj.getPanelProperties()) { String fxmlCode = property.getFXMLCode(); if (!fxmlCode.isEmpty()) { code.append(fxmlCode).append(' '); } } code.append("/>\n"); if (node instanceof Pane) { for (Node node2 : ((Pane) node).getChildren()) { fxmlOutput(node2, code); } } }
39d11a0f-27aa-4e18-9849-6ef537d60233
2
private static void setData(String row, Data data) { // String regex = "('(.*?)'|(?))"; // Matcher m = getMatcher(regex, row); // ArrayList<String> cells = new ArrayList<String>(); // while (m.find()) { // cells.add(m.group(1)); // } if (!isComment(row)) { // System.out.println(row); String[] temp = row.replaceAll("[\' ]", "").split(","); ArrayList<String> cells = new ArrayList<String>(); for (String s : temp) cells.add(s); data.addData(cells); } }
68fc653d-cbc0-4ba1-96ae-2c81f964f18c
3
private String getCipherInitString() { if (algName.equalsIgnoreCase("SkipJack")) { return "SKIPJACK/CBC/PKCS5Padding"; } else if (algName.equalsIgnoreCase("TwoFish")) { return "TWOFISH/CBC/PKCS5Padding"; } else if (algName.equalsIgnoreCase("Salsa20")) { return "Salsa20"; // stream } else { return algName; } }
a607001b-fcf5-4540-a8f1-e276689a27ea
8
public void lifetimeQuery() throws UtilityException, MessageAttributeException, MessageHeaderParsingException, MessageAttributeParsingException, IOException { try { DatagramSocket socket = new DatagramSocket(); socket.connect(InetAddress.getByName(stunServer), port); socket.setSoTimeout(timeout); MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); sendMH.generateTransactionID(); ChangeRequest changeRequest = new ChangeRequest(); ResponseAddress responseAddress = new ResponseAddress(); responseAddress.setAddress(ma.getAddress()); responseAddress.setPort(ma.getPort()); sendMH.addMessageAttribute(changeRequest); sendMH.addMessageAttribute(responseAddress); byte[] data = sendMH.getBytes(); DatagramPacket send = new DatagramPacket(data, data.length, InetAddress.getByName(stunServer), port); socket.send(send); logger.finer("Binding Request sent."); MessageHeader receiveMH = new MessageHeader(); while (!(receiveMH.equalTransactionID(sendMH))) { DatagramPacket receive = new DatagramPacket(new byte[200], 200); initialSocket.receive(receive); receiveMH = MessageHeader.parseHeader(receive.getData()); receiveMH.parseAttributes(receive.getData()); } ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); if (ec != null) { logger.config("Message header contains errorcode message attribute."); return; } logger.finer("Binding Response received."); if (upperBinarySearchLifetime == (lowerBinarySearchLifetime + 1)) { logger.config("BindingLifetimeTest completed. UDP binding lifetime: " + binarySearchLifetime + "."); completed = true; return; } lifetime = binarySearchLifetime; logger.finer("Lifetime update: " + lifetime + "."); lowerBinarySearchLifetime = binarySearchLifetime; binarySearchLifetime = ( upperBinarySearchLifetime + lowerBinarySearchLifetime ) / 2; if (binarySearchLifetime > 0) { BindingLifetimeTask task = new BindingLifetimeTask(); timer.schedule(task, binarySearchLifetime); logger.finer("Timer scheduled: " + binarySearchLifetime + "."); } else { completed = true; } } catch (SocketTimeoutException ste) { logger.finest("Read operation at query socket timeout."); if (upperBinarySearchLifetime == (lowerBinarySearchLifetime + 1)) { logger.config("BindingLifetimeTest completed. UDP binding lifetime: " + binarySearchLifetime + "."); completed = true; return; } upperBinarySearchLifetime = binarySearchLifetime; binarySearchLifetime = ( upperBinarySearchLifetime + lowerBinarySearchLifetime ) / 2; if (binarySearchLifetime > 0) { if (bindingCommunicationInitialSocket()) { return; } BindingLifetimeTask task = new BindingLifetimeTask(); timer.schedule(task, binarySearchLifetime); logger.finer("Timer scheduled: " + binarySearchLifetime + "."); } else { completed = true; } } }
6267a7cd-9870-48ff-a168-3923b2c89e96
5
public void actionPerformed(ActionEvent e) { if (e.getSource() == valider) { String err = null; int note = Integer.parseInt(textNote.getText()); if (textNom.getText() == "") err += "Le nom du fichier ne peut être nul<br />"; if (note < 0 || note > 10) err += "La note doit être comprise entre 0 et 10<br />"; if (err == null) { BDApplication.updateMetadonnees(nom, textNom.getText(), textAuteur.getText(), note); } } }
4b05bf47-8a98-4833-90b1-63cbb0594d9d
3
public Command getCommand() { String inputLine; // will hold the full input line String word1 = null; String word2 = null; System.out.print("> "); // print prompt inputLine = reader.nextLine(); // Find up to two words on the line. Scanner tokenizer = new Scanner(inputLine); if(tokenizer.hasNext()) { word1 = tokenizer.next(); // get first word if(tokenizer.hasNext()) { word2 = tokenizer.next(); // get second word // note: we just ignore the rest of the input line. } } // Now check whether this word is known. If so, create a command // with it. If not, create a "null" command (for unknown command). if(commands.isCommand(word1)) { return new Command(word1, word2); } else { return new Command(null, word2); } }
6ba81210-0017-4af4-9ffd-103971caa658
6
@Override public boolean equals(Object object){ if(object instanceof Editor){ Editor e = (Editor)object; if(e.getId() == this.getId() && e.getNome().equals(this.getNome()) && e.getLogin().equals(this.getLogin()) && e.getSenha().equals(this.getSenha()) && e.getEmail().equals(this.getEmail())) return true; } return false; }
1b2de535-1d92-4ede-b5fd-3b30611a66a0
9
long zipDir(File zipDir, ZipOutputStream zos, String name, long count) throws IOException { // Create a new File object based on the directory we have to zip if (name.endsWith(File.separator)) name = name.substring(0, name.length() - File.separator.length()); if (!name.endsWith(CompressUtil.ZIP_FILE_SEPARATOR)) name = name + CompressUtil.ZIP_FILE_SEPARATOR; final int scale = scale(progressTotal); // Place the zip entry in the ZipOutputStream object // Get a listing of the directory content File[] dirList = zipDir.listFiles(); if (dirList.length == 0) { // empty directory if (CompressUtil.DEBUG) System.out.println("Add empty entry for directory : " + name); ZipEntry anEntry = new ZipEntry(name); zos.putNextEntry(anEntry); return count; } // Loop through dirList, and zip the files for (int i=0; i<dirList.length; i++) { File f = dirList[i]; String fName = name + f.getName(); if (f.isDirectory()) { // if the File object is a directory, call this // function again to add its content recursively count = zipDir(f, zos, fName, count); } else { if (isTotalSize()) { count = count + f.length(); progressTotal.setValue((int) (count/scale)); } else { count++; progressTotal.setValue((int)count); } zipFile(f, zos, fName); if (isOperationCanceled(progressTotal)) throw new InterruptedIOException("progress"); if (isOperationCanceled(progressFile)) throw new InterruptedIOException("progress"); } } return count; }
0b6ec555-8595-4bf0-83aa-e855e78e66c3
6
public void auctionList() { auctions.removeAll(auctions); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } PreparedStatement ps = null; Connection con = null; ResultSet rs; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); try { String sql = "SELECT distinct AirlineID, FlightNo,Class from mlavina.auctions where AccountNo = ?;"; ps = con.prepareStatement(sql); ps.setInt(1, accountNo); ps.execute(); rs = ps.getResultSet(); while (rs.next()) { auctions.add(new Auction(rs.getString("AirlineID"), rs.getInt("FlightNo"), rs.getString("Class"))); } con.commit(); } catch (Exception e) { con.rollback(); } } } catch (Exception e) { System.out.println(e); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
8899111c-f2f8-4ee7-a17f-5a5aa536e19d
2
@Override public boolean canBomb() { if (tile == null) { return false; } return bombs > 0 && tile.passable(); }
caf68ed5-0b52-4502-83b2-eaacaea3e77d
7
public static void assign(String result, String exp, int[] offset) throws Exception{ if(result.equals("MP_FIXED")){ result = "MP_FLOAT"; } if(exp.equals("MP_FIXED")){ exp = "MP_FLOAT"; } if(result.equals(exp)) { // do nothing } else if(result.equals("MP_FLOAT") && exp.equals("MP_INTEGER")) { bw.write("CASTSF\n"); } else if (result.equals("MP_INTEGER") && exp.equals("MP_FLOAT")) { bw.write("CASTSI\n"); } else { throw new Exception("Assigning incompatible types"); } bw.write("POP " + offset[0] + "(D" + offset[1] + ")\n"); }
911d4582-5abf-43c5-9317-f3673190e541
6
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
e9faae2a-05d8-462f-a206-5aa39f534bbd
4
protected boolean in_grouping(char [] s, int min, int max) { if (cursor >= limit) return false; char ch = current.charAt(cursor); if (ch > max || ch < min) return false; ch -= min; if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) return false; cursor++; return true; }
baa616ba-4c71-4cf1-8292-291b96dfffd3
2
private void butLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butLimpiarActionPerformed File archivo = bean.getArchivoDeRegla(); bean = new FirenzeBean(); resultTextArea.setText(""); listaHechosInicio.setSelectedIndices(new int[0]); if (ComboObjetivo.getModel().getSize() != 0) { ComboObjetivo.setSelectedIndex(0); } if (null != archivo) { bean.setArchivoDeRegla(archivo); } }//GEN-LAST:event_butLimpiarActionPerformed
6b94cf31-bcf6-4676-b722-290bdd0f372a
8
public static String encode(String value) { String encoded = null; try { encoded = URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException ignore) { } StringBuffer buf = new StringBuffer(encoded.length()); char focus; for (int i = 0; i < encoded.length(); i++) { focus = encoded.charAt(i); if (focus == '*') { buf.append("%2A"); } else if (focus == '+') { buf.append("%20"); } else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') { buf.append('~'); i += 2; } else { buf.append(focus); } } return buf.toString(); }
be82bdb9-f797-4aed-b5d7-c828799253e5
1
public State tryMove(Move m) { // copy the state State newstate = new State(this); if (newstate.applyMove(m)) return newstate; // apparently, move was not succesful return null; }
cfdc0007-9622-4481-a05b-e97beceaf9c4
2
public boolean createMember(String passport, String name, String password, String postal, int phone, String email) { Query q = em.createQuery("SELECT t from SHSMember t"); for (Object o : q.getResultList()) { SHSMemberEntity p = (SHSMemberEntity) o; if (p.getPersonId().equals(passport)) { return false; } } SHSMemberEntity c = new SHSMemberEntity(); c.create(passport, name, password); ContactEntity contact = new ContactEntity(); contact.create(postal, phone, email); c.setContact(contact); em.persist(contact); em.persist(c); return true; }
22818f0c-9d64-4bba-a316-dafea7e3e326
1
@Before public void putDataSelectionSort(){ a_selectionSort = new Integer[MAX]; for(int i = 0; i < MAX; ++i){ a_selectionSort[i] = i + 1; } shuffleIntArray(a_selectionSort); }
6a8d463d-8582-441f-8e1d-e4b939e010bf
0
public Claire() { super(); }
021fc8c3-9c1f-448c-bc83-4f2fb3ba6a50
9
public boolean execute(CommandSender sender, String[] args, String label) { FileConfiguration messages = plugin.getMessageConfig(); final String badPageNum = messages.getString("info.warnings.badPage"); final String helpHeader = messages.getString("commands.help.alerts.header"); final String aliases = messages.getString("commands.help.alerts.aliases"); final String nextPageString = messages.getString("info.alerts.nextPage"); final String aliasList = "/landlord, /land, /ll"; //check if page number is valid int pageNumber = 1; if (args.length > 1 && Arrays.asList(getTriggers()).contains(args[0])) { try { pageNumber = Integer.parseInt(args[1]); } catch (NumberFormatException e) { // Is not a number! sender.sendMessage(ChatColor.RED + badPageNum); return true; } } // construct the header form the base strings String header = ChatColor.DARK_GREEN + "-|| " + helpHeader // start out with the initial header .replace("#{version}", "v" + plugin.getDescription().getVersion()) // fill in the version .replace("#{author}", ChatColor.BLUE + plugin.getDescription().getAuthors().get(0) + ChatColor.DARK_GREEN) // fill in the author name + " ||--" + "\n " + ChatColor.GRAY + aliases.replace("#{aliases}", aliasList); // add the aliases line ArrayList<String> helpList = new ArrayList<String>(); // Get each help string for (LandlordCommand lc : registeredCommands) { String currCmd = lc.getHelpText(sender); if (currCmd != null) { // make sure the help string isn't null (can happen if conditions aren't right) helpList.add(currCmd.replace("#{label}", label)); } } //Amount to be displayed per page final int numPerPage = 5; int numPages = ceil((double) helpList.size() / (double) numPerPage); if (pageNumber > numPages) { sender.sendMessage(ChatColor.RED + badPageNum); return true; } String pMsg = header; if (pageNumber == numPages) { for (int i = (numPerPage * pageNumber - numPerPage); i < helpList.size(); i++) { pMsg += '\n' + helpList.get(i); } pMsg += ChatColor.DARK_GREEN + "\n------------------------------"; } else { for (int i = (numPerPage * pageNumber - numPerPage); i < (numPerPage * pageNumber); i++) { pMsg += '\n' + helpList.get(i); } pMsg += "\n" + ChatColor.DARK_GREEN + "--- " + nextPageString .replace("#{label}", ChatColor.YELLOW + "/" + label) .replace("#{cmd}", getTriggers()[0]) .replace("#{pageNumber}", "" + (pageNumber + 1) + ChatColor.DARK_GREEN) + " ---"; } sender.sendMessage(pMsg); return true; }
37852d21-96a5-4927-8723-eb6042f431ed
7
public static List<Node> interpolate(short x0, short y0, short x1, short y1) { short sx, sy, dx, dy, pow, offset; List<Node> line = new ArrayList<>(); dx = (short) Math.abs(x1 - x0); dy = (short) Math.abs(y1 - y0); sx = (short) ((x0 < x1) ? 1 : -1); sy = (short) ((y0 < y1) ? 1 : -1); offset = (short) (dx - dy); while (true) { line.add( new Node().construct(x0, y0) ); if (x0 == x1 && y0 == y1) break; pow = (short) (2 * offset); if (pow > -dy) { x0 = (short) (x0 + sx); offset = (short) (offset - dy); } if (pow < dx) { y0 = (short) (y0 + sy); offset = (short) (offset + dx); } } return line; }
1a8ce193-9bea-4bd5-969f-f098eddac829
3
public ArrayList<Pos> getCanSetList(Stone color) { ArrayList<Pos> retList = new ArrayList<Pos>(); Pos workPos = new Pos(); for (int y = Common.Y_MIN_LEN; y < Common.Y_MAX_LEN; y++) { workPos.setY(y); for (int x = Common.X_MIN_LEN; x < Common.X_MAX_LEN; x++) { workPos.setX(x); if (CanSet(workPos, color)) { retList.add(new Pos(x, y)); } } } return retList; }
6b0d9080-c606-47e9-ba1e-774243c77dda
4
public void destroy(String[] split) { if (split.length != 4) { PrintMessage(DESTROYSYNTAX); return; } Player giver; giver = getPlayer(split[1]); if (giver==null) { PrintMessage(split[1] + " does not exist"); return; } try { int amount = new Integer(split[2]); if (amount < 0) { PrintMessage("amounts must be positive"); return; } LinkedList<Moneys> temp = giver.take(amount, split[3],""); giver.writecsv("destroy", amount + ":" + temp.toString()); PrintMessage(temp.toString() + " was destroyed"); } catch (NumberFormatException e) { PrintMessage(split[2] + " is not a number"); return; } }
410fa5b9-c2f0-4daf-9cce-9fd587b66b01
5
public static void main(String[] args) { Scanner reader1 = new Scanner(System.in); System.out.println(".: MAYOR MENOR O IGUAL :."); String v_numero1; String v_numero2; do { System.out.println("Ingrese el primer numero: "); v_numero1 = reader1.next(); } while (isNumeric(v_numero1)); do { System.out.println("Ingrese el segundo numero: "); v_numero2 = reader1.next(); } while (isNumeric(v_numero2)); if (Double.parseDouble(v_numero1) > Double.parseDouble(v_numero2)) System.out.println("El numero: " + v_numero1 + " es Mayor que " + v_numero2); else if (Double.parseDouble(v_numero2) > Double.parseDouble(v_numero1)) System.out.println("El numero: " + v_numero2 + " es Mayor que " + v_numero1); else if (Double.parseDouble(v_numero2) == Double.parseDouble(v_numero1)) System.out.println("El numero: " + v_numero1 + " es igual que " + v_numero2); else System.out.println("error"); }
a71243e3-9e6a-4539-91db-bddca15abf9e
8
public int getFlags() { int flags = 0; flags |= lastUpdatePresent ? 1 : 0; flags |= (biomeArrayPresent ? 1 : 0) << 1; flags |= (addBlockArrayPresent ? 1 : 0) << 2; flags |= (blockLightPresent ? 1 : 0) << 3; flags |= (skyLightPresent ? 1 : 0) << 4; flags |= (tileTicksPresent ? 1 : 0) << 5; flags |= (entitiesPresent ? 1 : 0) << 6; flags |= (tileEntitiesPresent ? 1 : 0) << 7; return flags; }
5ee865d1-a868-4b7b-8876-c33801acc209
3
public void update(int Delta) { if(preMode) { if(diaryElapsedTime > diaryDELAY) { preMode = false; diaryElapsedTime = 0; } else diaryElapsedTime += Delta; } else { if(elapsedTime > timer) { Play.lf = true; } elapsedTime += Delta; } }
5fa1b1d3-4b2c-4dc0-a4e6-1520336d1114
2
public static int getOffsetY(int direction) { if((direction & SOUTH) != 0) { return -1; } if((direction & NORTH) != 0) { return 1; } return 0; }
20b95fee-93f1-4752-955b-77662856981e
6
@Override public void in() throws Exception { if (data == null) { // throw new ComponentException("Not connected: " + toString()); if (log.isLoggable(Level.WARNING)) { log.warning("@In not connected : " + toString() + ", using default value."); } return; } Object val = data.getValue(); // fire only if there is a listener if (ens.shouldFire()) { DataflowEvent e = new DataflowEvent(ens.getController(), this, val); // DataflowEvent e = new DataflowEvent(ens.getController(), this, access.toObject()); ens.fireIn(e); // the value might be altered val = e.getValue(); } // type conversion if (val != null && field.getType() != val.getClass() && !field.getType().isAssignableFrom(val.getClass())) { // // default type conversion fails, we need to convert. // // this will use the Conversions SPI. val = Conversions.convert(val, field.getType()); } // access.pass((Access) val); setFieldValue(val); }
a1567170-e811-4a63-97ec-42eaac09d63e
3
@Override public List<Class<?>> getDatabaseClasses() { ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); classes.add(Faction.class); classes.add(Member.class); classes.add(PlayerReinforcement.class); classes.add(ReinforcementKey.class); classes.add(FactionMember.class); classes.add(PersonalGroup.class); classes.add(Moderator.class); return classes; }
694d904d-10a0-4b58-abb8-56a3a4cb46b3
2
public Node23(Node12 node, Key key, Value value) throws DuplicateKeyException { int cmp = key.compareTo(node.key1); if (cmp < 0) { this.key1 = key; this.value1 = value; this.key2 = node.key1; this.value2 = node.value1; } else if (cmp > 0) { this.key1 = node.key1; this.value1 = node.value1; this.key2 = key; this.value2 = value; } else { throw new DuplicateKeyException(); } this.leftChild = null; this.rightChild = null; this.middleChild = null; }
1e56ea90-6100-4404-a19e-d0f8022f7df4
1
protected static Thread startChatServer(Thread chatServerThread, ServerInfo serverInfo) { if (chatServerThread == null) { ChatServer chatServer = new ChatServer(serverInfo, verbose); log.info("CREATE chat server object"); chatServerThread = new Thread(chatServer); log.info("CREATE thread for chat server object"); chatServerThread.start(); log.info("Start thread for chat server object"); } else { System.out.println("chat sever is already started"); log.info("chat sever is already started"); } return chatServerThread; }
18724169-8bec-4f1b-8526-32e03357acd4
3
public static void runFromBattle() { b1.addText("You try to run away..."); if(!BATTLE_TYPE.equals("WILD")) { b1.addText("No! There's no running from a Trainer battle!"); } else { if(user[userIndex].speed>enemy[enemyIndex].speed) { b1.addText("Got away safely!"); BATTLE_OVER=true; } else { if((int)(Math.random()*10)<5) { b1.addText("Can't escape!"); } else { b1.addText("Got away safely!"); BATTLE_OVER=true; } } } }
a8546dc2-3f1c-43c8-a46d-9368dc771378
9
private Node<K,V> lower( V value ) { if(value == null) return null; Node<K,V> node = mRoot; Node<K,V> ret = null; if(mValueComparator != null) { Comparator<? super V> comp = mValueComparator; while(node != null) { int c = comp.compare(value, node.mValue); if(c <= 0) { node = node.mAllLeft; }else{ ret = node; node = node.mAllRight; } } }else{ Comparable<? super V> comp = (Comparable<? super V>)value; while(node != null) { int c = comp.compareTo(node.mValue); if(c <= 0) { node = node.mAllLeft; }else{ ret = node; node = node.mAllRight; } } } return ret; }
9e48d23f-41b1-4576-ad91-5eb1be6fce1c
0
@Override public boolean Shutdown() { //TODO: Bye Bye =( return true; }
7f7df79e-a384-468b-a76d-aa49478fb2da
7
public String getTrueLink( String url, String encode ) { Document doc = null; try { //System.out.println(url); doc = getDocument(url, encode); //System.out.println(doc.toString()); if ( doc.toString().contains("location.replace") ) { String html = doc.toString(); return getTrueLink(html.substring(html.indexOf("(\"") + 2, html.lastIndexOf("\"")), encode); } if ( url.contains("paper.chinaso.com") ) { Element jumpEle = doc.select("div[class=newpaper_con]").first(); url = jumpEle.select("a[href]").attr("abs:href"); return getTrueLink(url, encode); } Elements metaEles = doc.select("meta[http-equiv=REFRESH]"); if ( metaEles.size() == 0 ) { //System.out.println(url); return url; } else { String content = metaEles.attr("content"); int firstIndex = content.toUpperCase().indexOf("URL") + 4; String link = content.substring(firstIndex); if ( link.indexOf('\\') >= 0 ) link = link.replace('\\', '/'); if ( link.contains("http://") ) return link; String sub = url.substring(url.lastIndexOf('/')); if ( sub.length() != 1 ) return getTrueLink(url.substring(0, url.lastIndexOf('/')+1) + link, encode); else return getTrueLink(url + link, encode); } }catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(baos)); NewsEyeSpider.logger.debug(baos.toString()); } return null; }
5fe73ab8-120a-4856-9d99-e58b11412f54
5
private static boolean tryPlacementAt( Tile t, BotanicalStation parent, Plantation allots[], int dir, boolean covered ) { for (int i = 0 ; i < allots.length ; i++) try { final Plantation p = allots[i] = new Plantation( parent, i == 0 ? TYPE_NURSERY : (covered ? TYPE_COVERED : TYPE_BED), dir, allots ) ; p.setPosition( t.x + (N_X[dir] * 2 * i), t.y + (N_Y[dir] * 2 * i), t.world ) ; if (! p.canPlace()) return false ; } catch (Exception e) { return false ; } return true ; }
3641b38f-d3bc-48ad-a8ed-ece778bf6755
6
public ArrayList<ArrayList<Integer>> levelOrder(treeNode root) { ArrayList<ArrayList<treeNode>> listLevelNodes = new ArrayList<ArrayList<treeNode>>(); ArrayList<ArrayList<Integer>> listLevelValues = new ArrayList<ArrayList<Integer>>(); int curLevel = 0; if (root == null) return listLevelValues; // put root into the first element of listLevelNodes, set the current // level index to 0, corresponding to its index in array; ArrayList<treeNode> curLevelNode = new ArrayList<treeNode>(); curLevelNode.add(root); listLevelNodes.add(curLevelNode); ArrayList<Integer> curLevelValue = new ArrayList<Integer>(); curLevelValue.add(new Integer(root.value)); listLevelValues.add(curLevelValue); treeNode curNode = null; while (true) { ArrayList<treeNode> nextLevelNode = new ArrayList<treeNode>(); ArrayList<Integer> nextLevelValue = new ArrayList<Integer>(); // for each level's nodes in the list already, find its children to // add to next level's array for (int i = 0; i < listLevelNodes.get(curLevel).size(); i++) { curNode = listLevelNodes.get(curLevel).get(i); if (curNode.leftLeaf != null) { nextLevelNode.add(curNode.leftLeaf); nextLevelValue.add(new Integer(curNode.leftLeaf.value)); } if (curNode.rightLeaf != null) { nextLevelNode.add(curNode.rightLeaf); nextLevelValue.add(new Integer(curNode.rightLeaf.value)); } } if (nextLevelNode.isEmpty()) { // finish traversing tree break; } else { listLevelNodes.add(nextLevelNode); listLevelValues.add(nextLevelValue); curLevel++; } } return listLevelValues; }
244c87d2-cec9-4517-b2c2-8006bb98d973
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseLocation other = (BaseLocation) obj; if (x != other.x) return false; if (y != other.y) return false; return true; }
6f7d3614-90d1-4e13-a354-ac673b9e6f9f
6
public static void main(String[] args){ try{ BufferedReader in=null; if(args.length>0){ in = new BufferedReader(new FileReader(args[0])); } else{ in = new BufferedReader(new InputStreamReader(System.in)); } ArrayList<String> input = new ArrayList<String>(); String inp = in.readLine(); while(inp!=null){ input.add(inp); inp=in.readLine(); } int len = input.size(); int[][] nabomatrise = new int[len][len]; for(int i=0; i<len;i++){ Arrays.fill(nabomatrise[i], INF); } StringTokenizer st; StringTokenizer stSplitter; for(int i=0;i<len;i++){ st = new StringTokenizer((String)input.get(i)); while(st.hasMoreTokens()){ stSplitter = new StringTokenizer(st.nextToken(), ":"); nabomatrise[i][Integer.parseInt(stSplitter.nextToken())]=Integer.parseInt(stSplitter.nextToken()); } } System.out.println(new StringBuilder().append(mst(nabomatrise)).toString()); } catch(Exception e){ e.printStackTrace(); } }
3d4fd27f-e5f8-4a05-8839-517a12d0a8fb
2
public static NpcDefinition forId(int id) { for (int i = 0; i < 20; i++) { if (NpcDefinition.cache[i].type == id) { return NpcDefinition.cache[i]; } } NpcDefinition.totalNpcs = (NpcDefinition.totalNpcs + 1) % 20; NpcDefinition npc = NpcDefinition.cache[NpcDefinition.totalNpcs] = new NpcDefinition(); NpcDefinition.buffer.offset = NpcDefinition.npcIndices[id]; npc.type = id; npc.readValues(NpcDefinition.buffer); return npc; }
300ddb7f-961a-491e-8af2-6c71d8afb052
2
public boolean occurs(Term term) { for (Term arg : args) { if (arg.equals(term)) { return true; } } return false; }
a798eda4-703e-40e3-b633-3abbc23bef0a
4
private boolean includedInReplaceOrAdd(String nodePath) { for (String path : replaceChildrenTags) { if (path.startsWith(nodePath)) { return true; } } for (String path : addChildrenTags) { if (path.startsWith(nodePath)) { return true; } } return false; }
72c488dc-3a6e-4491-9372-8f28cc2fddc4
1
public List<ArgPosition> getArgPositionsForTerm(final Object term) { if (this.equals(term)) { return Collections.emptyList(); } List<ArgPosition> result = new ArrayList<ArgPosition>(); ArgPosition curArgPosition = ArgPosition.TOP; internalGetArgPositionsForTerm(term, this, curArgPosition, result); return result; }
6ca9f716-3cd0-4e2a-8a85-7f2f38df629d
4
private int searchName(String name, String password) throws SQLException { conn.commit(); s = conn.createStatement(); rs = s.executeQuery("select NAME,PASSWORD from " + tableName + " ORDER BY NAME"); if (!rs.next()) { return 3; // database empty } do { if (rs.getString("NAME").equalsIgnoreCase(name)) if (rs.getString("PASSWORD").equals(password)) return 1; else return 2; } while (rs.next()); return 0; }
a1100a01-14fa-471f-b0dc-4d69d37edd9d
3
private MetricStrategyInterface chosenStrategy(String metricParam) { MetricEnum m = MetricEnum.valueOf(metricParam); switch (m) { case ETX: return new EtxStrategy(); case ETT: return new EttStrategy(); case MTM: return new MtmStrategy(); default: return new HopStrategy(); } }
6825d325-3ea4-4c0f-ae43-628aa24316e1
3
private String getLanguage(HashMap<String, Object> map) { @SuppressWarnings("unchecked") ArrayList<Object> langs = (ArrayList<Object>) map .get("primaryLanguages"); if (langs == null || langs.isEmpty()) { return null; } else { if (langs.size() > 1) System.out.println("Multiple languages for course [" + map.get("name") + "]: " + langs); return (String) langs.get(0); } }
d9629472-3b13-481a-920f-7ec1ae3c9e75
2
public static void ReadMessageTypes_Properties() { if(!irc_properties_file.exists()) { Utils.Warning("Could not find plugins/AprilonIrc/messagetypes.properties!"); return; } try { InputStream reader = new FileInputStream(messagetypes_properties_file); messagetypes_properties.load(reader); } catch(Exception e) { Utils.LogException(e, "reading messagetypes.properties"); return; } }
eb3856d9-5378-4070-b99b-fe3a6309e574
3
public boolean removeShift(Shift shift) { boolean success = false; if(shift.getEndTime() == null) { working = false; currentShift = null; success = true; } else{ for(int x = 0; x < shifts.size(); x++) { Shift temp = shifts.get(x); if(temp == shift) { shifts.remove(x); success = true; } } } return success; }
f29b8887-b759-4323-9a9d-5d9baebd4d63
9
public void run() { while(true) { try { Socket client=null;//客户Socket client=serverSocket.accept();//客户机(这里是 IE 等浏览器)已经连接到当前服务器 if(client!=null) { System.out.println("连接到服务器的用户:"+client); try { // 第一阶段: 打开输入流 BufferedReader in=new BufferedReader(new InputStreamReader( client.getInputStream())); System.out.println("客户端发送的请求信息: ***************"); // 读取第一行, 请求地址 String line=in.readLine(); System.out.println(line); String resource=line.substring(line.indexOf('/'),line.lastIndexOf('/')-5); //获得请求的资源的地址 resource=URLDecoder.decode(resource, "UTF-8");//反编码 URL 地址 String method = new StringTokenizer(line).nextElement().toString();// 获取请求方法, GET 或者 POST // 读取所有浏览器发送过来的请求参数头部信息 while( (line = in.readLine()) != null) { System.out.println(line); if(line.equals("")) break; } // 显示 POST 表单提交的内容, 这个内容位于请求的主体部分 if("POST".equalsIgnoreCase(method)) { System.out.println(in.readLine()); } System.out.println("请求信息结束 ***************"); System.out.println("用户请求的资源是:"+resource); System.out.println("请求的类型是: " + method); // GIF 图片就读取一个真实的图片数据并返回给客户端 if(resource.endsWith(".gif")) { fileService("images/test.gif", client); closeSocket(client); continue; } // 请求 JPG 格式就报错 404 if(resource.endsWith(".jpg")) { PrintWriter out=new PrintWriter(client.getOutputStream(),true); out.println("HTTP/1.0 404 Not found");//返回应答消息,并结束应答 out.println();// 根据 HTTP 协议, 空行将结束头信息 out.close(); closeSocket(client); continue; } else { // 用 writer 对客户端 socket 输出一段 HTML 代码 PrintWriter out=new PrintWriter(client.getOutputStream(),true); out.println("HTTP/1.0 200 OK");//返回应答消息,并结束应答 out.println("Content-Type:text/html;charset=GBK"); out.println();// 根据 HTTP 协议, 空行将结束头信息 out.println("<h1> Hello Http Server</h1>"); out.println("你好, 这是一个 Java HTTP 服务器 demo 应用.<br>"); out.println("您请求的路径是: " + resource + "<br>"); out.println("这是一个支持虚拟路径的图片:<img src='abc.gif'><br>" + "<a href='abc.gif'>点击打开abc.gif, 是个服务器虚拟路径的图片文件.</a>"); out.println("<br>这是个会反馈 404 错误的的图片:<img src='test.jpg'><br><a href='test.jpg'>点击打开test.jpg</a><br>"); out.println("<form method=post action='/'>POST 表单 <input name=username value='用户'> <input name=submit type=submit value=submit></form>"); out.close(); closeSocket(client); } } catch(Exception e) { System.out.println("HTTP服务器错误:"+e.getLocalizedMessage()); } } //System.out.println(client+"连接到HTTP服务器");//如果加入这一句,服务器响应速度会很慢 } catch(Exception e) { System.out.println("HTTP服务器错误:"+e.getLocalizedMessage()); } } }
e4770ee6-21fe-49ed-8104-8a370da3d9bf
1
public Type getGeneralizedType(Type type) { if (type.typecode == TC_RANGE) type = ((RangeType) type).getTop(); return type; }
2f9e33ca-2b3a-4950-b7ce-a466108ce0d1
6
private static Map<String, List<?>> defaultValues( Map<String, AbstractOptionSpec<?>> recognizedSpecs ) { Map<String, List<?>> defaults = new HashMap<String, List<?>>(); for ( Map.Entry<String, AbstractOptionSpec<?>> each : recognizedSpecs.entrySet() ) defaults.put( each.getKey(), each.getValue().defaultValues() ); return defaults; }
1af7556d-50d6-414e-9406-077a715df130
1
@Override public boolean equals(Object obj) { if (obj instanceof UserEntity) { UserEntity user = (UserEntity) obj; return user.equals(this.username); } return false; }
d008ebd2-784e-4d0c-9988-7af46d045cdf
9
public void tabulate(ArrayList<Response> resp){ //Takes a list of relevant responses for a question and displays all choices made HashMap<String, ArrayList<Integer>> count = new HashMap<String, ArrayList<Integer>>(); HashMap<String, ArrayList<String>> s = null; ArrayList<String> vals = null; for (int i = 0; i < resp.size(); i++){ //For each response s = ((RespDict)resp.get(i)).getAns(); //Pull a response for (Entry<String, ArrayList<String>> entry : s.entrySet()){ //Iterate through all keys if (count.get(entry.getKey()) == null){ //Prepare new key count.put(entry.getKey(),new ArrayList<Integer>()); } vals = entry.getValue(); for (int j = 0; j < right.size(); j++){ //For each right value if (count.get(entry.getKey()).size() < right.size()){ //Prepare new array element count.get(entry.getKey()).add(0); } for (int k = 0; k < vals.size(); k++){ //For each user input response if (right.get(j).equals(vals.get(k))){ //If right value is the response, increment count.get(entry.getKey()).set(j, count.get(entry.getKey()).get(j) + 1); } }//for (int k = 0; k < vals.size(); k++) }//for (int j = 0; j < right.size(); j++) }//for (Entry<String, ArrayList<String>> entry : s.entrySet()) }//for (int i = 0; i < resp.size(); i++) for (int i = 0; i < left.size(); i++){ Out.getDisp().renderLine(left.get(i) + ":"); for (int j = 0; j < right.size(); j++){ Out.getDisp().renderLine(right.get(j) + "- " + count.get(left.get(i)).get(j)); } } }
18afe8f0-88c3-4d48-9774-5d0fd20dc6ef
5
final void method1716(boolean bool) { if (bool != false) method1736(-57); anInt5880++; if (((Class239) this).aClass348_Sub51_3136.method3422(674) != Class10.aClass230_186) ((Class239) this).anInt3138 = 1; else if (((Class239) this).aClass348_Sub51_3136.method3425(-95)) ((Class239) this).anInt3138 = 0; if ((((Class239) this).anInt3138 ^ 0xffffffff) != -1 && (((Class239) this).anInt3138 ^ 0xffffffff) != -2) ((Class239) this).anInt3138 = method1710(20014); }
196a3887-30d6-4a95-89ae-3274b4a4d2d0
2
public Admin adminLogin(String username, String password) { Admin admin; try { admin = (Admin) this.em.createNamedQuery("findByUsername") .setParameter("paramUsername", username).getSingleResult(); if (!admin.getPassword().equals(password)) { throw new Exception(); } } catch (Exception e) { admin = null; } return admin; }
ac17a7b1-343f-4265-ad9a-d5e7fc6cd24e
1
public static void initDB() { File dbFile = new File(Settings.DB_PATH); if (!dbFile.exists()) DB.createDB(); }
7f526e4d-2456-40a7-b885-d388f4faa24c
7
public void paintComponent (Graphics g) { super.paintComponent(g); // 共通する部分をはここで g.setFont(mpFont); g.setColor(Color.BLACK); g.drawImage(backgroundImage, 0, 0, WIDTH, HEIGHT, this); // labelの位置は変わらないので共通部分に start.setLocation(WIDTH/2 - start.getWidth()/2, HEIGHT/2 - start.getHeight()/2); explain.setLocation(WIDTH/2 - explain.getWidth()/2, HEIGHT/2 + 50); exit.setLocation(WIDTH/2 - exit.getWidth()/2, HEIGHT/2 + 100 + explain.getHeight()/2); explainLabel.setLocation(WIDTH/2 - explainLabel.getWidth()/2, HEIGHT/2); next.setLocation(WIDTH/2 - next.getWidth()/2, HEIGHT/2 + next.getHeight()/2); point.setLocation(WIDTH/2 - point.getWidth()/2, 100); // ゲームのstatusに応じた描画の処理 switch (status) { case START: explainLabel.setVisible(false); next.setVisible(false); point.setVisible(false); fillTransparentRect(g, Color.BLACK); break; case EXPLAIN: start.setVisible(false); explain.setVisible(false); exit.setVisible(false); explainLabel.setVisible(true); fillTransparentRect(g, Color.BLACK); break; case GAME_LOOP: start.setVisible(false); explain.setVisible(false); exit.setVisible(false); explainLabel.setVisible(false); next.setVisible(false); point.setVisible(false); ghost.draw(g); if (!item.clicked()) { item.draw(g); } drawSpotlight(g); break; case CATCH_GHOST: point.setVisible(true); point.setText(Ghost.coughtCounter + "体目のゴーストを捕まえました!"); next.setVisible(true); exit.setVisible(true); ghost.draw(g); item.draw(g); fillTransparentRect(g, Color.BLACK); break; case GAME_OVER: point.setVisible(true); exit.setVisible(true); point.setText("残念、取り逃がしてしまいました"); ghost.draw(g); item.draw(g); fillTransparentRect(g, Color.BLACK); break; case FINISH: point.setVisible(true); exit.setVisible(true); point.setText("全てのゴーストを捕まえました!"); ghost.draw(g); item.draw(g); fillTransparentRect(g, Color.BLACK); break; default: g.drawString("Error", 100, 100); break; } }
fcde4b87-2324-44e4-a02b-ca82ce366f12
6
@EventHandler public void SnowmanFastDigging(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getsnowgolemConfig().getDouble("Snowman.FastDigging.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getsnowgolemConfig().getBoolean("Snowman.FastDigging.Enabled", true) && damager instanceof Snowman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getsnowgolemConfig().getInt("Snowman.FastDigging.Time"), plugin.getsnowgolemConfig().getInt("Snowman.FastDigging.Power"))); } }
dc566f75-f184-4ff2-9542-bde353e76ac2
9
@Override public void clearInventoryMoney(MOB mob, String currency) { if(mob==null) return; List<Item> clear=null; Item I=null; for(int i=0;i<mob.numItems();i++) { I=mob.getItem(i); if((I instanceof Coins) &&(((Coins)I).container()==null)) { if(clear==null) clear=new ArrayList<Item>(); if(currency==null) clear.add(I); else if(((Coins)I).getCurrency().equalsIgnoreCase(currency)) clear.add(I); } } if(clear!=null) for(int i=0;i<clear.size();i++) clear.get(i).destroy(); }
bc9ff261-f8ac-42f3-8bd2-abc5c7451277
3
public void tail(Node node, int depth) { String name = node.nodeName(); if (name.equals("br")) append("\n"); else if (StringUtil.in(name, "p", "h1", "h2", "h3", "h4", "h5")) append("\n\n"); else if (name.equals("a")) append(String.format(" <%s>", node.absUrl("href"))); }
9b4b1083-190f-475e-b2d1-71e626bc1f1a
3
@Override public <T extends Comparable<T>> boolean hasElement(T element, T[] sortedArray) { int high = sortedArray.length - 1; int low = 0; int pivot; while (low <= high) { pivot = low + (high - low) / 2; System.out.println(pivot); if (sortedArray[pivot].compareTo(element) > 0) { //go right high = pivot - 1; } else { System.out.println(pivot); if (sortedArray[pivot].compareTo(element) < 0) { //go right low = pivot + 1; } else { return true; } } } return false; }
fc3447c1-a36e-4e13-8c90-9884672b2bbf
3
public String readLine() { String s = null; try { s = myInFile.readLine(); } catch (IOException e) { if (myFileName != null) System.err.println("Error reading " + myFileName + "\n"); myErrorFlags |= READERROR; } if (s == null) myErrorFlags |= EOF; return s; }
db5e5dac-3772-43e4-a273-cb80895098ae
1
public static void compareStats() throws ParameterException, ExpectationException, VarianceException { int trials = 100000; RandomVariable X = new t(6); double sum = 0; double sumSq = 0; for(int i = 0; i < trials; i++) { double obs = X.observe(); sum += obs; sumSq += Math.pow(obs, 2); System.out.println(obs); } System.out.println("x-bar = " + sum / trials); System.out.println("E[X] = " + X.getExpectation()); double s = ((double) trials / (trials + 1)) * (sumSq / trials - Math.pow(sum / trials, 2)); System.out.println("s = " + s); System.out.println("Var[X] = " + X.getVariance()); }
68c621bb-16a4-4512-bb5e-48085eab83b8
2
public static <T extends DC> MSet<DC> dMax(Set<Pair<Pair<T,PT<Integer>>,Pair<T,PT<Integer>>>> phiMax) { if(phiMax!=null) { if(phiMax.getNext()!=null) { return new MSet(phiMax.getFst().fst().fst().delta(phiMax.getFst().snd().fst()).diff(),dMax(phiMax.getNext())); } else { return new MSet(phiMax.getFst().fst().fst().delta(phiMax.getFst().snd().fst()).diff(),null); } } else { return null;} }
5b06bae6-3690-4651-9bd0-2c91d1464fb9
7
public static void main(String[] args) { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; String url = "jdbc:mysql://MySQL55.marlborough.int:3306/MHS_News"; String user = "Android_Client"; String password = "bA55nAFA"; try { con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement("SELECT * FROM Updates"); rs = pst.executeQuery(); while (rs.next()) { System.out.println("ID: "+rs.getInt(2)); //i.e 1= first ever, 2 is second ever, etc. (1,3,4 happens) System.out.println("User: "+rs.getInt(3)); //identifier for person System.out.println("Text: "+rs.getString(4)); System.out.println("Date: "+convertDate(rs.getString(1))); System.out.println(); } pst = con.prepareStatement("SELECT * FROM Users"); rs = pst.executeQuery(); while(rs.next()) { System.out.println(rs.getString(2)); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Tester3.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Tester3.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } }
c37d4bd8-6fd2-468f-a0f6-2e0ed6ba31a7
9
public boolean isContained(char axis) { switch (axis) { case 'x': if (center.x - corner.x < -0.5f * model.getLength() || center.x + corner.x > 0.5f * model.getLength()) return false; break; case 'y': if (center.y - corner.y < -0.5f * model.getWidth() || center.y + corner.y > 0.5f * model.getWidth()) return false; break; case 'z': if (center.z - corner.z < -0.5f * model.getHeight() || center.z + corner.z > 0.5f * model.getHeight()) return false; break; } return true; }
6451a1b8-c610-4e36-a192-0d0f5fc3cb06
1
public boolean host(Lobby alobby) { this.lobby = alobby; waitforclient = true; ishost = true; try { serverSocket = new ServerSocket(port); } catch (IOException ex) { System.out.println(ex.getMessage()); return false; } System.out.println("Host"); playing = true; return true; }
12d6677a-5b54-4943-a87b-601a282af621
8
void releaseChildren(boolean destroy) { if (items != null) { for (int i = 0; i < itemCount; i++) { TableItem item = items[i]; if (item != null && !item.isDisposed()) { item.release(false); } } items = null; } if (columns != null) { for (int i = 0; i < columnCount; i++) { TableColumn column = columns[i]; if (column != null && !column.isDisposed()) { column.release(false); } } columns = null; } super.releaseChildren(destroy); }
2ab33ad5-2b38-4524-ac67-143ab60a1c10
8
@Override public void takeInfo(InfoPacket info) throws Exception { if(!getFailed()){ super.takeSuperInfo(info); Iterator<Pair<?>> i = info.namedValues.iterator(); Pair<?> pair = null; Label label = null; while(i.hasNext()){ pair = i.next(); label = pair.getLabel(); switch (label){ case temp: setTemperature((Double) pair.second()); break; case pres: setPressure((Double) pair.second()); break; case coRL: setControlRodLevel((Double) pair.second()); break; case wLvl: setWaterLevel((Double) pair.second()); break; default: // should this do anything by default? } } } }
0171f515-7b57-4b82-be1a-1bff5f0926f2
5
void checkNextProt(String genomeVer, String vcfFile, String effectDetails, EffectImpact impact) { String args[] = { "-classic", "-v", "-nextProt", genomeVer, vcfFile }; SnpEff cmd = new SnpEff(args); // Run SnpEffCmdEff cmdEff = (SnpEffCmdEff) cmd.snpEffCmd(); List<VcfEntry> vcfEntries = cmdEff.run(true); // Check results int numNextProt = 0; for (VcfEntry ve : vcfEntries) { for (VcfEffect veff : ve.parseEffects()) { System.out.println("\t" + veff); if ((veff.getEffect() == EffectType.NEXT_PROT) // Is it nextProt? && effectDetails.equals(veff.getEffectDetails()) // Are details OK? && (impact == veff.getImpact())) // Is impact OK? numNextProt++; } } Assert.assertEquals(1, numNextProt); }
bcadf122-be07-4382-8cb9-ed15fb4eaf52
0
public SubmitException(Result result){ this.result=result; }
3e2242db-39bc-4945-ac9c-c5283cec820d
1
public void visit_invokestatic(final Instruction inst) { final MemberRef method = (MemberRef) inst.operand(); final Type type = method.nameAndType().type(); stackHeight -= type.stackHeight(); if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += type.returnType().stackHeight(); }
efc768a5-3061-4a8c-a486-5ab9512e3536
7
private BeaconState readBeacon( InputStream in ) throws IOException { BeaconState beacon = new BeaconState(); boolean visited = readBool(in); beacon.setVisited(visited); if ( visited ) { beacon.setBgStarscapeImageInnerPath( readString(in) ); beacon.setBgSpriteImageInnerPath( readString(in) ); beacon.setBgSpritePosX( readInt(in) ); beacon.setBgSpritePosY( readInt(in) ); beacon.setUnknownVisitedAlpha( readInt(in) ); } beacon.setSeen( readBool(in) ); boolean enemyPresent = readBool(in); beacon.setEnemyPresent(enemyPresent); if ( enemyPresent ) { beacon.setShipEventId( readString(in) ); beacon.setShipBlueprintListId( readString(in) ); beacon.setUnknownEnemyPresentAlpha( readInt(in) ); } int fleetPresence = readInt(in); switch ( fleetPresence ) { case 0: beacon.setFleetPresence( FleetPresence.NONE ); break; case 1: beacon.setFleetPresence( FleetPresence.REBEL ); break; case 2: beacon.setFleetPresence( FleetPresence.FEDERATION ); break; case 3: beacon.setFleetPresence( FleetPresence.BOTH ); break; default: throw new RuntimeException( "Unknown fleet presence: " + fleetPresence ); } beacon.setUnderAttack( readBool(in) ); boolean storePresent = readBool(in); beacon.setStorePresent(storePresent); if ( storePresent ) { StoreState store = new StoreState(); store.setTopShelf( readStoreShelf(in) ); store.setBottomShelf( readStoreShelf(in) ); store.setFuel( readInt(in) ); store.setMissiles( readInt(in) ); store.setDroneParts( readInt(in) ); beacon.setStore(store); } return beacon; }
15c39ceb-8771-4935-8a62-6bd3326661b2
5
public double findMedianSortedArrays_3(int A[], int B[]){ int a = A.length; int b = B.length; if(a == 0){ if ((b & 1) == 1) return findKthSortedArrays(A, 0, B, 0, b/2+1); else return (findKthSortedArrays(A, 0, B, 0, b/2+1) + findKthSortedArrays(A, 0, B, 0, b/2))/2.0; }else if(b == 0){ if ((a & 1) == 1) return findKthSortedArrays(B, 0, A, 0, a/2+1); else return (findKthSortedArrays(B, 0, A, 0, a/2+1) + findKthSortedArrays(B, 0, A, 0, a/2))/2.0; } int len = a + b; if((len & 1) == 1) return findKthSortedArrays(A, 0, B, 0, len/2+1); else return (findKthSortedArrays(A, 0, B, 0, len/2) + findKthSortedArrays(A, 0, B, 0, len/2+1))/2.0; }
25ef1771-755e-4a77-839b-6f9cc8bc9f61
3
public List<Item> zoekAlleItems() { List<Item> items = new ArrayList<>(); try (Connection conn = DriverManager.getConnection(JDBC_URL)) { PreparedStatement queryAlleItems = conn.prepareStatement("SELECT * FROM ITEM"); try (ResultSet rs = queryAlleItems.executeQuery()) { while (rs.next()) { int iditems = rs.getInt("IDITEMS"); String naam = rs.getString("NAAM"); int waarde = rs.getInt("WAARDE"); String omschrijving = rs.getString("OMSCHRIJVING"); items.add(new Item(iditems, naam, waarde , omschrijving)); } } } catch (SQLException ex) { for (Throwable t : ex) { t.printStackTrace(); } } return items; }
fdeb663e-c9a2-4326-9b1c-e6c15c74faee
1
public void close() { if(running == true) { running = false; System.out.println("TCP Thread closed"); } }
a46c8061-239c-4469-aed8-4512963094fa
7
private void generatePossibleTests() throws CloneNotSupportedException { boolean randomGeneration = possibleTestsCount != 0; if (possibleTestsCount == 0) { possibleTestsCount = getPossibleTestsNumber(sizes); } if (possibleTestsCount > Integer.MAX_VALUE) { throw new IllegalStateException("Dimension of the problem is too big"); } Logger.getLogger(this.getClass().getName()).info("Creation of " + possibleTestsCount + " possible tests"); possibleTestsSet = new HashSet<SmartTest>((int) possibleTestsCount); if (!randomGeneration) { SmartTest test = new SmartTest(questionCount); possibleTestsSet.add(test); generateNewTestsRecursive(test, 0); } else { Random r = new Random(); while (possibleTestsSet.size() != possibleTestsCount) { SmartTest smartTest = new SmartTest(questionCount); for (int i = 0; i < questionCount; i++) { smartTest.setAnswer(r.nextInt(sizes[i]), i); } possibleTestsSet.add(smartTest); } } createTemplateSmartTest(answerGroupMaxSize); Logger.getLogger(this.getClass().getName()).info( "Number of answer combinations = " + template.getAnswerGroups().size() + " (depth = " + answerGroupMaxSize + ")"); for (SmartTest currentTest : possibleTestsSet) { currentTest.setAnswerGroupsCheckStates(new boolean[template.getAnswerGroups().size()]); for (int i = 0; i < template.getAnswerGroups().size(); i++) { currentTest.setAnswerGroupChecked(i, true); } currentTest.setQuality(template.getQuality()); } }
86c2fb29-18a6-4a48-bb44-83243df8d32f
7
void bufferAttribute(final char[] buffer, final int nameOffset, final int nameLen, final int nameLine, final int nameCol, final int operatorOffset, final int operatorLen, final int operatorLine, final int operatorCol, final int valueContentOffset, final int valueContentLen, final int valueOuterOffset, final int valueOuterLen, final int valueLine, final int valueCol) { if (this.attributeCount >= this.attributeBuffers.length) { // We've reached the max number of attributes currently allowed in the structure, so we must grow final char[][] newAttributeBuffers = new char[this.attributeCount + DEFAULT_ATTRIBUTES_INC][]; Arrays.fill(newAttributeBuffers, null); System.arraycopy(this.attributeBuffers, 0, newAttributeBuffers, 0, this.attributeCount); this.attributeBuffers = newAttributeBuffers; final int[] newAttributeNameLens = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; Arrays.fill(newAttributeNameLens, 0); System.arraycopy(this.attributeNameLens, 0, newAttributeNameLens, 0, this.attributeCount); this.attributeNameLens = newAttributeNameLens; final int[] newAttributeOperatorLens = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; Arrays.fill(newAttributeOperatorLens, 0); System.arraycopy(this.attributeOperatorLens, 0, newAttributeOperatorLens, 0, this.attributeCount); this.attributeOperatorLens = newAttributeOperatorLens; final int[] newAttributeValueContentOffsets = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; final int[] newAttributeValueContentLens = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; Arrays.fill(newAttributeValueContentOffsets, 0); Arrays.fill(newAttributeValueContentLens, 0); System.arraycopy(this.attributeValueContentOffsets, 0, newAttributeValueContentOffsets, 0, this.attributeCount); System.arraycopy(this.attributeValueContentLens, 0, newAttributeValueContentLens, 0, this.attributeCount); this.attributeValueContentOffsets = newAttributeValueContentOffsets; this.attributeValueContentLens = newAttributeValueContentLens; final int[] newAttributeValueOuterLens = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; Arrays.fill(newAttributeValueOuterLens, 0); System.arraycopy(this.attributeValueOuterLens, 0, newAttributeValueOuterLens, 0, this.attributeCount); this.attributeValueOuterLens = newAttributeValueOuterLens; final int[] newAttributeNameLines = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; final int[] newAttributeNameCols = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; System.arraycopy(this.attributeNameLines, 0, newAttributeNameLines, 0, this.attributeCount); System.arraycopy(this.attributeNameCols, 0, newAttributeNameCols, 0, this.attributeCount); this.attributeNameLines = newAttributeNameLines; this.attributeNameCols = newAttributeNameCols; final int[] newAttributeOperatorLines = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; final int[] newAttributeOperatorCols = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; System.arraycopy(this.attributeOperatorLines, 0, newAttributeOperatorLines, 0, this.attributeCount); System.arraycopy(this.attributeOperatorCols, 0, newAttributeOperatorCols, 0, this.attributeCount); this.attributeOperatorLines = newAttributeOperatorLines; this.attributeOperatorCols = newAttributeOperatorCols; final int[] newAttributeValueLines = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; final int[] newAttributeValueCols = new int[this.attributeCount + DEFAULT_ATTRIBUTES_INC]; System.arraycopy(this.attributeValueLines, 0, newAttributeValueLines, 0, this.attributeCount); System.arraycopy(this.attributeValueCols, 0, newAttributeValueCols, 0, this.attributeCount); this.attributeValueLines = newAttributeValueLines; this.attributeValueCols = newAttributeValueCols; } final int requiredLen = nameLen + operatorLen + valueOuterLen; if (this.attributeBuffers[this.attributeCount] == null || this.attributeBuffers[this.attributeCount].length < requiredLen) { // The current buffer for attribute texts hasn't been created yet, or is too small this.attributeBuffers[this.attributeCount] = new char[Math.max(requiredLen, DEFAULT_ATTRIBUTE_BUFFER_SIZE)]; } // We check if the entire attribute (name, operator, value) comes in the buffer as a whole block final boolean isContinuous = (nameOffset + nameLen == operatorOffset) && (operatorOffset + operatorLen == valueOuterOffset) && (valueOuterOffset <= valueContentOffset && (valueOuterOffset + valueOuterLen) >= (valueContentOffset + valueContentLen)); if (isContinuous) { System.arraycopy(buffer, nameOffset, this.attributeBuffers[this.attributeCount], 0, requiredLen); } else { System.arraycopy(buffer, nameOffset, this.attributeBuffers[this.attributeCount], 0, nameLen); System.arraycopy(buffer, operatorOffset, this.attributeBuffers[this.attributeCount], nameLen, operatorLen); System.arraycopy(buffer, valueOuterOffset, this.attributeBuffers[this.attributeCount], nameLen + operatorLen, valueOuterLen); } this.attributeNameLens[this.attributeCount] = nameLen; this.attributeOperatorLens[this.attributeCount] = operatorLen; // valueContentOffset is computed for the structure buffer (not the original buffer that came from parsing) this.attributeValueContentOffsets[this.attributeCount] = (nameLen + operatorLen) + (valueContentOffset - valueOuterOffset); this.attributeValueContentLens[this.attributeCount] = valueContentLen; this.attributeValueOuterLens[this.attributeCount] = valueOuterLen; this.attributeNameLines[this.attributeCount] = nameLine; this.attributeNameCols[this.attributeCount] = nameCol; this.attributeOperatorLines[this.attributeCount] = operatorLine; this.attributeOperatorCols[this.attributeCount] = operatorCol; this.attributeValueLines[this.attributeCount] = valueLine; this.attributeValueCols[this.attributeCount] = valueCol; this.attributeCount++; }
1e9f52d5-78f5-4aaf-a7de-120f1f12aa0f
7
@SuppressWarnings("serial") public Object readResolve() throws ObjectStreamException { try { ClassLoader cl = JMSRemoteSystem.INSTANCE.getUserClassLoader(this); Class<?> superclass = cl.loadClass(this.superclass); Class<?>[] interfaces = null; if (this.interfaces != null) { interfaces = new Class<?>[this.interfaces.length]; for (int i = 0; i < this.interfaces.length; i++) { interfaces[i] = cl.loadClass(this.interfaces[i]); } } return CGLibProxyAdapter.newProxyInstance(superclass, interfaces, handler); } catch (final ClassNotFoundException e) { ObjectStreamException oe = new ObjectStreamException(e.getMessage()) {}; oe.initCause(e); throw oe; } catch (ExportException ee) { ObjectStreamException oe = new ObjectStreamException(ee.getMessage()) {}; oe.initCause(ee); throw oe; } }
cb8e6a9f-3e5a-496e-8b9f-2dc871edae52
4
public void run() { try { BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); while (isRunning) { String input = in.readLine(); if ( input == null ) { System.out.println("Client closed connection : " + socket); break; } out.println("BACK " + input); } } catch (IOException e) { System.out.println("Exception catch"); e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } }
29fdbf8c-43dd-4fac-9e52-2919887a5ce8
0
public double getIntencity() { return intencity; }
f9bc34fa-657c-47fc-9455-73fb1c502e9c
9
protected JButton retrieveButton(int f) { switch (f) { case 1: return a1Button; case 2: return a2Button; case 3: return a3Button; case 4: return a4Button; case 5: return a5Button; case 6: return a6Button; case 7: return a7Button; case 8: return a8Button; case 9: return a9Button; } return null; }
ce58ee52-cec5-4117-a134-140bc705bbaa
7
public static String getTypeName(Configuration config, ClassDoc cd, boolean lowerCaseOnly) { String typeName = ""; if (cd.isOrdinaryClass()) { typeName = "doclet.Class"; } else if (cd.isInterface()) { typeName = "doclet.Interface"; } else if (cd.isException()) { typeName = "doclet.Exception"; } else if (cd.isError()) { typeName = "doclet.Error"; } else if (cd.isAnnotationType()) { typeName = "doclet.AnnotationType"; } else if (cd.isEnum()) { typeName = "doclet.Enum"; } return config.getText( lowerCaseOnly ? typeName.toLowerCase() : typeName); }
88a4a288-5ace-4800-8dc7-df884279b1a9
0
private int findNearest(int value, int partition) { return value/partition; }
2218bf68-c5c1-4407-b9db-7dae5de52ea5
7
public void addBlockHitEffects(int var1, int var2, int var3, int var4) { int var5 = this.worldObj.getBlockId(var1, var2, var3); if(var5 != 0) { Block var6 = Block.blocksList[var5]; float var7 = 0.1F; double var8 = (double)var1 + this.rand.nextDouble() * (var6.maxX - var6.minX - (double)(var7 * 2.0F)) + (double)var7 + var6.minX; double var10 = (double)var2 + this.rand.nextDouble() * (var6.maxY - var6.minY - (double)(var7 * 2.0F)) + (double)var7 + var6.minY; double var12 = (double)var3 + this.rand.nextDouble() * (var6.maxZ - var6.minZ - (double)(var7 * 2.0F)) + (double)var7 + var6.minZ; if(var4 == 0) { var10 = (double)var2 + var6.minY - (double)var7; } if(var4 == 1) { var10 = (double)var2 + var6.maxY + (double)var7; } if(var4 == 2) { var12 = (double)var3 + var6.minZ - (double)var7; } if(var4 == 3) { var12 = (double)var3 + var6.maxZ + (double)var7; } if(var4 == 4) { var8 = (double)var1 + var6.minX - (double)var7; } if(var4 == 5) { var8 = (double)var1 + var6.maxX + (double)var7; } this.addEffect((new EntityDiggingFX(this.worldObj, var8, var10, var12, 0.0D, 0.0D, 0.0D, var6, var4, this.worldObj.getBlockMetadata(var1, var2, var3))).func_4041_a(var1, var2, var3).func_407_b(0.2F).func_405_d(0.6F)); } }
39a7c033-2b45-4544-b83d-0cd4ea886e50
7
public void CombatEventOccurred(CombatEvent e) { switch (e.getAttackType()) { case Melee: case Ranged: if (e.isSuccess()) { gameLogger.append(((Entity)e.getAttacker()).getName() + " inflicts " + e.getDamage() + " damage to " + ((Entity)e.getAttacked()).getName() + '\n'); } else { gameLogger.append(((Entity)e.getAttacked()).getName() + " evaded " + ((Entity)e.getAttacker()).getName() + "'s attack!" + '\n'); } break; case Magic: if (e.isSuccess()) { if (e.getSpell().dealsDamage()) { if (e.getDamage() > 0) { gameLogger.append(((Entity)e.getAttacker()).getName() + " casted " + e.getSpell().getName() + " on " + ((Entity)e.getAttacked()).getName() + " causing " + e.getDamage() + " damage" + '\n'); } else { gameLogger.append(((Entity)e.getAttacker()).getName() + " casted " + e.getSpell().getName() + " on " + ((Entity)e.getAttacked()).getName() + " healing him for " + -e.getDamage() + " HP" + '\n'); } } else { gameLogger.append(((Entity)e.getAttacker()).getName() + " casted " + e.getSpell().getName() + " on " + ((Entity)e.getAttacked()).getName() + '\n'); } } else { gameLogger.append(((Entity)e.getAttacked()).getName() + " failed to cast " + e.getSpell().getName() + " on " + ((Entity)e.getAttacker()).getName() + "!\n"); } break; } gameLogger.setCaretPosition(gameLogger.getText().length() -1); }
7f8d50cc-7c83-4e11-ad48-9432dfd7c389
9
public boolean isSimple(List<Point> vertices) { if (vertices == null || vertices.size() < 3) { return false; } List<Segment> segments = new ArrayList<Segment>(vertices.size()); Point last = vertices.get(vertices.size() - 1); for (int i = 0; i < vertices.size(); i++) { Point current = vertices.get(i); if (current.equals(last)) { return false; } segments.add(new Segment(last, current)); last = current; } Segment prev = segments.get(0); Map<Point, Segment[]> endPoints = new TreeMap<Point, Segment[]>(new PointComparator()); for (int i = vertices.size() - 1; i >= 0; i--) { Segment next = segments.get(i); Segment[] edges = new Segment[] { prev, next }; Segment[] existing = endPoints.put(vertices.get(i), edges); // duplicated point found if (existing != null) { return false; } prev = next; } List<Segment> checkingList = new ArrayList<Segment>(); for (Map.Entry<Point, Segment[]> endPoint : endPoints.entrySet()) { Point vertex = endPoint.getKey(); Segment[] edges = endPoint.getValue(); if (!check(vertex, edges[0], checkingList)) { return false; } if (!check(vertex, edges[1], checkingList)) { return false; } } return true; }