method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c65d3076-e1c3-413a-a34c-57bdbc73aef6
3
public void actionPerformed (ActionEvent event) { String eventName=event.getActionCommand(); // Cancel if (eventName.equals("Cancel")) { changedTriggers=false; dispose(); } // OK if (eventName.equals("OK")) { // Check the entries if (checkTrigger()==true) { changedTriggers=true; dispose(); } } }
32d5de9d-eb19-4ed1-b211-6f4a610d6475
8
public HashMap<String, Integer> printCheck(Check check) throws Exception { HashMap<String, Integer> result = new HashMap<String, Integer>(); if ( ! check.validate()) throw new Exception("Ошибка заполнения чека"); int command = check.getCommand(); ArrayList<Integer> answer = this.device.send(0x8D, 5, new char[]{(char)check.getType()}); if (answer.get(0) != Status.OK) throw new Exception("Ошибка открытия чека"); int products_count = check.getProductsCount(); for(int i = 0; i < products_count; i++) { String title = check.getProduct(i).title; if (title.length() > 39) { this.printLongString(2, 39, title); check.getProduct(i).title = ""; } answer = device.send(command, 3, check.getProduct(i).getSaleParams()); if (answer.get(0) != Status.OK) throw new Exception("Ошибка продажи товара"); } answer = device.send(0x85, 5, check.getCloseParams()); if (answer.get(0) != Status.OK) throw new Exception("Ошибка закрытия чека"); result.put("result", answer.get(0)); if (answer.get(0) == Status.OK) { if (answer.size() > 1) { result.put("error_code", answer.get(4)); result.put("operator", answer.get(5)); } } return result; }
c7c797c4-8d05-44a0-bf2d-08b4c1a0a9c4
2
String genoStr(String geno) { if (geno.equals("x") || geno.equals("0")) return ""; return geno; }
30b8c22d-8a7e-4034-8756-099afff2ed85
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; }
5d7ca3d6-4e6d-4eb5-8048-ee7a228d2a44
2
public void ls() { System.out.println(CompositeDemo.g_indent + m_name); CompositeDemo.g_indent.append(" "); for (Object obj : m_files) { // Recover the type of this object if (obj instanceof Directory) { ((Directory) obj).ls(); } else { ((File) obj).ls(); } } CompositeDemo.g_indent.setLength(CompositeDemo.g_indent.length() - 3); }
8cb80bfe-cab6-49c5-a3af-4536fa2f6089
2
public static void saveToPreferences() { Preferences prefs = Preferences.getInstance(); prefs.removePreferences(MODULE); for (String key : DEFAULTS.keySet()) { Font font = UIManager.getFont(key); if (font != null) { prefs.setValue(MODULE, key, font); } } }
5021efc2-d3e1-43c7-9eec-c342b2e92d47
0
public void setReal (boolean b) { real = b; }
c69bd3df-f2e3-4ff9-8283-5bb56d5911e8
7
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { String label = scanner.next(); //first value entered is label if(scanner.hasNextInt()) { //check if next input is integer int length = scanner.nextInt(); if(length > MAX_BAR_LENGTH || length < 0) { //check if input is within range System.out.println("INPUT ERROR"); return; } System.out.println(drawBar(label, length)); } else if(scanner.hasNextDouble()) { //check if input is a double double scale = scanner.nextDouble(); if(scale > MAX_BAR_SCALE || scale < 0) { //check if input is within range System.out.println("INPUT ERROR"); return; } System.out.println(drawBar(label, scale)); } else { //if input is neither int nor double, exit program System.out.println("INPUT ERROR"); return; } } }
588a4c6d-8d90-4bbf-8990-4bfa7d86f0a2
3
@Override public Hit intersect(Ray ray) { Vector x0 = ray.getOrigin().sub(center); Vector d = ray.getNormalizedDirection(); float t1 = 0.0f; float t2 = 0.0f; if ((x0.dot(d) * x0.dot(d)) * ((x0.dot(x0)) - (radius * radius)) < 0) { return null; } if ((x0.dot(d) * x0.dot(d)) * ((x0.dot(x0)) - (radius * radius)) == 0) { t1 = -(x0.dot(d)); return new Hit(ray.getPoint(t1), color); } else { t1 = (float) (-(x0.dot(d)) + Math.sqrt((x0.dot(d) * x0.dot(d)) * ((x0.dot(x0)) - (radius * radius)))); t2 = (float) (-(x0.dot(d)) - Math.sqrt((x0.dot(d) * x0.dot(d)) * ((x0.dot(x0)) - (radius * radius)))); if (t1 < t2) { return new Hit(ray.getPoint(t1), color); } else { return new Hit(ray.getPoint(t2), color); } } }
a367c1c7-066a-422e-97bf-98b11074a513
5
private void addNeighbour(int x, int y, Cell cell) { if (x >= 0 && x < maxCols && y >= 0 && y < maxRows) { LogicCell c = new LogicCell(x, y); if (!nextStep.containsKey(c)) { c.neigbour = 1; nextStep.put(c, c); } else { nextStep.get(c).neigbour++; } } }
0f6eb5c4-4761-46a7-be0f-473cf4b849be
8
public int send(short dest, byte[] data, int len) { //can't have too many unacked things to send if (toSend.size() > 3)//if there is 4 unacked { stat.changeStat(Status.INSUFFICIENT_BUFFER_SPACE); if(debugLevel > 0) output.println("Too many packets. Not sending"); return 0; } if(len < 0) { stat.changeStat(Status.BAD_BUF_SIZE); if(debugLevel > 0) output.println("Illegal buffer size"); return 0; } if(debugLevel > 0) output.println("LinkLayer: Sending " + len + " bytes to " + dest + " at " + clock.getLocalTime()); int dataLimit = RF.aMPDUMaximumLength - 10; short seq = 0; //placeholder //can't have too many unacked things to send //if if (len <= dataLimit) { // build the frame with data, sequence # = 0, retry bit = 0 byte[] outPack = helper.createMessage("Data", false, ourMAC, dest,data, len, seq); // create packet toSend.add(outPack);// add to the outgoing queue } else // build multiple packets. case where send too large items { int srcPos = 0; int lenEx = len; while (lenEx > dataLimit) { byte[] packetS = new byte[dataLimit]; System.arraycopy(data, srcPos, packetS, 0, dataLimit); byte[] outPack = helper.createMessage("Data", false, ourMAC, dest, packetS, dataLimit, seq); // create packet toSend.add(outPack);// add to the outgoing queue //seq++; srcPos = srcPos + dataLimit; lenEx = lenEx - dataLimit; } byte[] packetL = new byte[lenEx]; System.arraycopy(data, srcPos, packetL, 0, lenEx); byte[] outPack = helper.createMessage("Data", false, ourMAC, dest, packetL, lenEx, seq); // create packet toSend.add(outPack);// add to the outgoing queue } if(debugLevel > 0) output.println("Finished the sending routine. Packet in buffer: " + toSend.size() + " at " +clock.getLocalTime() ); return len; }
ee956baa-551b-4eae-b635-2fab9d83ed88
3
public double compareStrings(String text1, String text2) { ArrayList<String> pairs1 = wordLetterPairs(text1.toUpperCase()); ArrayList<String> pairs2 = wordLetterPairs(text2.toUpperCase()); int similarityCounter = 0; int completeSize = pairs1.size() + pairs2.size(); for (int i = 0; i < pairs1.size(); i++) { Object pair1 = pairs1.get(i); for (int j = 0; j < pairs2.size(); j++) { Object pair2 = pairs2.get(j); if (pair1.equals(pair2)) { similarityCounter++; pairs2.remove(j); break; } } } // 2.0 => Skalierung auf Werte zwischen 0 und 1 return (2.0 * similarityCounter) / completeSize; }
8c3c4400-5f9c-4354-a0e2-4fdaed651374
7
public static List<Double> findRoots(Function f, double startPoint, double endPoint, int numberOfProbes, double tolerance) { double distance = Math.abs((endPoint - startPoint) / numberOfProbes); double[] evaluationPoints = getEvaluationPoints(startPoint, distance, numberOfProbes); List<Double> startingPointsToCheck = findRangesWhereSignsChange(f, evaluationPoints, numberOfProbes); /* * For each interval where the sign changed, used the Secant method to find the root. * If secant method fails, do Bisection three times on the interval and try again */ List<Double> resultList = new LinkedList<Double>(); for (int i = 0; i < startingPointsToCheck.size(); i++) { double start = startingPointsToCheck.get(i); double end = start + distance; double currentLocation = (start + end) / 2; double oldLocation = currentLocation + 0.0005; double currentValue = f.evaluate(currentLocation); double nextLocation = getNextSecantLocation(f, currentLocation, oldLocation); double nextValue = f.evaluate(nextLocation); boolean wasFound = false; //Keep doing secant until we find a root or stall out while (Math.abs(nextValue) < 0.5 * Math.abs(currentValue)) { if (Math.abs(nextValue) < tolerance) //We found the root. w00t! { resultList.add(nextLocation); wasFound = true; break; } oldLocation = currentLocation; currentLocation = nextLocation; nextLocation = getNextSecantLocation(f, currentLocation, oldLocation); nextValue = f.evaluate(nextLocation); } //If we didn't find it, do bisection three times, //Then add the new location to the list and try again if (wasFound == false) { double tempStart = start; double tempEnd = end; double mid = (tempStart + tempEnd) / 2; for (int j = 0; j < 3; j++) { double startVal = f.evaluate(tempStart); double endVal = f.evaluate(tempEnd); double midVal = f.evaluate(mid); if (startVal * midVal <= 0) { tempEnd = mid; continue; } else if (midVal * endVal <= 0) { tempStart = mid; continue; } } startingPointsToCheck.add(tempStart); } } return resultList; }
7f8516b0-7f23-429c-91ee-c5d7d3f401a0
1
private String getWordInSingularOrPluralForm(String word, long count) { return (count > 1) ? word + "s" : word; }
d7651cc7-edaa-473f-a73c-a3c7131f9f68
9
protected boolean encodeHeader(int alphabetSize, int[] alphabet, int[] frequencies, int lr) { EntropyUtils.encodeAlphabet(this.bitstream, alphabet, alphabetSize); if (alphabetSize == 0) return true; this.bitstream.writeBits(lr-8, 3); // logRange int inc = (alphabetSize > 64) ? 16 : 8; int llr = 3; while (1<<llr <= lr) llr++; // Encode all frequencies (but the first one) by chunks of size 'inc' for (int i=1; i<alphabetSize; i+=inc) { int max = 0; int logMax = 1; final int endj = (i+inc < alphabetSize) ? i + inc : alphabetSize; // Search for max frequency log size in next chunk for (int j=i; j<endj; j++) { if (frequencies[alphabet[j]] > max) max = frequencies[alphabet[j]]; } while (1<<logMax <= max) logMax++; this.bitstream.writeBits(logMax-1, llr); // Write frequencies for (int j=i; j<endj; j++) this.bitstream.writeBits(frequencies[alphabet[j]], logMax); } return true; }
a22910b6-b0c8-43e1-9af1-951f7fe89e7e
9
protected void resolveConflict(int s, int newValue) { // The set of children values TreeSet<Integer> values = new TreeSet<Integer>(); // Add the value-to-add values.add(new Integer(newValue)); // Find all existing children and add them too. for (int c = 0; c < alphabetLength; c++) { int tempNext = getBase(s) + c; if (tempNext < getSize() && getCheck(tempNext) == s) values.add(new Integer(c)); } // Find a place to move them. int newLocation = nextAvailableMove(values); // newValue is not yet a child of s, so we should not check for it. values.remove(new Integer(newValue)); /* * This is where the job is done. For each child of s, */ for (Integer value : values) { int c = value.intValue(); // The child state to move int tempNext = getBase(s) + c; // assert tempNext < getSize(); assert getCheck(tempNext) == s; /* * base(s)+c state is child of s. * Mark new position as owned by s. */ assert getCheck(newLocation + c) == EMPTY_VALUE; setCheck(newLocation + c, s); /* * Copy pointers to children for this child of s. * Note that even if this child is a leaf, this is needed. */ assert getBase(newLocation + c) == EMPTY_VALUE; setBase(newLocation + c, getBase(getBase(s) + c)); updateChildMove(s, c, newLocation); /* * Here the child c is moved, but not *its* children. They must be * updated so that their check values point to the new position of their * parent (i.e. c) */ if (getBase(getBase(s) + c) != LEAF_BASE_VALUE) { // First, iterate over all possible children of c for (int d = 0; d < alphabetLength; d++) { /* * Get the child. This could well be beyond the store size * since we don't know how many children c has. */ int tempNextChild = getBase(getBase(s) + c) + d; /* * Here we could also check if tempNext > 0, since * negative values end the universe. However, since the * implementation of nextAvailableHop never returns * negative values, this should never happen. Presto, a * nice way of catching bugs. */ if (tempNextChild < getSize() && getCheck(tempNextChild) == getBase(s) + c) { // Update its check value, so that it shows to the new position of this child of s. setCheck(getBase(getBase(s) + c) + d, newLocation + c); } else if (tempNextChild >= getSize()) { /* * Minor optimization here. If the above if fails then tempNextChild > check.size() * or the tempNextChild position is already owned by some other state. Remember * that children states are stored in increasing order (though not necessarily * right next to each other, since other states can be between the gaps they leave). * That means that failure of the second part of the conjuction of the if above * does not mean failure, since the next child can exist. Failure of the first conjuct * however means we are done, since all the rest of the children will only be further * down the store and therefore beyond its end also. Nothing left to do but break */ break; } } // Finally, free the position held by this child of s setBase(getBase(s) + c, EMPTY_VALUE); setCheck(getBase(s) + c, EMPTY_VALUE); } } // Here, all children and grandchildren (if existent) of s have been // moved or updated. That which remains is for the state s to show // to its new children setBase(s, newLocation); updateStateMove(s, newLocation); }
83972e32-6674-4324-b6c3-7bee112d544d
5
public boolean preaching() { if (preaching == 1){ if (holyBook){ startAnimation(1335); } if (unholyBook){ startAnimation(1336); } if (balanceBook){ startAnimation(1337); } preaching = 2; } if (preaching == 2){ resetPreaching(); } return true; }
e1c3d372-74a2-4779-9e48-eb60ece6bf1e
9
public String getMergedfile(SmartlingKeyEntry updateEntry) throws IOException, JSONException { // for each locale (for the specific project) , get translated file from smartling String responseHtml = SmartlingRequestApi.getFileFromSmartling(updateEntry.getFileUri(), updateEntry.getProjectId(), updateEntry.getLocale(),updateEntry.getApiKey()); if (responseHtml.contains("VALIDATION_ERROR")) return responseHtml; // Get List of updated Strings from App Engine DB List<SmartlingKeyEntry> dbFile = getTranslationFromDb(datastore, updateEntry.getProjectId(), updateEntry.getLocale(), updateEntry.getFileUri()); if (dbFile.isEmpty()) { log.info("No Updated Strings for ProjectId:" + updateEntry.getProjectId() + ";File:" + updateEntry.getFileUri() + ";Locale:" + updateEntry.getLocale()); return responseHtml; } // build map from Json (smarling) HashMap<String, Object> smartlingFile = new ObjectMapper().readValue(responseHtml, HashMap.class); for (int i = 0; i < dbFile.size(); i++) { String keyInDb = dbFile.get(i).getKey(); String updatedEngVal = dbFile.get(i).getUpdatedEngVal(); String tranlatedVal = dbFile.get(i).getTranslationInLocale(); //String currentValInLocaleFile = (String) smartlingFile.get(keyInDb); String currentValInLocaleFile = "new orgenize images"; if (currentValInLocaleFile == null || currentValInLocaleFile.isEmpty()) { String error = "Key:" + keyInDb + " Not found in ProjectId:" + updateEntry.getProjectId() + ", But it's on DB. should we remove from DB???"; log.severe(error); continue; } if (currentValInLocaleFile.equals(updatedEngVal)) { String error = "Key:" + keyInDb + "found in ProjectId:" + updateEntry.getProjectId() + " But Still not translated in locale:" + updateEntry.getLocale() + ".value=" + currentValInLocaleFile; smartlingFile.put(keyInDb,tranlatedVal); log.info(error); continue; } if (!currentValInLocaleFile.equals(updatedEngVal)) { String error = "Key:" + keyInDb + "found in ProjectId:" + updateEntry.getProjectId() + " re-translated in locale:" + updateEntry.getLocale() + ".value=" + currentValInLocaleFile; log.info(error); // remove from DB !!! removeKeyFromDb(datastore, updateEntry.getProjectId(), updateEntry.getLocale(), updateEntry.getFileUri(), keyInDb); continue; } } JSONObject returnJson = new JSONObject(); Iterator it = smartlingFile.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); if (!pairs.getKey().toString().equalsIgnoreCase("smartling")) returnJson.put(pairs.getKey().toString() , pairs.getValue().toString()); } return returnJson.toString(); }
8d28a7d4-993f-4936-bd5d-8aef60750c9f
2
public Lep(int i, int j, int k, int l, int[][] t){ logger.info("Meghívták a konstruktort."); aktualispoz1=i; aktualispoz2=j; hovaakar1=k; hovaakar2=l; for(int a=0; a<8; a++) for(int b=0; b<8; b++) sajat[a][b]=t[a][b]; }
1b6f5d9d-401b-45af-88af-86640893467c
6
private ArrayList<File> dirFilelist(File f) { ArrayList<File> res = new ArrayList<>(); if (f.exists() && f.isDirectory()) { File[] chld = f.listFiles(); for (File sf : chld) { if (!sf.getName().equals(".") && !sf.getName().equals("..") && sf.isFile()) { res.add(sf); } } } return res; }
b494f577-a563-4ef4-aabc-7442dd952af7
1
public void resetPositions(){ // Reposition game objects p1.setX(initialPosX_p1); p1.setY(initialPosY_p1); p2.setX(initialPosX_p2); p2.setY(initialPosY_p2); b.setY(gameWindow.getCenterY() - 14); b.setVelX(0); b.setVelY(0); // alternate the ball's starting side if((roundCount % 2) == 1){ b.setX(p1.getX() + 15); b.setInitVelX(initialBall_velX); b.setInitVelY(initialBall_velY); } else{ b.setX(p2.getX() - 15); b.setInitVelX(-initialBall_velX); b.setInitVelY(-initialBall_velY); } }
43ddb0ff-28d7-423c-81b6-e7d051c14dc3
9
@Override public void handlePacket(Packet packet, Socket s, Main game) { if (!packet.getBoolean()) { // success JOptionPane.showMessageDialog(game.gameFrame, "You cannot do that.", "Error", JOptionPane.ERROR_MESSAGE); game.setButtons(true); return; } int rank = 0; Group group = null; for (int i = 0; i < 7; i++) { Card temp = packet.getCard(); if (i == 0) { rank = temp.getRank(); int id = 0; if (game.getBoard().containsKey(rank)) { id = game.getBoard().get(rank).size(); } group = new Group(rank, id); group.addCards(Collections.singletonList(temp)); } else { game.getHand().add(temp); } } if (group == null) { throw new RuntimeException("Error Constructing Draw7 Group"); } int i = 0; for (Iterator<Card> it = game.getHand().iterator(); it.hasNext();) { if (i >= 2) { break; } Card c = it.next(); if (c.getRank() == rank) { group.addCards(Collections.singletonList(c)); it.remove(); i++; } } game.setStaging(group); try { s.getOutputStream().write(PacketCreator.play(group).toByteArray()); } catch (IOException e) { e.printStackTrace(); } game.redraw(); }
17845d29-ecaf-4678-97b8-6b1adba09170
9
public CommandHandler(String command, String pitch, String commandGrammar, String where, String summary, List<String> notes, String input, String output, String example, Options options) { if ((command == null)) { throw new IllegalArgumentException("command cannot be null."); } this.fcommand = command; this.fpitch = pitch == null ? "undocumented" : pitch; this.fcommandGrammar = commandGrammar == null ? "undocumented" : commandGrammar; this.fwhere = where == null ? "undocumented" : where; this.fsummary = summary == null ? "undocumented" : summary; this.fnotes = notes == null ? new ArrayList<String>() : notes; this.finput = input == null ? "undocumented" : input; this.foutput = output == null ? "undocumented" : output; this.fexample = example == null ? "undocumented" : example; this.foptions = options; }
5bf58301-e882-4088-a801-9304f87ead9b
7
public boolean addElementField(ElementField element) { gameFieldView().addElementFieldView(element); if (element instanceof Ball) { return _balls.add((Ball) element); } else if (element instanceof DestructibleBrick) { return _dBricks.add((DestructibleBrick) element); } else if (element instanceof BoundaryField) { return _bondarysField.add((BoundaryField) element); } else if (element instanceof Swarm) { return _swarms.add((Swarm) element); } else if (element instanceof IndestructibleBrick) { return _iBricks.add((IndestructibleBrick) element); } else if (element instanceof Racket) { if (_racket == null) { _racket = (Racket) element; return true; } else { return false; } } return false; }
befad3ae-90bd-4e3f-8588-cba429796132
4
public void dumpLayers() { System.out.println("<layers>"); for (Layer l : layers) { if (l instanceof CodeEntry) { System.out.println("CodeEntry: " + ((CodeEntry)l).clnm); } else if (l instanceof Code) { System.out.println("Code: " + ((Code)l).name); Field[] classfields = ((Code)l).getClass().getFields(); for(Field f : classfields) { Class ftype = f.getType(); System.out.println("Name: "+f.getName()+"; Type: "+ftype.getName()); } } else { System.out.println(l); } } System.out.println("</layers>"); }
a91f4b1b-190e-499b-8400-c0bfd0b410df
3
public void run(){ long lastTime = System.nanoTime(); long timer = System.currentTimeMillis(); final double ns =1000000000.0 /60.0; double delta =0; int frames =0; int updates =0; requestFocus(); while(running){ long now =System.nanoTime();//re-sets time to computer time lag delta += (now-lastTime) /ns; lastTime =now; while (delta >=1){ update(); updates++; delta--; } render(); frames++; //adds 1000 ns to time which is 1 sec per if(System.currentTimeMillis()-timer > 1000){ timer += 1000; System.out.println(updates+ "ups,"+frames+"frames");//prints frames and ups frame.setTitle(title+" | " +updates+ "ups,"+frames+"frames"); updates =0; frames =0; } } stop(); }
9b853ac2-a417-4fee-8a51-3351dfa056c0
6
private static Point2D getProjectionOnEdge(Point2D source, Point2D wayPoint, double panelWidth, double panelHeight) { final LineEquation eq = new LineEquation(source, wayPoint); double interX; // X coord of the intersection double interY; // Y coord of the intersection if (eq.a > 0) { // Intersection avec la droite y = y_max interX = -(eq.c + eq.b * panelHeight) / eq.a; interY = panelHeight; } else { // Intersection avec la droite y = 0 interX = -eq.c / eq.a; interY = 0; } if (interX >= 0 && interX <= panelWidth) { // this point is in the boundaries, no need to carry on return new Point2D.Double(interX, interY); } if (eq.b > 0) { // Intersection avec la droite x = 0 interX = 0; interY = -eq.c / eq.b; } else { // Intersection avec la droite x = x_max interX = panelWidth; interY = -(eq.c + eq.a * panelWidth) / eq.b; } if (interY >= 0 && interY <= panelHeight) { // this point is in the boundaries return new Point2D.Double(interX, interY); } throw new RuntimeException("No correct intersection was found"); }
2b05a059-7023-4d4a-ba9e-45f37ab194c2
5
@Override public List<Group> findGroupByUserId(int userId) { List<Group> list = new ArrayList<Group>(); Connection cn = null; PreparedStatement ps = null; ResultSet rs = null; try { cn = ConnectionHelper.getConnection(); ps = cn.prepareStatement(QTPL_SELECT_BY_USER_ID); ps.setInt(1, userId); rs = ps.executeQuery(); while (rs.next()) { list.add(processResultSet(rs)); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { cn.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; }
bda193e8-69a5-4d26-af2c-d73f9a29f67e
7
public Passenger(JSONObject json) throws JSONException { try { if (json.has(AMOUNT)) { this.setAmount(Float.parseFloat(json.getString(AMOUNT))); } if (json.has(TOTAL)) { this.setTotal(Float.parseFloat(json.getString(TOTAL))); } if (json.has(NETAMOUNT)) { this.setNetamount(Float.parseFloat(json.getString(NETAMOUNT))); } if (json.has(TYPE)) { this.setType(json.getString(TYPE)); } if (json.has(SURCHARGES)) { this.setSurcharges(Float.parseFloat(json.getString(SURCHARGES))); } if (json.has(TAX)) { this.setTax(Float.parseFloat(json.getString(TAX))); } } catch (NumberFormatException nfe) { logger.error(nfe); throw new JSONException("Error parsing string to float"); } // if (json.has("ticketbydate")) { // this.setTicketbydate(json.getString("ticketbydate")); // } }
f1cead48-335c-4f6d-be8d-41a24731a52c
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Shelf other = (Shelf) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
570f216c-d599-429e-bf73-1a8f52770ebd
6
public static final void itemSort(SeekableLittleEndianAccessor slea, MapleClient c) { slea.readInt(); // timestamp byte mode = slea.readByte(); boolean sorted = false; MapleInventoryType pInvType = MapleInventoryType.getByType(mode); MapleInventory pInv = c.getPlayer().getInventory(pInvType); while (!sorted) { byte freeSlot = (byte) pInv.getNextFreeSlot(); if (freeSlot != -1) { byte itemSlot = -1; for (int i = freeSlot + 1; i <= 100; i++) { if (pInv.getItem((byte) i) != null) { itemSlot = (byte) i; break; } } if (itemSlot <= 100 && itemSlot > 0) { MapleInventoryManipulator.move(c, pInvType, itemSlot, freeSlot); } else { sorted = true; } } } c.getSession().write(MaplePacketCreator.finishedSort(mode)); c.getSession().write(MaplePacketCreator.enableActions()); }
28327f11-b788-482e-9f78-211058be19cd
0
public int getSize() { return statusRepo.size(); }
809c7f21-5bda-44d1-96c0-d556d483f663
9
double calculatescore() { total = 0; for (int i = 0; i < seedlist.size(); i++) { double score; double chance = 0.0; double totaldis = 0.0; double difdis = 0.0; for (int j = 0; j < seedlist.size(); j++) { if (j != i) { totaldis = totaldis + Math.pow( distanceseed(seedlist.get(i), seedlist.get(j)), -2); } } for (int j = 0; j < seedlist.size(); j++) { if (j != i && ((seedlist.get(i).tetraploid && !seedlist.get(j).tetraploid) || (!seedlist .get(i).tetraploid && seedlist.get(j).tetraploid))) { difdis = difdis + Math.pow( distanceseed(seedlist.get(i), seedlist.get(j)), -2); } } //System.out.println(totaldis); //System.out.println(difdis); chance = difdis / totaldis; score = chance + (1 - chance) * s; seedlist.get(i).score = score; total = total + score; } return total; }
a6f2cb71-7a59-4de2-bbde-6cdecfe6d864
3
private boolean exitTableBody(Token t, HtmlTreeBuilder tb) { if (!(tb.inTableScope("tbody") || tb.inTableScope("thead") || tb.inScope("tfoot"))) { // frag case tb.error(this); return false; } tb.clearStackToTableBodyContext(); tb.process(new Token.EndTag(tb.currentElement().nodeName())); // tbody, tfoot, thead return tb.process(t); }
54a9eeb6-447a-419c-9913-518f6d451a93
7
public static String extractTitleFrom(String filePath) /* * The extractNameFrom method checks the ID3 version of the mp3 file and * extracts the song title from the MP3 file. */{ String title = null; try { Mp3File mp3File = new Mp3File(filePath); if (mp3File.hasId3v2Tag()) { ID3v2 id3v2Tag = mp3File.getId3v2Tag(); title = id3v2Tag.getTitle(); } else if (mp3File.hasId3v1Tag()) { ID3v1 id3v1Tag = mp3File.getId3v1Tag(); title = id3v1Tag.getTitle(); } } catch (UnsupportedTagException e) { e.printStackTrace(); } catch (InvalidDataException e) { System.out.print("Invalid Data"); return " - Unknown Title"; //e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(title == null) { int lastSlash = filePath.lastIndexOf('\\'); if(filePath.lastIndexOf('/') > lastSlash) lastSlash = filePath.lastIndexOf('/'); title = filePath.substring(lastSlash + 1).replaceAll("\\.mp3$",""); } return title; }
0bc93023-6e68-4539-b7f7-4d439dc13bc8
4
protected static Ptg calcInt( Ptg[] operands ) { if( operands.length != 1 ) { return PtgCalculator.getNAError(); } double dd = 0.0; try { dd = operands[0].getDoubleVal(); } catch( NumberFormatException e ) { return PtgCalculator.getValueError(); } if( new Double( dd ).isNaN() ) // Not a Num -- possibly PtgErr { return PtgCalculator.getError(); } long res = Math.round( dd ); if( res > dd ) { res--; } PtgInt pint = new PtgInt( (int) res ); return pint; }
31485828-5f9f-4276-931e-12c4b56295e2
7
public void setFrame(String panel){ switch(panel){ case "login": frame.remove(curPanel); frame.add(login); login.refresh(); frame.validate(); frame.repaint(); curPanel=login; frame.setSize(425,300); break; case "createUser": frame.remove(curPanel); frame.add(createUser); createUser.refresh(); frame.validate(); frame.repaint(); curPanel=createUser; frame.setSize(425,300); break; case "createMeeting": frame.remove(curPanel); frame.add(createMeeting); createMeeting.refresh(); createMeeting.setYear(year); createMeeting.setMonth(month); createMeeting.setDay(day); frame.validate(); frame.repaint(); curPanel=createMeeting; frame.setSize(600, 350); break; case "editMeeting": frame.remove(curPanel); frame.add(editMeeting); editMeeting.refresh(); frame.validate(); frame.repaint(); curPanel=editMeeting; frame.setSize(660, 360); break; case "mainScreen": frame.remove(curPanel); frame.add(mainScreen); mainScreen.refresh(); mainScreen.setDatePicked(); mainScreen.setNewsfeed(); mainScreen.setNotifications(); frame.validate(); frame.repaint(); curPanel=mainScreen; frame.setSize(700, 400); mainScreen.setDatePicked(); mainScreen.setNewsfeed(); mainScreen.setNotifications();; break; case"showMeeting": frame.remove(curPanel); frame.add(showMeeting); showMeeting.refresh(); frame.validate(); frame.repaint(); curPanel=showMeeting; frame.setSize(600, 360); break; case "weekCalendar": frame.remove(curPanel); frame.add(weekCalendar); weekCalendar.refresh(); frame.validate(); frame.repaint(); curPanel=weekCalendar; frame.setSize(700, 400); break; } }
2777ee16-1840-4008-845b-7a9e5e8601da
0
public void destroy() { targetNode = null; currentRenderer = null; prevRenderer = null; }
872ff0d1-5c56-49b0-a73f-4b580af3eed5
4
private LinkedHashMap<Rashi, ArrayList<Nakshatra>> getStarsInRashi() { LinkedHashMap<Rashi, ArrayList<Nakshatra>> starsInRashi = new LinkedHashMap<Rashi, ArrayList<Nakshatra>>(); ArrayList<Nakshatra> starsForRashiList = new ArrayList<Nakshatra>(); for (Nakshatra nakshatra : Nakshatra.values()) { if (nakshatra.getSplit()) { starsForRashiList.add(nakshatra); starsForRashiList.add(nakshatra); } else { starsForRashiList.add(nakshatra); } } int index = 0; for (Rashi rashi : Rashi.values()) { ArrayList<Nakshatra> starInfo = new ArrayList<Nakshatra>(); for (int i = 0; i < 3; i++) { starInfo.add(starsForRashiList.get(index++)); } starsInRashi.put(rashi, starInfo); } return starsInRashi; }
e2542c1b-085f-47af-8e47-4ab2931e902b
4
private void useTeamPiece(char teamSymbol) throws Exception{ if (!NineManMill.DEBUG_VERSION){ throw new Exception ("This is not a debug version, cannot call useTeamPiece()!"); } switch (teamSymbol){ case EMPTY: return; case PLAYER1: /* Find some way to get the coordinates */ // team1.usePiece(new GamePiece()); return; case PLAYER2: /* Find some way to get the coordinates */ // team2.usePiece(new GamePiece()); return; default: throw new PiecePlacementException("Building debug board failed, encountered unknown teamsymbol"); } }
b0cb0ddd-5d53-4713-bc27-769218f0d23d
1
public static void main(String[] args) { int elements[] = {5, 3, 2, 6, 3, 1, 8, 7, 1, 2, 4, 1, 6, 2, 3, 4, 5, 2, 3, 2, 6, 1, 1, 8, 7, 1, 2, 4, 1, 2, 2, 3, 4, 5, 2, 3, 2, 6, 1, 1, 8, 7, 1, 2, 4, 1, 1, 2, 3, 4, 5, 2, 3, 2, 6, 1, 1, 8, 7, 1, 2, 4, 7, 1, 2, 3, 4, 5, 2, 3, 5, 6, 1, 1, 8, 7, 1, 2, 4, 1, 1, 2, 3, 4, 5, 2 }; Generation gen = Generation.initFirstGeneration(Element.intArrToList(elements), 100); gen.countFitness(); for(int i = 0; i < 100; i++){ gen.selection(); gen.generateNextGeneration(); gen.addMutations(); gen.countFitness(); System.out.println("Best fintess in generation ~"+gen.getGenerationNumber()+": "+gen.getBestFitValue() + " with " + gen.bestBinsCount + " used. "+ gen.allGens()/*gen.allFits()*/); } }
f0f54cc4-1149-41af-a4c6-3fcc0d20af0c
1
public MyCanvas() { setDoubleBuffered(false); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { oX = e.getX(); oY = e.getY(); } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { cX = e.getX(); cY = e.getY(); graphics2D.setStroke(new BasicStroke(10)); graphics2D.setColor(new Color(rValue,gValue,bValue)); if (graphics2D != null) graphics2D.drawLine(oX,oY, cX, cY); repaint(); oX = cX; oY = cY; } }); }
a3714e05-81c2-4ebb-9d9d-fac114523235
5
private int upgradeForGood(Service type) { final Integer key = (Integer) SupplyDepot.SERVICE_KEY.get(type) ; final Upgrade KU ; if (key == null) return -1 ; else if (key == SupplyDepot.KEY_RATIONS ) KU = RATIONS_STOCK ; else if (key == SupplyDepot.KEY_MINERALS) KU = PROSPECT_EXCHANGE ; else if (key == SupplyDepot.KEY_MEDICAL ) KU = MEDICAL_EXCHANGE ; else if (key == SupplyDepot.KEY_BUILDING) KU = HARDWARE_STOCK ; else return -1 ; return structure.upgradeLevel(KU) ; }
38ab6442-5707-46e7-ae6a-915241708fb2
8
public boolean similar(Object other) { if (!(other instanceof JSONArray)) { return false; } int len = this.length(); if (len != ((JSONArray)other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.get(i); Object valueOther = ((JSONArray)other).get(i); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; }
b3484565-e229-4ac7-ae91-3b892e46523e
1
public void close(){ //called when room is closing, should kick all users for (ChatServerThread thread : threads){ thread.disconnect("Room is closing."); } }
f9335c9b-3ac5-4368-9621-8b6eeab50a74
7
private void salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarActionPerformed Contato contato = new Contato(); contato.setNome(nome.getText()); if((null != tel_1.getText()) && !(tel_1.getText().isEmpty())){ contato.setTelefone1(Integer.parseInt(tel_1.getText())); } if((null != tel_2.getText()) && !(tel_2.getText().isEmpty())){ contato.setTelefone2(Integer.parseInt(tel_2.getText())); } if((null != tel_3.getText()) && !(tel_3.getText().isEmpty())){ contato.setTelefone3(Integer.parseInt(tel_3.getText())); } contato.setEmail(email.getText()); contato.setObservacoes(observcoes.getText()); if(FachadaSistema.getInstance().validarContato(contato)){ FachadaSistema.getInstance().adicionarContato(contato); JOptionPane.showMessageDialog(null, "Contato adicionado!"); limparTela(); } }//GEN-LAST:event_salvarActionPerformed
32c2c353-0766-44b0-8c91-383acaa09370
6
public final float apply(float x, float y, float z) { // Skew input space to relative coordinate in simplex cell s = (x + y + z) * onethird; i = fastfloor(x+s); j = fastfloor(y+s); k = fastfloor(z+s); // Unskew cell origin back to (x, y , z) space s = (i + j + k) * onesixth; u = x - i + s; v = y - j + s; w = z - k + s; A[0] = A[1] = A[2] = 0; // For 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we're in int hi = u >= w ? u >= v ? 0 : 1 : v >= w ? 1 : 2; int lo = u < w ? u < v ? 0 : 1 : v < w ? 1 : 2; return k(hi) + k(3 - hi - lo) + k(lo) + k(0); }
ab37041e-f009-4ea4-b491-c691f88119cc
7
public CheckResultMessage check27(int day) { int r1 = get(39, 5); int c1 = get(40, 5); int r2 = get(41, 5); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); for (int i = r1 + 21; i < r2; i++) { b = b.add(getValue(i, c1 + day, 10)); } if (0 != getValue(r1 + 20, c1 + day, 10).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">其他跳整项L20:" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); for (int i = r1 + 21; i < r2; i++) { b = b.add(getValue1(i, c1 + day, 10)); } if (0 != getValue1(r1 + 20, c1 + day, 10).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">其他跳整项L20:" + day + "日错误"); } } catch (Exception e) { } } return error("支付机构汇总报表<" + fileName + ">其他跳整项L20:" + day + "日正确"); }
16694960-3959-48fc-9787-f31abcb59a76
2
private Move getMinimaxMove(StateTree tree) throws Exception { TicTacToeBoard state = tree.getState(); if (state.getTurn() == MIN_PLAYER) { return this.getMinMove(tree); } else if (state.getTurn() == MAX_PLAYER) { return this.getMaxMove(tree); } else { throw new Exception("Invalid player turn"); } }
c3da6b7f-0964-4b09-aaff-1d23c9b2e192
7
public void attdam(int maxDamage, int range) { for (Player p : server.playerHandler.players) { if(p != null) { client person = (client)p; if((person.playerName != null || person.playerName != "null")) { if(person.distanceToPoint(absX, absY) <= range && person.playerId != playerId) { int damage = misc.random(maxDamage); if (person.playerLevel[3] - hitDiff < 0) damage = person.playerLevel[3]; person.hitDiff = damage; person.KillerId = playerId; person.updateRequired = true; person.hitUpdateRequired = true; } } } } }
ca69173e-7b89-4821-a22d-0ce6c127e5e6
1
public boolean jumpMayBeChanged() { return (catchBlock.jump != null || catchBlock.jumpMayBeChanged()); }
ff64e17a-afd4-4c18-a226-ea6095cc06fc
4
@Override public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws IOException, ServletException { Integer id = null; String name = null; String surname = null; Date dateOfBirth = null; Double salary = null; String salaryType = null; Employee newEmp = null; String message = null; try { id=Integer.valueOf(request.getParameter("id")); name=request.getParameter("name"); surname=request.getParameter("surname"); dateOfBirth=DateParser.getDateFromString(request.getParameter("dateofbirth")); salary=Double.valueOf(request.getParameter("salary")); salaryType=request.getParameter("salarytype"); request.getParameter("name"); if(salaryType.equals("fixedsalary")) { newEmp = new FixedSalaryEmployee(id, name, surname, dateOfBirth, salary); }else if(salaryType.equals("hourlywages")){ newEmp = new HourlyWageEmployee(id, name, surname, dateOfBirth, salary); } Company company = Company.getInstance(); company.getEmployees().add(newEmp); }catch (Exception e){ e.printStackTrace(); } message=(newEmp!=null)?"Successfully added:"+newEmp.toString():"error"; request.setAttribute("message", message); request.getRequestDispatcher("/WEB-INF/addinfo.jsp").forward(request, response); }
bb8b89e6-6219-4bbf-98b1-be96b8696d4f
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Pessoa)) { return false; } Pessoa other = (Pessoa) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
0aafa330-c407-4b43-bd7f-e60360f9894e
9
public boolean eventGeneratable(String eventName) { if (m_listenee == null) { return false; } if (m_listenee instanceof EventConstraints) { if (eventName.equals("instance")) { if (!((EventConstraints)m_listenee). eventGeneratable("incrementalClassifier")) { return false; } } if (eventName.equals("dataSet") || eventName.equals("trainingSet") || eventName.equals("testSet")) { if (((EventConstraints)m_listenee). eventGeneratable("batchClassifier")) { return true; } if (((EventConstraints)m_listenee).eventGeneratable("batchClusterer")) { return true; } return false; } } return true; }
20b4eb87-1455-4632-a2b4-65dc55cde0cb
6
TabbedPane() { super(new GridLayout(1, 1)); JTabbedPane tabbedPane = new JTabbedPane(); java.net.URL imgURL = getClass().getResource("img/db.jpg"); ImageIcon iconDB = new ImageIcon(imgURL); panelDB = new JPanelCluster("MINE", new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { try{ learningFromDBAction(); } catch (SocketException e1) { JOptionPane.showMessageDialog(panelFile, "Errore! - Impossibile Connettersi al Server\n\nDettagli:\n" + e1); } catch (IOException e1) { JOptionPane.showMessageDialog(panelFile, e1); } catch (ClassNotFoundException e1) { JOptionPane.showMessageDialog(panelFile, e1); } } }); tabbedPane.addTab("DB", iconDB, panelDB, "Kmeans from Database"); imgURL = getClass().getResource("img/file.jpg"); ImageIcon iconFile = new ImageIcon(imgURL); panelFile = new JPanelCluster("STORE FROM FILE", new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { try{ learningFromFileAction(); } catch (SocketException e1) { JOptionPane.showMessageDialog(panelFile, "Errore! - Impossibile Connettersi al Server\n\nDettagli:\n" + e1); } catch (IOException e1) { JOptionPane.showMessageDialog(panelFile, e1); } catch (ClassNotFoundException e1) { JOptionPane.showMessageDialog(panelFile, e1); } } }); tabbedPane.addTab("FILE", iconFile, panelFile,"Kmeans from File"); add(tabbedPane); tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); }
b7921633-3988-458b-875e-f6af8e185c9b
3
private void setPauseResume(ButtonMode mode) { BattleRunner runner = engine.getCurrentBattle(); if(mode == ButtonMode.PAUSE) { if(runner != null) { runner.setPaused(true); } btnPause.setText("Resume"); } else { if(runner != null) { runner.setPaused(false); } btnPause.setText("Pause"); } }
55c17911-cb9b-41f4-b986-8a4c67b4ba77
1
public static void main(String[] args) throws InterruptedException { Thread [] threads = new Thread[5]; CountDownLatch latch = new CountDownLatch(5);//tell it how many count downs there will be for(int i = 0; i<threads.length; i++){ final int current = i; threads[i] = new Thread(){ public void run(){ System.out.println(current); latch.countDown(); } }; threads[i].start(); } latch.await();//waits until the condition is met, will wait forever if need be /*int alive = threads.length; while(alive > 0){ alive = 0; for(int i = 0; i<threads.length; i++){//if no threads are alive then alive will //stay = 0, and loop will end if(threads[i].isAlive()){ alive++; } } }*/ System.out.println("finished"); }
89b9a1b4-3537-416e-ba5a-eaa6f18c76c0
5
public void addSum(int[] num,List<Integer> list,int target,int index){ if(target <= 0){ if(target == 0 && !result.contains(list)) result.add(new ArrayList<Integer>(list)); return; } for (int i = index;i < num.length ;i++ ) { if(num[i] > target) break; list.add(num[i]); addSum(num,list,target-num[i],i+1); list.remove(list.size()-1); } }
c371e96c-3df4-4595-a81a-0653cbc654fd
1
public Encryption(String m, String k) { if (k != "error") { char[] ck = fill(k); int[] i = fill1(ck); char[] cm = fill(m); int[] s = fill(cm); int[] r = scramble(s, i); o = em(r); }else{ //Do Nothing } return; }
1acb5463-0e8b-40bd-aa82-4dc040b10ef4
3
public void clearCache() { BufferedImage cache = cachedImage == null ? null : cachedImage.get(); if (cache != null) { cache.flush(); } cacheCleared = true; if (!isCacheable()) { cachedImage = null; } }
e15f1b4e-9297-4d10-9fca-2f72e37fe51f
4
public void setWidth(int width) { if(rotation == 90 || rotation == 270){ if(zoom == 1){ this.height = (int) (width/zoom); }else{ this.height = (int) (width/zoom)+1; } }else{ if(zoom == 1){ this.width = (int) (width/zoom); }else{ this.width = (int) (width/zoom)+1; } } }
a356c6f3-7540-4312-b3d6-bc3a8942970f
8
public int AddInstanceToBestCluster(Instance inst) { double delta; double deltamax; int clustermax = -1; if (clusters.size() > 0) { int tempS = 0; int tempW = 0; if (inst instanceof SparseInstance) { for (int i = 0; i < inst.numValues(); i++) { tempS++; tempW++; } } else { for (int i = 0; i < inst.numAttributes(); i++) { if (!inst.isMissing(i)) { tempS++; tempW++; } } } deltamax = tempS / Math.pow(tempW, m_Repulsion); for (int i = 0; i < clusters.size(); i++) { CLOPECluster tempcluster = clusters.get(i); delta = tempcluster.DeltaAdd(inst, m_Repulsion); // System.out.println("delta " + delta); if (delta > deltamax) { deltamax = delta; clustermax = i; } } } else { CLOPECluster newcluster = new CLOPECluster(); clusters.add(newcluster); newcluster.AddInstance(inst); return clusters.size() - 1; } if (clustermax == -1) { CLOPECluster newcluster = new CLOPECluster(); clusters.add(newcluster); newcluster.AddInstance(inst); return clusters.size() - 1; } clusters.get(clustermax).AddInstance(inst); return clustermax; }
1bf68c47-236b-401f-9fbe-67a06b75eaae
9
private void okButtonClick(ActionEvent evt) { Object[] selectedValues = templatesList.getSelectedValues(); if (selectedValues.length==0) { JOptionPane.showMessageDialog(this, "请选择模板.", "提示", JOptionPane.INFORMATION_MESSAGE); return; } String targetProject = textTargetProject.getText(); if (StringUtil.isEmpty(targetProject)) { JOptionPane.showMessageDialog(this, "请输入代码保存路径.", "提示", JOptionPane.INFORMATION_MESSAGE); return; } String basePackage = textBasePackage.getText(); if (StringUtil.isEmpty(basePackage)) { JOptionPane.showMessageDialog(this, "请输入基准包.", "提示", JOptionPane.INFORMATION_MESSAGE); return; } String moduleName = textModuleName.getText(); if (StringUtil.isEmpty(moduleName)) { JOptionPane.showMessageDialog(this, "请输入模块名.", "提示", JOptionPane.INFORMATION_MESSAGE); return; } String tableAlias = textTableAlias.getText(); if (StringUtil.isEmpty(moduleName)) { JOptionPane.showMessageDialog(this, "请输入表别名.", "提示", JOptionPane.INFORMATION_MESSAGE); return; } configuration.setTagertProject(targetProject); configuration.setBasePackage(basePackage); configuration.setModuleName(moduleName); tableModel.setTableAlias(tableAlias); Map<String, Object> model = new HashMap<String, Object>(); model.put("tagertProject", configuration.getTagertProject()); model.put("basePackage", configuration.getBasePackage()); model.put("moduleName", configuration.getModuleName()); model.put("table", tableModel); for (TemplateElement templateElement : configuration.getTemplates()) { templateElement.setSelected(false); } int count = selectedValues.length; for (int i=0;i<count; i++) { try { Object selectedObject = selectedValues[i]; TemplateElement templateElement = (TemplateElement) selectedObject; templateElement.setSelected(true); TemplateEngine templateEngine = engineBuilder.getTemplateEngine(templateElement.getEngine()); if(templateEngine==null){ JOptionPane.showMessageDialog(this, "没有对应的模板引擎: "+templateElement.getEngine(), "错误", JOptionPane.ERROR_MESSAGE); } else { templateEngine.processToFile(model, templateElement); } } catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); } } configuration.save(); JOptionPane.showMessageDialog(this, "生成完毕.", "提示", JOptionPane.INFORMATION_MESSAGE); }
5ee451f3-260b-48b8-975b-aaa0c3466764
6
public final boolean is888() { if (!trueColour) return false; if (bpp != 32) return false; if (depth != 24) return false; if (redMax != 255) return false; if (greenMax != 255) return false; if (blueMax != 255) return false; return true; }
432ba8bb-4c23-47af-9d91-2f0bb4f066ff
9
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed boolean ch=false,ch2=false; for (int i = 0; i < cont.getText().length(); i++) { if(cont.getText().charAt(i)=='['||cont.getText().charAt(i)==']'||!Character.isDigit(cont.getText().charAt(i))){ ch=true; break; } } for (int i = 0; i < addr.getText().length(); i++) { if(addr.getText().charAt(i)=='['||addr.getText().charAt(i)==']'){ ch2=true; break; } } if(ch2) JOptionPane.showMessageDialog(null, "please provide a correct address"); else if(ch) JOptionPane.showMessageDialog(null, "please provide a correct contact number"); else query.UpdateInfo(cont.getText(), addr.getText(), fn, ln); }//GEN-LAST:event_jButton3ActionPerformed
d7439d32-7734-4c02-a415-6c36cf7f1f0a
6
static public Object deserializeArray(InputStream in, Class elemType, int length) throws IOException { if (elemType==null) throw new NullPointerException("elemType"); if (length<-1) throw new IllegalArgumentException("length"); Object obj = deserialize(in); Class cls = obj.getClass(); if (!cls.isArray()) throw new InvalidObjectException("object is not an array"); Class arrayElemType = cls.getComponentType(); if (arrayElemType!=elemType) throw new InvalidObjectException("unexpected array component type"); if (length != -1) { int arrayLength = Array.getLength(obj); if (arrayLength!=length) throw new InvalidObjectException("array length mismatch"); } return obj; }
1b5e5cb9-6c40-47eb-9c09-f5c6227d2f80
1
@Override public int getIndex(TreeNode node) { if (!(node instanceof MyFile)) { throw new IllegalArgumentException("Unsupported type for the tree node " + node); } return this.files.indexOf(node); }
b0e2f9f6-ba38-4808-8cb0-c5aae2433864
2
public double PrecessionEpoch(double y, int type) { switch (type) { case JULIAN_EPOCH: return JulianEpoch(y); case BESSELIAN_EPOCH: return BesselianEpoch(y); default: return 0.0; } }
e0efdb06-7d14-4a52-a2ab-6617216a6075
6
public static Point[] getBlastRadius(Point point, int blockSize, int radius) { if(radius == 0) { return new Point[] {}; } else if(radius == 1) { return new Point[] {new Point(point.x, point.y - blockSize), new Point(point.x - blockSize, point.y), new Point(point.x + blockSize, point.y), new Point(point.x, point.y + blockSize)}; } else if(radius == 2) { return getThreeByThreeAround(point, blockSize); } else if((radius % 2) == 1) { /* * 2 -> 9 = 3^2, 3 -> 25 = 5^2 */ int i = 0; Point[] result = new Point[(int)Math.pow((radius * 2) - 1, 2)]; for(int x = (point.x - (blockSize * radius)); x <= point.x + (blockSize * radius); x += blockSize) { for(int y = (point.y - (blockSize * radius)); y <= point.y + (blockSize * radius); y += blockSize) { result[i++] = new Point(x, y); } } return result; } else { return new Point[] {new Point(point.x, point.y + blockSize)}; } }
2df81548-e3bc-4053-a975-3b162ad065b7
6
@Override public void repaint(Graphics graphics) { Graphics2D g2 = (Graphics2D) graphics; g2.setStroke(new BasicStroke(1)); g2.setFont(g2.getFont().deriveFont(10f)); int x = X; int y = Y; g2.setColor(COLOUR_BACKGROUND); g2.fillRect(x - 2, y - 2, WIDTH, HEIGHT); g2.setColor(COLOUR_BACKGROUND_BORDER); g2.drawRect(x - 2, y - 2, WIDTH, HEIGHT); y += 8; text(g2, "Falador", x, y); y += 2; x += 1; AllotmentEnum.FALADOR_N.object(ctx).repaint(g2, x, y); HerbEnum.FALADOR.object(ctx).repaint(g2, x + 32, y); FlowerEnum.FALADOR.object(ctx).repaint(g2, x + 16, y + 16); AllotmentEnum.FALADOR_S.object(ctx).repaint(g2, x + 20, y + 16); CompostEnum.FALADOR.object(ctx).repaint(g2, x + 24, y); y += 51; text(g2, "Catherby", x, y); y += 4; AllotmentEnum.CATHERBY_N.object(ctx).repaint(g2, x, y); HerbEnum.CATHERBY.object(ctx).repaint(g2, x + 32, y + 16); FlowerEnum.CATHERBY.object(ctx).repaint(g2, x + 16, y + 16); AllotmentEnum.CATHERBY_S.object(ctx).repaint(g2, x, y + 28); CompostEnum.CATHERBY.object(ctx).repaint(g2, x, y + 18); y += 51; text(g2, "Ardougne", x, y); y += 4; AllotmentEnum.ARDOUGNE_N.object(ctx).repaint(g2, x, y); HerbEnum.ARDOUGNE.object(ctx).repaint(g2, x + 32, y + 16); FlowerEnum.ARDOUGNE.object(ctx).repaint(g2, x + 16, y + 16); AllotmentEnum.ARDOUGNE_S.object(ctx).repaint(g2, x, y + 28); CompostEnum.ARDOUGNE.object(ctx).repaint(g2, x, y + 18); y += 51; text(g2, "Port", x, y); y += 8; text(g2, "Phasmatys", x, y); y += 4; AllotmentEnum.PORT_PHASMATYS_N.object(ctx).repaint(g2, x, y); HerbEnum.PORT_PHASMATYS.object(ctx).repaint(g2, x + 32, y); FlowerEnum.PORT_PHASMATYS.object(ctx).repaint(g2, x + 16, y + 16); AllotmentEnum.PORT_PHASMATYS_S.object(ctx).repaint(g2, x + 20, y + 16); CompostEnum.PORT_PHASMATYS.object(ctx).repaint(g2, x + 44, y + 28); y += 51; text(g2, "Trollheim", x, y); y += 2; HerbEnum.TROLLHEIM.object(ctx).repaint(g2, x, y); x = X + 57; y = Y + 8; text(g2, "Trees", x, y); y += 2; for (TreeEnum treeEnum : TreeEnum.values()) { treeEnum.object(ctx).repaint(g2, x, y); text(g2, treeEnum, x + 12, y + 8); y += 12; } y += 7; text(g2, "Fruit Trees", x - 1, y); y += 2; for (FruitTreeEnum treeEnum : FruitTreeEnum.values()) { treeEnum.object(ctx).repaint(g2, x, y); text(g2, treeEnum, x + 12, y + 8); y += 12; } y += 7; text(g2, "Spirit Trees", x - 1, y); y += 4; for (SpiritTreeEnum treeEnum : SpiritTreeEnum.values()) { treeEnum.object(ctx).repaint(g2, x, y); text(g2, treeEnum, x + 12, y + 8); y += 12; } y += 7; text(g2, "Cactus", x - 1, y); y += 2; for (CactusEnum treeEnum : CactusEnum.values()) { treeEnum.object(ctx).repaint(g2, x, y); text(g2, treeEnum, x + 12, y + 8); y += 12; } y += 7; text(g2, "Calquat", x - 1, y); y += 4; for (CalquatEnum treeEnum : CalquatEnum.values()) { treeEnum.object(ctx).repaint(g2, x, y); text(g2, treeEnum, x + 12, y + 8); y += 12; } y = Y; x = X - 64; g2.setColor(COLOUR_BACKGROUND); g2.fillRect(x - 2, y - 2, 62, CROP_STATES.length * 12 + 3); g2.setColor(COLOUR_BACKGROUND_BORDER); g2.drawRect(x - 2, y - 2, 62, CROP_STATES.length * 12 + 3); ++x; ++y; for (CropState state : CROP_STATES) { g2.setColor(state.color()); g2.fillRect(x, y, 9, 9); g2.setColor(Color.gray); g2.drawRect(x, y, 9, 9); text(g2, state, x + 12, y + 9); y += 12; } }
33248860-02ba-4b45-898e-35369e7783e6
0
public Fly(Animation left, Animation right, Animation deadLeft, Animation deadRight, Animation standingLeft, Animation standingRight, Animation jumpingLeft, Animation jumpingRight) { super(left, right, deadLeft, deadRight, standingLeft, standingRight, jumpingLeft, jumpingRight); }
bf1276ad-7d8f-40bf-bb17-200a24430883
6
public void run() { int p1Win = 0; int p2Win = 0; for (int i = 0; i < turn; i++) { Game game = null; if (i % 2 == 0) game = new Game(player1, player2, true); else game = new Game(player2, player1, true); game.clearBoard(); int result = game.play(); if (result == 1) { if (i % 2 == 0) { ++p1Win; System.out.println(player1.getName() + " wins!!"); } else { ++p2Win; System.out.println(player2.getName() + " wins!!"); } } else if (result == -1) { if (i % 2 == 0) { ++p2Win; System.out.println(player2.getName() + " wins!!"); } else { ++p1Win; System.out.println(player1.getName() + " wins!!"); } } else { System.out.println("draw!!"); } } System.out.println(); System.out.println("----------------------------------"); System.out.println(player1.getName() + " won the game " + p1Win + " times."); System.out.println(player2.getName() + " won the game " + p2Win + " times."); }
18cb7146-313c-4ef3-9777-5527ac964280
9
public void await() { // Set to 1 for ourselves. readyCount = 1; // Send out-going confirmations. new Thread(new Runnable() { @Override public void run() { for (ServerIdentifier identifier : servers) { if (identifier.equals(myIdentifier)) { continue; } try { Socket outSocket = identifier.createSocket(); BufferedReader in = new BufferedReader(new InputStreamReader(outSocket.getInputStream())); PrintWriter out = new PrintWriter(outSocket.getOutputStream(), true); out.println(myIdentifier.toString()); // Wait for response. String response = in.readLine(); if (BARRIER_ACK.equals(response)) { markReady(identifier); } in.close(); out.close(); outSocket.close(); } catch (IOException e) { // Problem connecting. } } } }).start(); // Accept in-coming confirmations. ServerSocket barrierSocket = null; try { barrierSocket = new ServerSocket(myIdentifier.getPort()); barrierSocket.setSoTimeout(1000); while (readyCount < servers.size()) { Socket client; try { client = barrierSocket.accept(); } catch (IOException e) { // Just a timeout, carry on. continue; } BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream(), true); ServerIdentifier identifier = ServerIdentifier.parse(in.readLine().trim()); markReady(identifier); out.println(BARRIER_ACK); in.close(); out.close(); client.close(); } } catch (IOException e) { throw new RuntimeException("Error waiting for all servers to initialize.", e); } finally { if (barrierSocket != null) { try { barrierSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
4cfa53ea-1356-4d4b-9688-e41ed2e1fb4c
4
@Override public void paintComponent(Graphics g){ Paint paint; Graphics2D g2d; if (g instanceof Graphics2D) { g2d = (Graphics2D) g; } else { System.out.println("Error"); return; } RenderingHints qualityHints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); qualityHints.put(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(qualityHints); if(this.supprimee){ paint = new GradientPaint(0,0, this.couleur==Couleur.NOIR?Color.RED:Color.WHITE, getWidth(), getHeight(), this.couleur==Couleur.NOIR?Color.DARK_GRAY:Color.RED); g2d.setPaint(paint); g.fillOval(5, 5, getWidth()-10, getHeight()-10); } else{ paint = new GradientPaint(0,0, getBackground(), getWidth(), getHeight(), getForeground()); g2d.setPaint(paint); g.fillOval(5, 5, getWidth()-10, getHeight()-10); } }
50a9ee97-09fc-4ed0-b360-5a1890a3a596
6
public String getInsertStatement(String ver, int book, int chapter) throws ParseException, IOException { // String strBook = String.format("B%02d", book); // String strChapter = String.format("C%03d", chapter); String strHtml = getOneChapterContent(ver, getBookChapter(book, chapter)); int verse = 0; Document doc = Jsoup.parse(strHtml); Elements testing = doc.select("P"); StringBuilder sb = new StringBuilder(); sb.append("\nINSERT INTO `bible`.`bible` (`VERSION`, `BOOK`, `CHAPTER`, `VERSE`, `CONTENT`) VALUES"); for (Element src : testing) { // // filter out // if (src.toString().contains("<a href=")) { continue; } if (src.toString().length() <= 7) { continue; } if (src.toString().contains("<img src")) { continue; } if (src.toString().contains("<p>&nbsp;</p>")) { continue; } // // replace // String plain; plain = src.toString().replace("<p>", ""); plain = plain.replace("</p>", ""); plain = plain.replace("<i>", ""); plain = plain.replace("</i>", ""); if (ver.equals("tw")) { plain = plain.replace(" ", ""); plain = plain.replace(".", "。"); plain = plain.replace("、", ","); } else { // for English plain = plain.replace("'", "&rsquo;"); } // // compose SQL // verse++; // System.out.println("ver="+ver+" book"+book+" chapter="+chapter+" "+verse + "=> " + plain); String temp = String.format("%n('%s','%s','%s','%s','%s'),", ver, book, chapter, verse, plain); sb.append(temp); // System.out.println(temp); } sb.deleteCharAt(sb.length() - 1); sb.append(";"); // System.out.println(sb.toString()); return sb.toString(); }
21354a1c-ef31-4aed-a1d0-6d3e0c397bda
5
private void despacharSolicitud(Solicitud psolicitud) { Operario operario1 = (Operario) listaOperarios.get(0); // Si hay mas de un operario, entonces asignar la solicitud a quien // tenga menos asignadas. if (listaOperarios.size() > 1 && solicitudesDespachadas.size() > 0) { Operario operario2 = (Operario) listaOperarios.get(1); int op1Cont = 0; int op2Cont = 0; for (int i = 0; i < solicitudesDespachadas.size(); i++) { Solicitud solicitud = (Solicitud) solicitudesDespachadas.get(i); if (solicitud.getOperarioEncargado().getCedula() == operario1.getCedula()) { op1Cont++; } else { op2Cont++; } } // Si el operario 1 tiene mas solicitudes asignadas que el operario 2 // entonces asignarle la solicitud al operario 2. if (op1Cont > op2Cont) { psolicitud.asignarOperarioEncargado(operario2); } else { // Si el operario 2 tiene igual cantidad o mas solicitudes que // el operario 1, entonces asignar la solicitud al operario 1. psolicitud.asignarOperarioEncargado(operario1); } } else { // Si solo hay un operario en el centro, entoces asignarle // la solicitud. psolicitud.asignarOperarioEncargado(operario1); } // Cambiar el estado de la solicitud y agregarla a la lista de despachadas. psolicitud.setCondicionAtencion(Constantes.SOLICITUD_CONDICION_DESPACHADA); solicitudesDespachadas.add(psolicitud); }
10e5d2cd-7a22-4a70-b05c-54a56787ce0f
1
public int getSize() { int counter = 0; Occurrence temp = head; while (head != null) { counter++; head = head.next; } head = temp; return counter; }
af21167d-e38e-4ef4-9abd-b4ae032dc567
5
public void insert() { Connection conn = null; PreparedStatement pstmt = null; try { //1、加载驱动 Class.forName("com.mysql.jdbc.Driver"); String mysqlUrl = "jdbc:mysql://localhost:3306/rock"; //2、建立连接 conn = DriverManager.getConnection(mysqlUrl,"root","123456"); String sql = "insert into emp2(ename,sal) values(?,?)"; //3、选择处理快(预处理块) pstmt = conn.prepareStatement(sql); //4、拼接sql语句,填入执行参数,执行 pstmt.setString(1, "rock3"); pstmt.setDouble(2, 100.0); //5、分析结果 int result = pstmt.executeUpdate(); System.out.println(result); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //6、释放资源 try { if(null !=pstmt) { pstmt.close(); } if(null !=conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
dca9bb44-762d-41b8-a5c9-8ca9bac94f77
4
private static DefaultComboBoxModel createModel(Color[] colors, String[] names, boolean allowCustomColors) { DefaultComboBoxModel model = new DefaultComboBoxModel(); for (int i = 0; i < colors.length; i++) { Color c = colors[i]; String text = null; if (i < names.length) { text = names[i]; } if (null == text) { text = ColorValue.toText(c); } model.addElement(new ColorValue(text, c, false)); } if (allowCustomColors) { model.addElement(ColorValue.CUSTOM_COLOR); } return model; }
570d782b-ba5c-428b-9049-49fecbd148a4
5
private void addActionListeners() { importDataMenuItem.addActionListener(e -> firePropertyChange(MainWindowController.IMPORT, 0, 1)); exportDataMenuItem.addActionListener(e -> firePropertyChange(MainWindowController.EXPORT, 0, 1)); ItemListener itemListener = new ComboBoxItemListener(); integrationMethodsComboBox.addItemListener(itemListener); angleComboBox.addItemListener(itemListener); drawButton.addActionListener(e -> MainWindowView.this.firePropertyChange(MainWindowController.DRAW_BUTTON_CLICK, 0, 1)); resetButton.addActionListener(e -> MainWindowView.this.firePropertyChange(MainWindowController.RESET_BUTTON_CLICK, 0, 1)); //Add focus listener and verifier to all text fields using reflection for (Field f : MainWindowView.this.getClass().getDeclaredFields()) { if (f.getName().contains("TextField")) { try { ((JTextField) f.get(MainWindowView.this)).addFocusListener(new TextFieldFocusListener()); if (f.getName().contains("Points") || f.getName().contains("Spheres")) { ((JTextField) f.get(MainWindowView.this)).setInputVerifier(intInputVerifier); } else { ((JTextField) f.get(MainWindowView.this)).setInputVerifier(doubleInputVerifier); } } catch (IllegalAccessException ex) { logger.error(ex); } } } }
34c36789-2e7e-4582-981f-bae3111f6b20
1
private String makeName(DateTimeField fieldA, DateTimeField fieldB) { if (fieldA.getName().equals(fieldB.getName())) { return fieldA.getName(); } else { return fieldA.getName() + "/" + fieldB.getName(); } }
c44c1c8d-cc6d-46de-9002-31d943418a33
5
private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead > 0) { zzEndRead+= numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of stream if (numRead == 0) { int c = zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++] = (char) c; return false; } } // numRead < 0 return true; }
5e62087c-4a74-4cef-942c-df8d4666670b
0
public static void prochaineGeneration(JCellule[][] grid, double nbrGenerations, JLabel lblGeneration, JButton btnProchaineGeneration) { ControllerGrille.grid.incrementGeneration(nbrGenerations); synchroniser(grid, lblGeneration, btnProchaineGeneration); }
d3456143-0691-4143-b896-23ce0fc44782
4
public static void setQt (String id, char signe) throws ParseException { for (int i=0;i<list.size();i++){ if (list.get(i).getId() == Integer.parseInt(id)){ if (signe == 'd') list.remove(i); else if (signe == '+') list.get(i).setQt(list.get(i).getQt()+1); else list.get(i).setQt(list.get(i).getQt()-1); } } }
5fdcaa44-cea5-4789-b360-843fb74bf596
5
public static void main(String[] args) { /* Activity 2.1 Scanners */ Scanner k = new Scanner(System.in); while ( k.hasNext() ) { // press Ctrl/Cmd + D(?) to stop input int d = 0; String s = ""; if (k.hasNextInt()) { d = k.nextInt(); } if (k.hasNext()) { s = k.next(); k.nextLine(); // should burn the newline character } System.out.println(d + "\n" + s); /* so even if there is not a number, it will still print zero. This could be avoided, but it's not worth it in such a small example. Could be done by having a boolean value that is set to true inside the if-statements. */ } // Scanners should be closed - just a good habit. k.close(); /* Activity 2.2 Files */ // note this does not need a Scanner because we are not reading the file's contents. File f = new File("data1.txt"); System.out.println(f.length()); System.out.println(f.getAbsolutePath()); /* Activity 2.3 Files Again */ // we will print out all lines in the file, since I don't know what data will be in your data1.txt Scanner kk = null; try { kk = new Scanner (f); } catch (FileNotFoundException e) { System.out.println("Bad filename, exiting"); // Always nice to know what is happening System.exit(1); // System.exit(0) is exiting normally } while (kk.hasNextLine()) { System.out.println(kk.nextLine()); // could have created a local variable meh easier code } kk.close(); // buh bye! }
d918c1e8-95bd-47c8-835f-4f8ea7f3bca4
7
private void Competicao_ComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_Competicao_ComboBoxItemStateChanged //Atualiza Jornadas_ComboBox Jornada_ComboBox.removeAllItems(); Competicao competicao; int max_jornadas; if (Campeonato_RadioButton.isSelected()) { String key = "Escalao." + Escalao_ComboBox.getSelectedItem().toString(); competicao = a.getDAOCompeticao().get(key); if(competicao != null) { max_jornadas = competicao.getDAOJornada().size(key); for (int i=1; i<= max_jornadas; i++) Jornada_ComboBox.addItem(Integer.toString(i)); } } if (Torneio_RadioButton.isSelected()) { if(Competicao_ComboBox.getSelectedIndex()>-1){ String key = Competicao_ComboBox.getSelectedItem().toString(); competicao = a.getDAOCompeticao().get(key); if(competicao != null) { max_jornadas = competicao.getDAOJornada().size(key); for (int i=1; i<= max_jornadas; i++) Jornada_ComboBox.addItem(Integer.toString(i)); } } } }//GEN-LAST:event_Competicao_ComboBoxItemStateChanged
283a7ded-2f49-48e9-ac9e-68f0b0aee41b
5
public long skip(long n) throws IllegalArgumentException, IOException { if (lookaheadChar == UNDEFINED) { lookaheadChar = super.read(); } // illegal argument if (n < 0) { throw new IllegalArgumentException("negative argument not supported"); } // no skipping if (n == 0 || lookaheadChar == END_OF_STREAM) { return 0; } // skip and reread the lookahead-char long skiped = 0; if (n > 1) { skiped = super.skip(n - 1); } lookaheadChar = super.read(); // fixme uh: we should check the skiped sequence for line-terminations... lineCounter = Integer.MIN_VALUE; return skiped + 1; }
20ed58d0-aed2-4153-bd2c-d1991fc78fd8
7
public Piece makePiece(String s) { boolean color = 'W' == s.charAt(0); switch (s.charAt(1)) { case 'X': return new Blank(color); case 'B': return new Bishop(color); case 'R': return new Rook(color); case 'P': return new Pawn(color); case 'Q': return new Queen(color); case 'K': return new King(color); case 'N': return new Knight(color); default: return null; } }
ef53e4d6-2b37-44c4-8959-a624725f88e6
0
@Override public void windowIconified(WindowEvent e) { }
f08056d4-07b4-4e77-893e-0b4f56180437
2
public static String wrapString(String str, double maxLength) { StringTokenizer st = new StringTokenizer(str); double spaceLeft = maxLength; int spaceWidth = 1; StringBuilder sb = new StringBuilder(); while (st.hasMoreTokens()) { String word = st.nextToken(); if ((word.length() + spaceWidth) > spaceLeft) { sb.append("\n" + word + " "); spaceLeft = maxLength - word.length(); } else { sb.append(word + " "); spaceLeft -= (word.length() + spaceWidth); } } return sb.toString(); }
5d413e8a-e8fb-421e-b903-f9dc12d91c74
2
@Override public void printValueToConsole(List<Integer> list) { // checking input parameter for null if (list == null) { throw new IllegalArgumentException("array not specified!"); } System.out.printf("\n%s", "Value of array: \n"); for (Integer foo : list) { System.out.printf("%d, ", foo); } }
46b58a25-b9ef-4145-bd9b-22fa2a091c12
2
public static void hypothesizeLambda(GrammarEnvironment env, Grammar g) { LambdaProductionRemover remover = new LambdaProductionRemover(); Set lambdaDerivers = remover.getCompleteLambdaSet(g); if (lambdaDerivers.contains(g.getStartVariable())) { JOptionPane.showMessageDialog(env, "WARNING : The start variable derives lambda.\n" + "New Grammar will not produce lambda String.", "Start Derives Lambda", JOptionPane.ERROR_MESSAGE); } if (lambdaDerivers.size() > 0) { LambdaPane lp = new LambdaPane(env, g); env.add(lp, "Lambda Removal", new CriticalTag() { }); env.setActive(lp); return; } hypothesizeUnit(env, g); }
ad44dca9-5d10-40e1-8116-d321b9f7cebf
1
public byte[] removeAttribute(String name) { if (unknownAttributes != null) return (byte[]) unknownAttributes.remove(name); return null; }
df14dc61-4b76-4be2-b09d-f654b3d27eea
6
private boolean processGMCommand(MapleClient c, MessageCallback mc, String[] splitted) { DefinitionGMCommandPair definitionCommandPair = gmcommands.get(splitted[0]); MapleCharacter player = c.getPlayer(); if (definitionCommandPair != null) { try { definitionCommandPair.getCommand().execute(c, mc, splitted); } catch (IllegalCommandSyntaxException ex) { mc.dropMessage(ex.getMessage()); dropHelpForGMDefinition(mc, definitionCommandPair.getDefinition()); } catch (NumberFormatException nfe) { mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below."); dropHelpForGMDefinition(mc, definitionCommandPair.getDefinition()); } catch (ArrayIndexOutOfBoundsException ex) { mc.dropMessage("[The Elite Ninja Gang] The Syntax to your command appears to be wrong. The correct syntax is given below."); dropHelpForGMDefinition(mc, definitionCommandPair.getDefinition()); } catch (NullPointerException exx) { mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage()); System.err.println("COMMAND ERROR" + exx); } catch (Exception exx) { mc.dropMessage("An error occured: " + exx.getClass().getName() + " " + exx.getMessage()); System.err.println("COMMAND ERROR" + exx); } return true; } else { processInternCommand(c, mc, splitted); } return true; }
ea34cc02-3d92-4605-8867-8e7ac28a7573
9
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("rawtypes") Pair other = (Pair) obj; if (a == null) { if (other.a != null) { return false; } } else if (!a.equals(other.a)) { return false; } if (b == null) { if (other.b != null) { return false; } } else if (!b.equals(other.b)) { return false; } return true; }
1a19de45-52c5-44ec-a7ff-7c32b1cce514
8
public static int[] getTopBins(int[] bins, int binCount, int collapseBins){ int[] topBins = new int[binCount]; List<Integer> sortedBins = new ArrayList<Integer>(); Map<Integer, List<Integer>> binCountMap = new HashMap<Integer, List<Integer>>(); for(int i = 0; i < bins.length; ++i){ if(!binCountMap.containsKey(bins[i])){ binCountMap.put(bins[i], new ArrayList<Integer>()); } binCountMap.get(bins[i]).add(i); sortedBins.add(bins[i]); } Collections.sort(sortedBins); Collections.reverse(sortedBins); // sort descending Set<Integer> countedBins = new HashSet<Integer>(); int i = 0; int j = 0; while(i < binCount && j < sortedBins.size()){ int binValue = sortedBins.get(j++); int binIndex = binCountMap.get(binValue).remove(0); if(!countedBins.contains(binIndex)){ topBins[i++] = binIndex; countedBins.add(binIndex); // Add the other ones to ignore for(int b = 1; b < collapseBins / 2; b++){ if(binIndex + b < bins.length){ countedBins.add(binIndex + b); } if(binIndex - b >= 0){ countedBins.add(binIndex - b); } } } } return topBins; }
339ae46f-d5df-4860-9724-0b35c9d38077
1
public static boolean oneIn(int x) { if (random.nextInt(x) == 0) { return true; } return false; }
81566949-67ff-491e-a73c-f04eb400d240
6
protected BufferedImage getCache() { if (floodFill != null) return myCache; floodFill = new FloodFill(canvas,source,origin,threshold); floodEdge = null; int w = floodFill.maxX - floodFill.minX + 1; int h = floodFill.maxY - floodFill.minY + 1; int rgb = c1.getRGB(); myCache = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); if (c1.equals(c2)) { for (Point p : floodFill.set) myCache.setRGB(p.x - floodFill.minX,p.y - floodFill.minY,rgb); return myCache; } floodEdge = new EdgeDetect(floodFill,canvas); if (c2 != null) { int rgb2 = c2.getRGB(); for (Point p : floodFill.set) myCache.setRGB(p.x - floodFill.minX,p.y - floodFill.minY,rgb2); } for (Point p : floodEdge.set) myCache.setRGB(p.x - floodFill.minX,p.y - floodFill.minY,rgb); return myCache; }
d538ac3a-6404-461f-a6fc-6f7fdf5d149f
3
public boolean checkEnemies() { for (Tile t : getMap()) { if (t.getClass() == Road.class) { if (((Road) t).hasEnemy() != null) ; return true; } } return false; }
45bba1d3-362a-4a31-9d1c-8437a81ed9a1
9
public final void printHTML(PrintStream out) { out.println("=== " + fcommand + " ==="); if (!fcommandGrammar.trim().equals("")) { out.println("*Usage:*"); out.println(); out.println("{{{"); out.println("java randoop.main.Main " + fcommandGrammar); out.println("}}}"); out.println(); } if (!fwhere.trim().equals("")) { out.println("_Where_:"); out.println(); out.println(fwhere); out.println(); } if (!fsummary.trim().equals("")) { out.println("*Summary:*"); out.println(); out.println(fsummary); out.println(); } if (!finput.trim().equals("")) { out.println("*Input:*"); out.println(); out.println(finput); out.println(); } if (!foutput.trim().equals("")) { out.println("*Output:*"); out.println(); out.println(foutput); out.println(); } if (!fexample.trim().equals("")) { out.println("*Example use:*"); out.println("{{{"); out.println(fexample); out.println("}}}"); out.println(); } if (fnotes != null && fnotes.size() > 0) { out.println("*Notes:*"); out.println(); for (String note : fnotes) { out.println(" * " + note); } } }