text
stringlengths
14
410k
label
int32
0
9
@Override public void removeTray(Tray tray) { tx.begin(); for (State state : tray.getStates()) { tray.removeState(state); em.remove(state); } em.merge(tray); em.remove(tray); tx.commit(); }
1
@Override public void run() { Peer potentialPeer = null; int i; for(i=6881; i <=65536; i++) { if(portOpen(i)) break; } manager.setListeningPort(i); ServerSocket listeningSocket = null; try { listeningSocket = new ServerSocket(i); this.listeningSocket = listeningSocket; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Socket clientSocket = null; while(!manager.stopThreads) //need to break at some point, and close inputstream { try { clientSocket = listeningSocket.accept(); DataInputStream dis = new DataInputStream(clientSocket.getInputStream()); byte[] handshake = new byte[68]; dis.readFully(handshake); byte[] peerID = new byte[20]; System.arraycopy(handshake, handshake.length-20, peerID, 0, 20); potentialPeer = new Peer(clientSocket.getPort(), clientSocket.getInetAddress().getHostAddress(), peerID); potentialPeer.setSocket(clientSocket); potentialPeer.receivedHandshake = true; System.out.println("Received handshake from peer " + potentialPeer); byte[] peerHash = new byte[20]; System.arraycopy(handshake, (handshake.length-41), peerHash, 0, 20); if(!Tracker.containsPeer(manager.peers, potentialPeer)){ manager.peers.add(potentialPeer); Thread messageHandler = new Thread(new MessageHandler(manager, potentialPeer, torrentInfo)); Runtime.getRuntime().addShutdownHook(messageHandler); potentialPeer.setMessageHandler(messageHandler); messageHandler.start(); } else { System.out.println("We're already connected to this peer."); } } catch (IOException e) { //no print stacktrace } } }
6
@Test public void bishopOnFullBoard() { Map<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(BISHOP.toString(), 2); Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap) .withDimension(DIMENSION_6) .withBishop() .build(); assertThat("all elements are not present on each board", chessboard.placeFiguresOnBoard("bbbbbb\n" + "bbbbbb\n" + "bbbbbb\n" + "bbbbbb\n" + "bbbbbb\n" + "bbbbbb\n") .filter(board -> !board.contains(KING.getFigureAsString()) && !board.contains(QUEEN.getFigureAsString()) && board.contains(BISHOP.getFigureAsString()) && !board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && !board.contains(FIELD_UNDER_ATTACK_STRING) && !board.contains(EMPTY_FIELD_STRING) && leftOnlyFigures(board).length() == 36) .map(e -> 1) .reduce(0, (x, y) -> x + y), is(1)); }
7
public static Stella_Object accessTokenizerTableSlotValue(TokenizerTable self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Stella.SYM_STELLA_TRANSITIONS) { if (setvalueP) { self.transitions = ((StringWrapper)(value)).wrapperValue; } else { value = StringWrapper.wrapString(self.transitions); } } else if (slotname == Stella.SYM_STELLA_UNIQUE_STATE_NAMES) { if (setvalueP) { self.uniqueStateNames = ((Vector)(value)); } else { value = self.uniqueStateNames; } } else if (slotname == Stella.SYM_STELLA_STATE_NAMES) { if (setvalueP) { self.stateNames = ((Vector)(value)); } else { value = self.stateNames; } } else if (slotname == Stella.SYM_STELLA_LEGAL_EOF_STATES) { if (setvalueP) { self.legalEofStates = ((Vector)(value)); } else { value = self.legalEofStates; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + slotname + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return (value); }
8
public static int iterate(Complex z0) { Complex z = new Complex(z0); if (mandelbrot){ //Iterates the passed complex z after the formula z_next = z^2 +z0 for (int i = 0; i < maxIterations; i++) { if (z.abs() > 2.0) { return i; } z = z.times(z).plus(z0); } return maxIterations; } else { //Iterates the passed complex z after the formula z_next = z^2 + c //c is the complex number for which the Julia set is found for (int i = 0; i < maxIterations; i++) { if (z.abs() > 2.0) { return i; } z = z.times(z).plus(juliaConstant); } return maxIterations; } }
5
private Type compileArray(Type base) throws ParseException, IOException { // [ while ((tokenizer.tokenType() == Tokenizer.SYMBOL) && (tokenizer.symbol() == '[')) { advance("program not ended"); int length = compileConstValue().intValue(); base = new ArrayType(base, length); // ] if ((tokenizer.tokenType() != Tokenizer.SYMBOL) || (tokenizer.symbol() != ']')) { throw new ParseException("] is excepted", tokenizer.lineNumber()); } advance("program not ended"); } // the next token after array return base; }
4
public boolean isWriteable(Object bean, String name) { try { Object[] call = resolveNested(bean, name); if (call != null) { bean = call[0]; name = (String) call[1]; } } catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } catch (NoSuchMethodException e) { return false; } // Remove any subscript from the final name value name = resolver.getProperty(name); try { PropertyDescriptor desc = getPropertyDescriptor(bean, name); if (desc == null) { return false; } return invoker.isWriteable(bean, desc, false) || invoker.isWriteable(bean, desc, true); } catch (IllegalAccessException e) { return (false); } catch (InvocationTargetException e) { return (false); } catch (NoSuchMethodException e) { return (false); } }
9
public static void main(String[] args) { //загрузка настроек для интерфейса try { getConfig(); } catch (IOException e) { e.printStackTrace(); } //установка скина для приложения java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { SubstanceLookAndFeel laf = new SubstanceMarinerLookAndFeel(); UIManager.setLookAndFeel(laf); String skinClassName = "org.pushingpixels.substance.api.skin."+skin+"Skin"; SubstanceLookAndFeel.setSkin(skinClassName); JDialog.setDefaultLookAndFeelDecorated(true); } catch (UnsupportedLookAndFeelException e) { throw new RuntimeException(e); } } }); //главная функция программы java.awt.EventQueue.invokeLater(new Runnable() { @SuppressWarnings("static-access") public void run() { frame = new MainFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); try{ @SuppressWarnings("resource") Socket telnet = new Socket(Phone.AsteriskIp, 5038); telnet.setKeepAlive(true); telnetWriter = new PrintWriter(telnet.getOutputStream()); telnetReader = new BufferedReader(new InputStreamReader(telnet.getInputStream())); telnetWriter.print("Action: login\r\n"); telnetWriter.print("UserName: "+Phone.ReadUser+"\r\n"); telnetWriter.print("Secret: "+Phone.ReadUserPassword+"\r\n\r\n"); telnetWriter.flush(); } catch (SocketException e1) { e1.printStackTrace();} catch (IOException e1) { e1.printStackTrace();} AsteriskThread = new AsteriskThread(); AsteriskThread.start(); } }); }
4
public static String timeIntervalToString(long millis) { StringBuffer sb = new StringBuffer(); if (millis < 10 * Constants.SECOND) { sb.append(millis); sb.append("ms"); } else { boolean force = false; String stop = null; for (int ix = 0; ix < units.length; ix++) { UD iu = units[ix]; long n = millis / iu.millis; if (force || n >= iu.threshold) { millis %= iu.millis; sb.append(n); sb.append(iu.str); force = true; if (stop == null) { if (iu.stop != null) { stop = iu.stop; } } else { if (stop.equals(iu.str)) { break; } } } } } return sb.toString(); }
7
public static void sortString(String[] strings, int longestBit) { int currBit = 1; int bucketNum = 256+1; // Additional one bit for the string which is smaller than the longestBit size String[][] bucket = new String[bucketNum][strings.length]; int[] bucketCount = new int[bucketNum]; while (currBit<=longestBit) { for (int i=0; i<strings.length; i++) { String currString = strings[i]; if(longestBit-currBit>=currString.length()) { // current string is smaller than the longestBit size // And then put it into the last bucket bucket[256][bucketCount[256]] = strings[i]; bucketCount[256]++; } else { char currChar = currString.charAt(longestBit-currBit); bucket[currChar][bucketCount[currChar]] = strings[i]; bucketCount[currChar]++; } } int k = 0; if(bucketCount[256] != 0) { for (int j=0; j<bucketCount[256]; j++) { strings[k] = bucket[256][j]; k++; } bucketCount[256] = 0; } for (int i=0; i<bucketNum-1; i++) { if (bucketCount[i] != 0) for (int j=0; j<bucketCount[i]; j++) { strings[k] = bucket[i][j]; k++; } bucketCount[i] = 0; } k = 0; currBit++; } }
8
public final void execute(CommandSender sender, String[] args) { this.isPlayer = sender instanceof Player; if (this.playersOnly() && !this.isPlayer) { error(sender, "MEOW MEOW MEOW MEOW MEOW MEOW MEOW"); return; } if (this.isPlayer) { if (this.getPermission() != null && !sender.hasPermission(this.getPermission())) { error(sender, "Sorry, you don't have permission for this command."); return; } } this.perform(sender, args); }
5
@Override public String toString() { return getName(); }
0
public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int a = 0; for(String ln;(ln = in.readLine())!=null;){ if(a>0)sb.append("\n"); int n = parseInt(ln); HashMap<String, int[]> sums = new HashMap<String, int[]>(); String names[] = new String[n]; StringTokenizer st = new StringTokenizer(in.readLine()); for(int i=0;i<n;++i) sums.put(names[i]=st.nextToken(), new int[3]); for(int i=0;i<n;++i){ st = new StringTokenizer(in.readLine()); String name = st.nextToken(); int costGit = parseInt(st.nextToken()); int m = parseInt(st.nextToken()); sums.get(name)[0]=-costGit; sums.get(name)[2]=m; for(int j=0;j<m;++j){ String friend = st.nextToken(); sums.get(friend)[1]+=ceil(costGit/m); } } for(int i=0;i<n;++i){ int val = 0; if(sums.get(names[i])[2]>0){ val = (sums.get(names[i])[0]*-1)-(((int) floor((sums.get(names[i])[0]*-1)/sums.get(names[i])[2]))*sums.get(names[i])[2]); sums.get(names[i])[0]=(int) (sums.get(names[i])[0]+sums.get(names[i])[1])+val; }else { sums.get(names[i])[0]=sums.get(names[i])[1]; } sb.append(names[i]).append(" ").append(sums.get(names[i])[0]).append("\n"); } a++; } System.out.print(new String(sb)); }
7
double read(boolean first) { Point2D centre = new Point2D.Double(localPosition.getX(), localPosition.getY()); Point2D front = new Point2D.Double(localPosition.getX() + range * Math.cos(localPosition.getT()), localPosition.getY() + range * Math.sin(localPosition.getT())); // reads the robot's position robot.readPosition(robotPosition); // center's coordinates according to the robot position robotPosition.rotateAroundAxis(centre); // front's coordinates according to the robot position robotPosition.rotateAroundAxis(front); double minDistance = -1.0; for (int i = 0; i < environment.getObstacles().size(); i++) { // This is really dirty: the laser uses direct access to environment's obstacles Obstacle obstacle = environment.getObstacles().get(i); if (!obstacle.getOpaque()) { double dist = pointToObstacle(obstacle.getPolygon(), centre, front, first); if (minDistance == -1.0 || (dist > 0 && dist < minDistance)) { minDistance = dist; if (minDistance > -1 && first) { return minDistance; } } } } if (minDistance > 0) return minDistance; return -1.0; }
8
public void setDataRejestracji(Date dataRejestracji) { this.dataRejestracji = dataRejestracji; }
0
public List<ScriptCoverageCount> getEmptyCoverageData(Set<String> urisAlreadyProcessed) { List<ScriptCoverageCount> scripts = new ArrayList<ScriptCoverageCount>(); for (File file: fileScanner.getFiles(urisAlreadyProcessed)) { String uri = ioUtils.getRelativePath(file, config.getDocumentRoot()); SourceProcessor sourceProcessor = new SourceProcessor(config, uri); try { sourceProcessor.instrumentSource(ioUtils.loadFromFileSystem(file)); ScriptCoverageCount script = new ScriptCoverageCount("/"+uri, new ArrayList<Integer>( sourceProcessor.getInstrumenter().getValidLines()), sourceProcessor.getInstrumenter().getNumFunctions(), sourceProcessor.getBranchInstrumentor().getLineConditionMap()); scripts.add(script); } catch (RuntimeException t) { logger.log(SEVERE, format("Problem parsing %s", uri), t); } } return scripts; }
2
private static String[] readNames(String filePath) throws IOException { FileReader fr = new FileReader(filePath); BufferedReader textReader = new BufferedReader(fr); String line = textReader.readLine(); int num = 0; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == '\"') { num++; } } num = (num / 2); String[] names = new String[num]; for (int i = 0; i < names.length; i++) { if (line.indexOf(',') != -1) { int pos = line.indexOf(','); names[i] = line.substring(1, pos - 1); line = line.substring(pos + 1); } else if (line.length() > 2) { names[i] = line.substring(1, line.length() - 1); break; } } textReader.close(); return names; }
5
static boolean isStandardProperty(Class clazz) { return clazz.isPrimitive() || clazz.isAssignableFrom(Byte.class) || clazz.isAssignableFrom(Short.class) || clazz.isAssignableFrom(Integer.class) || clazz.isAssignableFrom(Long.class) || clazz.isAssignableFrom(Float.class) || clazz.isAssignableFrom(Double.class) || clazz.isAssignableFrom(Character.class) || clazz.isAssignableFrom(String.class) || clazz.isAssignableFrom(Boolean.class); }
9
@Override final public void set_hand_to_hand(int level){ if(level >= 15){ bonus_dodge = 3; number_of_attacks = 7; number_actions = 7; bonus_strike = 2; crit_range = 19; } else if(level >= 12){ bonus_dodge = 3; number_of_attacks = 6; number_actions = 6; bonus_strike = 2; crit_range = 19; } else if(level >= 11){ bonus_dodge = 3; number_of_attacks = 6; number_actions = 6; bonus_strike = 1; crit_range = 19; } else if(level >= 9){ bonus_dodge = 2; number_of_attacks = 6; number_actions = 6; bonus_strike = 1; crit_range = 19; } else if(level >= 6){ bonus_dodge = 2; number_of_attacks = 5; number_actions = 5; bonus_strike = 1; crit_range = 19; } if(level >= 4){ bonus_dodge = 2; number_of_attacks = 5; number_actions = 5; bonus_strike = 1; } else if(level >= 2){ bonus_dodge = 2; number_of_attacks = 4; number_actions = 4; } else if(level == 1){ number_of_attacks = 4; number_actions = 4; } }
8
private void renderSecondSet(String choice, final GameContainer gc) { secondGroup.removeAll(); /* secondGroup.setSize(85, 130); secondGroup.setLocation(100, 465); secondGroup.setOpaque(true); secondGroup.setBackground(Color.black); RowLayout layout = new RowLayout(false, RowLayout.LEFT, RowLayout.CENTER); secondGroup.setLayout(layout); secondGroup.setZIndex(1); display.add(secondGroup); //display.reinit(); //display.ensureZOrder(); //display.add(content); */ switch (choice) { case "Physical": { ArrayList<Integer> usableAbilities = battlemanager.getAbilities(this.currenteffenttar.getNextPC()); //String[] row1 = new String[]{"One-Handed", "Two-Handed", "Close Quarters", "Projectile Weapons"}; for (final int s : usableAbilities) { String label = SkillFactory.getModel(s).getName(); Button tempButton = new Button(label); tempButton.setSize(10, secondGroup.getHeight() / 5); tempButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // Cursor cursor = new Cursor("data/Target.ani"); gc.setMouseCursor("data/Target.png", 16, 16); targeting = true; currentchosenaction = s; // gc.setmou } catch (SlickException ex) { Logger.getLogger(Battle.class.getName()).log(Level.SEVERE, null, ex); } } }); tempButton.setBorderRendered(false); tempButton.setOpaque(true); tempButton.setBackground(Color.cyan); //TODO: FIX ME tempButton.pack(); tempButton.setWidth(secondGroup.getWidth()); secondGroup.add(tempButton); } display.add(secondGroup); break; } case "Magical": { String[] row1 = new String[]{"Single-Target", "Multi-Target", "Buff / Debuff"}; for (final String s : row1) { Button tempButton = new Button(s); tempButton.setSize(10, secondGroup.getHeight() / 5); tempButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { renderThirdSet(s); } }); tempButton.setBorderRendered(false); tempButton.setOpaque(true); tempButton.setBackground(Color.cyan); //TODO: FIX ME tempButton.pack(); tempButton.setWidth(secondGroup.getWidth()); secondGroup.add(tempButton); } display.add(secondGroup); break; } case "Flee": { secondGroup.removeAll(); display.add(secondGroup); break; } case "Inventory": { secondGroup.removeAll(); display.add(secondGroup); break; } case "Attack": { secondGroup.removeAll(); display.add(secondGroup); break; } } }
8
public void knapsack(int[] wt, int[] val, int W, int N) { long negativeInfinity = Long.MIN_VALUE; long[][] m = new long[N + 1][W + 1]; long[][] sol = new long[N + 1][W + 1]; for (int i = 1; i <= N; i++) { for (int j = 0; j <= W; j++) { long m1 = m[i - 1][j]; long m2 = negativeInfinity; if (j >= wt[i]) { m2 = m[i - 1][j - wt[i]] + val[i]; } m[i][j] = Math.max(m1, m2); sol[i][j] = m2 > m1 ? 1 : 0; } } long[] selected = new long[N + 1]; for (int n = N, w = W; n > 0; n--) { if (sol[n][w] != 0) { selected[n] = 1; w = w - wt[n]; } else { selected[n] = 0; } } looted = 0; for (int i = 1; i < N + 1; i++) { if (selected[i] == 1) { looted += val[i]; } } }
8
public void actionPerformed(ActionEvent e) { if (aliens.size()==0) { String msg = "You won"; String msg1 = "Score = " + score+ "Topscore!!"; timer = new Timer(10, this); timer.start(); ingame = false; } ArrayList ms = craft.getMissiles(); for (int i = 0; i < ms.size(); i++) { missile m = (missile) ms.get(i); if (m.isVisible()) m.move(); else ms.remove(i); } for (int i = 0; i < aliens.size(); i++) { Alien a = (Alien) aliens.get(i); if (a.isVisible()) a.move(); else aliens.remove(i); } craft.move(); checkCollisions(); repaint(); }
5
public T[] getFooArray() { return fooArray; }
0
public Result[] SendLong(Submit submit) { if (this.LoginResult.ErrorCode == 0) { return this.pconnect.SendLong(submit); } else { Result [] result=new Result[1]; result[0]=this.LoginResult; return result; } }
1
public void setDeletedById(Integer id, boolean isDeleted) { String query = "update Task set isDeleted = :isDeleted where id = :taskId"; sessionFactory.getCurrentSession().createQuery(query) .setInteger("taskId", id) .setBoolean("isDeleted", isDeleted) .executeUpdate(); }
0
@Override public void logic2() { System.out.println("独自処理2 " + LoggerUtils.getSig()); }
0
@Override public void update(Observable arg0, Object arg1) { if(model.getState() != 2 || model.getPhase() == 1){ return; } Player owner = model.getTerritory(0).getOwner(); for(int i = 1; i < model.getTerritories().length; i++){ if(owner != model.getTerritory(i).getOwner()){ return; } } long stopTime = System.currentTimeMillis(); long runTime = stopTime - startTime; long seconds = runTime/1000; long minutes = seconds/60; seconds %= 60; long hours = minutes/60; minutes %= 60; lbTime.setText("Victory after " + (hours>10?"" + hours:"0" + hours) + ":" + (minutes>10?"" + minutes:"0" + minutes) + ":" + (seconds>10?"" + seconds:"0" + seconds)); setVisible(true); }
7
@Override public void loose(GameEvent event) { endGame("Verloren", event.getPoints()); }
0
public void checkType(Symtab st) { if (fc != null) { fc.setScope(scope); fc.setSymtab(st); } else if (oa != null) { oa.setScope(scope); oa.checkType(st); } else if (lg != null) { lg.setScope(scope); lg.checkType(st); } else if (ident != null) { ident.setScope(scope); ident.checkcontext(st); } }
4
public static void main(String[] args) throws IOException, InterruptedException { if (args.length == 0) { usage(); } File file = new File(args[0]); if (!file.exists()) { System.out.printf("File \"%s\" does not exist.%n", args[0]); System.exit(0); } if (file.length() % 4 != 0) { System.err.println("File does not seem to be set of 32bit integers. Its length is not divisible by 4."); } int threads = 1; if (args.length > 1) { try { threads = Integer.parseInt(args[1]); } catch (NumberFormatException ex) { usage(); } if (threads < 1) { System.err.println("Number of additional threads should be greater then 1"); usage(); } } ExternalSorter sorter = new ExternalSorter(); long start = System.currentTimeMillis(); SortResult sort = sorter.sort(file, null, threads, true); switch (sort) { case WELL_DONE: System.out.printf("File %s has been sorted in %d ms%n", file.getPath(), System.currentTimeMillis() - start); break; case ERROR: System.out.printf("File %s has not been sorted%n", file.getPath()); break; } }
8
public int getThickness() { return thickness; }
0
public static void remove_stopwords(String[] query, String[] stopwords) { Set<String> stopWordSet = new HashSet<>(); for (String s : stopwords) { stopWordSet.add(s); } for (String word : query) { if(!stopWordSet.contains(word)) { System.out.println(word); } } }
3
public UserCommand(TotalPermissions p) { plugin = p; }
0
private void batchEstimateDataAndMemory(boolean useRuntimeMaxJvmHeap, String outputDir, int reduceBase) throws IOException { //File mDataOutputFile = new File(outputDir, "eDataMappers.txt"); //File rDataOutputFile = new File(outputDir, "eDataReducers.txt"); File mJvmOutputFile = new File(outputDir, "eJvmMappers.txt"); File rJvmOutputFile = new File(outputDir, "eJvmReducers.txt"); if(!mJvmOutputFile.getParentFile().exists()) mJvmOutputFile.getParentFile().mkdirs(); //PrintWriter mDataWriter = new PrintWriter(new BufferedWriter(new FileWriter(mDataOutputFile))); //PrintWriter rDataWriter = new PrintWriter(new BufferedWriter(new FileWriter(rDataOutputFile))); PrintWriter mJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(mJvmOutputFile))); PrintWriter rJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(rJvmOutputFile))); //displayMapDataTitle(mDataWriter); //displayReduceDataTitle(rDataWriter); displayMapJvmCostTitle(mJvmWriter); displayReduceJvmCostTitle(rJvmWriter); for(int xmx = 1000; xmx <= 4000; xmx = xmx + 1000) { for(int ismb = 200; ismb <= 1000; ismb = ismb + 200) { for(int reducer = reduceBase; reducer <= reduceBase * 2; reducer = reducer * 2) { for(int xms = 0; xms <= 1; xms++) { //--------------------------Estimate the data flow--------------------------- //-----------------for debug------------------------------------------------- //System.out.println("[xmx = " + xmx + ", xms = " + xms + ", ismb = " + // ismb + ", RN = " + reducer + "]"); //if(xmx != 4000 || ismb != 400 || reducer != 16 || xms != 1) // continue; //if(xmx != 4000 || xms != 1 || ismb != 1000 || reducer != 9) // continue; //--------------------------------------------------------------------------- Configuration conf = new Configuration(); //long newSplitSize = 128 * 1024 * 1024l; conf.set("io.sort.mb", String.valueOf(ismb)); if(xms == 0) conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m"); else conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m" + " -Xms" + xmx + "m"); conf.set("mapred.reduce.tasks", String.valueOf(reducer)); //conf.set("split.size", String.valueOf(newSplitSize)); setNewConf(conf); // -------------------------Estimate the data flow------------------------- List<Mapper> eMappers = estimateMappers(); //don't filter the mappers with small split size List<Reducer> eReducers = estimateReducers(eMappers, useRuntimeMaxJvmHeap); String fileName = conf.getConf("mapred.child.java.opts").replaceAll(" ", "") + "-ismb" + ismb + "-RN" + reducer; displayMapperDataResult(eMappers, fileName , outputDir + File.separator + "eDataflow"); displayReducerDataResult(eReducers, fileName, outputDir + File.separator + "eDataflow"); // -------------------------Estimate the memory cost------------------------- InitialJvmCapacity gcCap = computeInitalJvmCapacity(); if(!gcCap.getError().isEmpty()) { System.err.println(gcCap.getError() + " [xmx = " + xmx + ", xms = " + xms + ", ismb = " + ismb + ", RN = " + reducer + "]"); } else { //filter the estimated mappers with low split size List<MapperEstimatedJvmCost> eMappersMemory = estimateMappersMemory(eMappers, gcCap); List<ReducerEstimatedJvmCost> eReducersMemory = estimateReducersMemory(eReducers, gcCap); displayMapperJvmCostResult(eMappersMemory, gcCap, mJvmWriter); displayReducerJvmCostResult(eReducersMemory, gcCap, rJvmWriter); } } } } } mJvmWriter.close(); rJvmWriter.close(); }
7
private void executeSelectCommandsOnNodes(final Command[] commands, final ObjectOutputStream clientOut) throws InterruptedException{ final int maxCounterMsg = numberOfNodes; final CountDownLatch latch = new CountDownLatch(maxCounterMsg); for(int i=0; i!=numberOfNodes; ++i){ final int index = i; if(commands[index] == null) continue; Thread t = new Thread(new Runnable() { @Override public void run() { // output to the console ++counterMsgSent; if(counterMsgSent == maxCounterMsg){ console.append("Command has been sent to " + counterMsgSent + " of " + maxCounterMsg + " nodes\n"); counterMsgSent = 0; } try { if(!nodeNames[index].equals(myName)){ if(nodesSocket[index] != null){ // send to the node nodesOut[index].writeObject(Message.NODE); nodesOut[index].writeObject(commands[index]); // receive from the node Data data = (Data)nodesIn[index].readObject(); while(data.nomoreselected == false){ synchronized (clientOut) { clientOut.writeObject(data); } data = (Data)nodesIn[index].readObject(); } } }else{ dataBase.executeSelect(commands[index], clientOut); } } catch (IOException e) { console.append("8. " + e.getMessage() + '\n'); nodesSocket[index] = null; nodesOut[index] = null; nodesIn[index] = null; } catch (ClassNotFoundException e) { console.append("9. " + e.getMessage() + '\n'); }finally{ latch.countDown(); } // output to the console ++counterMsgReceived; if(counterMsgReceived == maxCounterMsg){ console.append("Command has been recieved from " + counterMsgReceived + " of " + maxCounterMsg + " nodes\n"); counterMsgReceived = 0; } } }); t.start(); } latch.await(); }
9
public Double getMatch(String... searchForKeys){ for(String searchForKey : searchForKeys){ int found = 0; for(String key : keys){ if(searchForKey.equalsIgnoreCase(key)){ found++; } } if(found == 0){ match -= (1.0/searchForKeys.length); } } return (double)Math.round((this.match)*100); }
4
public void testConstructor_invalidObject() throws Throwable { try { new DateTime(new Object()); fail(); } catch (IllegalArgumentException ex) {} }
1
public void balanElimIzq( Retorno retorno ) { switch( balance ) { case BIZQ: if( izqNodo != null){ if( izqNodo.balance != BDER ) { retorno.respuesta = roteDer( ); if( retorno.respuesta.balance == BAL ) { retorno.respuesta.balance = BDER; retorno.respuesta.derNodo.balance = BIZQ; retorno.diferenciaAltura = false; } else { retorno.respuesta.balance = BAL; retorno.respuesta.derNodo.balance = BAL; } } else { retorno.respuesta = roteIzqDer( ); if(retorno.respuesta != null){ if( retorno.respuesta.balance == BIZQ ) { retorno.respuesta.derNodo.balance = BDER; } else { retorno.respuesta.derNodo.balance = BAL; } if( retorno.respuesta.balance == BDER ) { retorno.respuesta.izqNodo.balance = BIZQ; } else { retorno.respuesta.izqNodo.balance = BAL; } retorno.respuesta.balance = BAL; }}} break; case BAL: balance = BIZQ; retorno.diferenciaAltura = false; retorno.respuesta = this; break; case BDER: balance = BAL; retorno.respuesta = this; break; } }
9
private void pesquisarProduto() { dtm = (DefaultTableModel) JT_Venda_Produtos.getModel(); String sql = ""; if (!JTF_Produto.getText().equals("") && !JTF_Codigo.getText().equals("0")) { sql = "SELECT id, descricao, valor_venda FROM b_produtos WHERE (id = " + JTF_Codigo.getText() + " AND descricao LIKE '%" + JTF_Produto.getText() + "%' AND liberar_venda = 1);"; //vender(sql); // } else if (!JTF_Produto.getText().equals("")) { // // // sql = "SELECT id, descricao, valor_venda FROM b_produtos WHERE (descricao LIKE '%" + JTF_Produto.getText() + "%' AND liberar_venda = 1);"; // // } else if(!JTF_Codigo.getText().equals("0")) { // // sql = "SELECT id, descricao, valor_venda FROM b_produtos WHERE (id = "+JTF_Codigo.getText()+" AND liberar_venda = 1);"; // // // } else if (!JTF_Codigo.getText().equals("")) { // // sql = "SELECT id, descricao, valor_venda FROM b_produtos WHERE id = " + JTF_Codigo.getText() + " AND liberar_venda = 1;"; // //} else if (!JTF_Produto.getText().equals("") && !JTF_Codigo.getText().equals("")) { // // sql = "SELECT id, descricao, valor_venda FROM b_produtos WHERE (descricao LIKE '%" + JTF_Produto.getText() + "%' AND id = " + JTF_Codigo.getText() + " AND liberar_venda = 1);"; // } else { // // sql = "SELECT id, descricao, valor_venda FROM b_produtos WHERE liberar_venda = 1;"; } else if (!JTF_Codigo.getText().equals("0")) { sql = "SELECT id, descricao, valor_venda FROM b_produtos WHERE (id = " + JTF_Codigo.getText() + " AND liberar_venda = 1);"; // vender(sql); } else { JOptionPane.showMessageDialog(null, "A descrição não pode estar em branco e o código "); } try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(new CoreSql().db_conexao); st = con.createStatement(); } catch (Exception e) { System.out.println("Erro: " + e.toString()); } try { rs = st.executeQuery(sql); limpaTabela(); while (rs.next()) { dtm.addRow(new Object[]{rs.getString("id"), rs.getString("descricao"), rs.getString("valor_venda")}); } } catch (SQLException ex) { System.out.println("Pesquina não encontrada: " + ex.toString()); } }
6
private ArrayList<Block> findLeafNode(Block root) { ArrayList<Block> leafList = new ArrayList<Block>(); Queue<Block> queue = new LinkedList<Block>(); HashSet<Block> visited = new HashSet<Block>(); queue.add(root); while (!queue.isEmpty()) { Block blk = queue.remove(); if (blk == null || visited.contains(blk)) { continue; } if (blk.isLeaf()) { leafList.add(blk); } else if (blk.getNextBlock() != null && blk.getNextBlock().isBackEdgeFrom(blk)) { // stupid const loop leafList.add(blk.getNextBlock()); } visited.add(blk); queue.add(blk.getNextBlock()); queue.add(blk.getNegBranchBlock()); } return leafList; }
6
private static int[][] FileToWeightedGraphArray(String dat) { int[][] A = null; FileInputStream fis = null; try { fis = new FileInputStream(dat); } catch (Exception e) { System.out.println(dat + " konnte nicht geoeffnet werden"); System.out.println(e.getMessage()); } try { InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); // Knotenanzahl lesen String einZeile; einZeile = br.readLine(); int n = new Integer(einZeile); // Kantenanzahl lesen einZeile = br.readLine(); int m = new Integer(einZeile); A = new int[m + 1][3]; // Knoten- und Kantenanzahl -> Array A[0][0] = n; A[0][1] = m; // Kanten lesen for (int i = 1; i <= m; i++) { einZeile = br.readLine(); int sepIndex1 = einZeile.indexOf(' '); int sepIndex2 = einZeile.indexOf(' ', sepIndex1 + 1); String vStr = einZeile.substring(0, sepIndex1); String uStr = einZeile.substring(sepIndex1 + 1, sepIndex2); String wStr = einZeile.substring(sepIndex2 + 1, einZeile.length()); int v = new Integer(vStr); int u = new Integer(uStr); int w = new Integer(wStr); if (!(u >= 0 && u < n && v >= 0 && v < n)) throw new Exception("Falsche Knotennummer"); A[i][0] = v; A[i][1] = u; A[i][2] = w; } } catch (Exception e) { System.out.println("Einlesen nicht erfolgreich"); System.out.println(e.getMessage()); } return A; }
7
@Override public void setValue(String value) { for (HTMLComponent c : getChildren()) { if (c instanceof HTMLOption) { HTMLOption op = (HTMLOption)c; // System.out.println("option: " + op); if (op.getName().equals(value)) { super.setValue(value); return; } } } System.err.printf("Warning: <select(%s)>.setValue: no <option> for %s%n", getName(), value); super.setValue(value); }
3
public void update() { if (xPos < 0) { xPos = 0; } else if (xPos > Main.WIDTH - size) { xPos = Main.WIDTH - size; } if (yPos < 0) { yPos = 0; } else if (yPos > Main.HEIGHT - size) { yPos = Main.HEIGHT - size; } if (health < 1) { alive = false; health = 0; } }
5
@Override public void actionPerformed(ActionEvent e) { int option = FktLib .beenden(null, "Beenden?", "Wollen Sie das Spiel beenden"); if (option == JOptionPane.YES_OPTION) { System.exit(0); }else if(option== JOptionPane.CANCEL_OPTION){ return; } }
2
public int compareTo(WordSpan s) { if (getStart() < s.getStart()) { return -1; } else if (getStart() == s.getStart()) { if (getEnd() > s.getEnd()) { return -1; } else if (getEnd() < s.getEnd()) { return 1; } else { return 0; } } else { return 1; } }
4
public static int[][] permutations(int[] a) { int permutations[][] = new int[1][a.length]; int[] tempCopy, aCopy; boolean foundAk; int k = 0, l = 0, n, p = 0, al, ak, r; a = bubbleSortIncreasing(a); //reset the array for algorithm permutations[p++] = Arrays.copyOf(a, a.length); aCopy = permutations[0]; for (; p < factorial(aCopy.length); p++) { foundAk = false; //reset variable //Step 1 find k such that a[k] < a[k+1] for (ak = 0; ak < a.length - 1; ak++) { if (aCopy[ak] < aCopy[ak + 1]) { foundAk = true; k = ak; } } if (foundAk) { //Step 2 find the largest l such that a[k] < a[l] for (al = k + 1; al < aCopy.length; al++) { if (aCopy[k] < aCopy[al]) { l = al; } } //Step 3 swap a[k] with a[l] ak = aCopy[k]; aCopy[k] = aCopy[l]; aCopy[l] = ak; //Step 4 reverse sequence from a[k+1] inclusively to final element tempCopy = Arrays.copyOfRange(aCopy, k + 1, aCopy.length); //revisit loop to use the numbers from tempCopy properly for (r = k + 1, n = tempCopy.length - 1; r < aCopy.length && n >= 0; r++, n--) { aCopy[r] = tempCopy[n]; } permutations = arrayAddLine(permutations, aCopy); } } return permutations; }
8
@Override public String getColumnName(int columnIndex) { String res = ""; switch (columnIndex) { case 0: res = "id"; break; case 1: res = "First Name"; break; case 2: res = "LastName"; break; case 3: res = "Age"; break; case 4: res = "StreetName"; break; case 5: res = "PhoneNumber"; break; default: break; } return res; }
6
public void setField(Integer field, String value) { switch(field) { case 1: field1 = value; updateMap.put("field1", value); return; case 2: field2 = value; updateMap.put("field2", value); return; case 3: field3 = value; updateMap.put("field3", value); return; case 4: field4 = value; updateMap.put("field4", value); return; case 5: field5 = value; updateMap.put("field5", value); return; case 6: field6 = value; updateMap.put("field6", value); return; case 7: field7 = value; updateMap.put("field7", value); return; case 8: field8 = value; updateMap.put("field8", value); return; } throw new IllegalArgumentException("Invalid field."); }
8
private String Pretreatment(String filePath) { String result = ""; String FileName = filePath; File myFile = new File(FileName); if (!myFile.exists()) { System.err.println("Can't Find " + FileName); } try { BufferedReader in = new BufferedReader(new FileReader(myFile)); String str; while ((str = in.readLine()) != null) { //System.out.println(replaceBlank(str)); result += replaceBlank(str); } in.close(); } catch (IOException e) { e.getStackTrace(); } // System.out.println(result); return result; }
3
public void setup(){ Object[] options = {"Browse", "Build"}; int i = JOptionPane.showOptionDialog(null, "There has been an error locating the startup file." + "\nPlease select below either 'Browse' to navigate to" + " the correct file" + "\nor 'Build' to provide the program with information to" + " rebuild the file.", "Error locating startup file", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); switch(i){ case 0: this.browse(); // Find the file break; case 1: this.rebuild(); // Rebuild the file break; case -1: // If the close button is pressed System.exit(0); break; default: // Should never really happen - defensive programming new ClubException("Error setting up the startup file", "This should never happen"); break; } this.verifyFile(); // Double check it's actually there }
3
public void run() { int amountInput = 0; //统计类的参数最好在一开始初始化 println ("This program find the largest and smallest numbers."); /* set a sentinel number */ int n = readInt ("? "); if ( n == SENTINEL) { println ("The program is terminated by your input of the setinel number. "); } /* variable amountInput is for counting the amount of numbers we've input. * variable largestNum and smallestNum is for the recording of the largest and the smallest number respectively.*/ int largestNum = n; int smallestNum = n; while (n != SENTINEL) { amountInput ++; if (n > largestNum){ largestNum = n; } if (n < smallestNum){ smallestNum = n; } n = readInt ("? "); //把读取放在while循环的最后,能避免使用break语句。并且,在你的版本里,amountInput的逻辑不直接。 } /* reports the result of the largest and the smallest numbers. */ if (amountInput != 0){ println ("smallest: " + smallestNum); println ("largest: " + largestNum); } }
5
public void body() { logger.info(super.get_name() + " is starting..."); // get the resource id if (resID < 0) { logger.severe("Invalid resource: " + GridSim.getEntityName(resID)); return; } boolean success = submitGridlets(); if(success) { logger.info(super.get_name() + " is collecting jobs..."); Sim_event ev = new Sim_event(); while (Sim_system.running()) { super.sim_get_next(ev); // if the simulation finishes then exit the loop if (ev.get_tag() == GridSimTags.END_OF_SIMULATION) { break; } // process the received event processEvent(ev); // if all the Gridlets have been collected if (completedJobs.size() == numGenJobs) { break; } } } else { logger.severe(super.get_name() + " was unable to submit the jobs."); } // shut down all the entities, including GridStatistics entity since // we used it to record certain events. shutdownGridStatisticsEntity(); shutdownUserEntity(); terminateIOEntities(); logger.info(super.get_name() + " is exiting..."); }
5
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (!_pendingRics.isEmpty()) createRenderers(); // column is index of table view, not of table model. // Must use JTable.getColumnName(int) instead of // TableModel.getColumnName(int) JComponent c = null; if (row != -1) { synchronized (this) { RecordRenderer rr = (RecordRenderer)_recordRows.elementAt(row); c = rr.fieldRenderer(table.getColumnName(column)); } } else // header { // for some reason, when moving columns value of column // is incremented by one. For now, just prevent the // array out of bounds exception. Operation will perform // correctly anyway. if (column >= getColumnCount()) column = getColumnCount() - 1; c = (JComponent)_headerRenderers.elementAt(column); } if (c == null) { // Create dummy renderer if (value == "XX") c = _emptyLabel; else c = new JLabel((String)value); c.setForeground(Color.black); // cache the header renderer if (row == -1) _headerRenderers.setElementAt(c, column); } if (row == -1) { ((JLabel)c).setText((String)value); c.setBorder(new BevelBorder(BevelBorder.RAISED)); } else { if (isSelected) c.setBackground(table.getSelectionBackground()); else c.setBackground(table.getBackground()); } return c; }
8
public boolean MouseUpListener(int mX, int mY, int button) { if(mainLogic.currentState == GameLogic.GameState.PLAYING) { currentMouseAction.onMouseUp(mX, mY, button); } return false; }
1
public boolean move(Matrix matrix, Square destination) { if (destination.getCharacter() != null) { if (destination.getCharacter().isAlive()) { return false; } } if (destination instanceof Door) { if (!((Door)destination).isOpen()) { return false; } } ((Square)matrix.getNode(x, y)).removeCharacter(); destination.addCharacter(this); x = destination.getX(); y = destination.getY(); HashMap<String, Item> takenItems = destination.getItems(); if (destination.getItems() != null) { for (Item item : takenItems.values()) { addItem(item); } destination.removeItems(); } return true; }
6
public static void main(String args[]) { int N = Integer.parseInt(args[0]); int a, b, c, d, a3, b3, c3, d3; for (a = 1; a <= N; a++) { a3 = a * a * a; if (a3 > N) break; for (b = a; b <= N; b++) { b3 = b * b * b; if (a3 + b3 > N) break; for (c = a + 1; b <= N; c++) { c3 = c * c * c; if (c3 > a3 + b3) break; for (d = c; d <= N; d++) { d3 = d * d * d; if (c3 + d3 > a3 + b3) break; if (c3 + d3 == a3 + b3) { System.out.print((a3+b3) + " = "); System.out.print(a + "^3 + " + b + "^3 = "); System.out.print(c + "^3 + " + d + "^3"); System.out.println(); } } } } } }
9
public static void main(String[] args) { try { Display.setTitle("TestThingy"); Display.setDisplayMode(new DisplayMode(1280, 720)); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } glMatrixMode(GL_PROJECTION); glLoadIdentity(); GL11.glOrtho(0, 1280, 0, 720, 1, -1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); testInit(); while(!Display.isCloseRequested()) { render(); } glDeleteBuffers(vboVertexHandle); glDeleteBuffers(vboColorHandle); }
2
public static <T extends DC> Set<Set<Pair<T,T>>> despatch(Pair<T,T> pair,Set<Set<Pair<T,T>>> sets) { if(pair==null) { return sets; } else { if(sets==null) { return new Set(new Set(pair,null),null); } else//pair!=null && sets!=null { if(sets.next==null) { return new Set(sets.a.ins(pair),null); } else { return new Set(sets.a.ins(pair),despatch(pair,sets.next)); } } } }
3
public DisplayObject addChild(DisplayObject child) { DisplayObjectImpl impl = ((ContainerImpl) overlay).addChild(child.getOverlay()); if (impl != null) { children.add(child); } return (impl != null ? child : null); }
2
@ Override public int compare(File lhs, File rhs) { if (lhs.isDirectory () && !rhs.isDirectory ()) { if (order == FileFolderOrder.DIRECTORY_FIRST) return -1; // list directories first else return 1; // list directories last } else if ( !lhs.isDirectory () && rhs.isDirectory ()) if (order == FileFolderOrder.DIRECTORY_FIRST) return 1; // list files first else return -1; // list files last else { String lhsName = FileComparatorUtils.getStandardizedName (lhs); String rhsName = FileComparatorUtils.getStandardizedName (rhs); // Use natural order comparison to determine file order return Strings.compareNatural (lhsName, rhsName); } }
6
private void affichageErreurs(List<Error> erreurs){ for(Error e : erreurs){ switch(e){ case raisonSocialeVide : this.labelErreurRaisonSociale.setText("Veuillez saisir une raison sociale"); break; case telephoneVide : this.labelErreurTelephone.setText("Veuillez saisir un numéro de telephone"); break; case telephoneInvalide : this.labelErreurTelephone.setText("Veuillez saisir un numéro de telephone valide"); break; case emailVide : this.labelErreurEmail.setText("Veuillez saisir une adresse email"); break; case emailInvalide : this.labelErreurEmail.setText("Veuillez saisir une adresse email valide"); break; case adresseVide : this.labelErreurAdresse.setText("Veuillez saisir une adresse"); break; case siretVide : this.labelErreurSiret.setText("Veuillez saisir un numéro de siret"); break; case siretInvalide : this.labelErreurSiret.setText("Veuillez saisir un numéro de siret valide"); break; } } }
9
@Override public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) { if (e.getDocument() == null) { setEnabled(false); } else { calculateEnabledState(e.getDocument().getTree()); } }
1
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler() .runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide // with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the // server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering // information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it // is the first time we are posting, // it is not a interval ping, so it evaluates to // FALSE // Each time thereafter it will evaluate to // TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to // false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
7
public boolean verifierEmplacement(Piece p) { for( int y=0;y<p.getLongueur();y++) { for(int x=0;x<p.getLargeur();x++) { if( 0<=y+p.getPositionY()&& y+p.getPositionY()<longueur && 0<=x+p.getPositionX() &&x+p.getPositionX()<largeur ) { if( grille[y+p.getPositionY()][x+p.getPositionX()]!=null && p.getMatrice()[y][x] != null) {return false;} } else{ return false; } } } return true; }
8
private MainFrame() { // Set frame options. setTitle("Wombat - Build " + Wombat.VERSION); setSize(Options.DisplayWidth, Options.DisplayHeight); setLocation(Options.DisplayLeft, Options.DisplayTop); setLayout(new BorderLayout(5, 5)); setDefaultCloseOperation(EXIT_ON_CLOSE); try { setIconImage(IconManager.icon("Wombat.png").getImage()); } catch(NullPointerException ex) { } // Wait for the program to end. final MainFrame me = this; addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Options.DisplayTop = Math.max(0, e.getWindow().getLocation().y); Options.DisplayLeft = Math.max(0, e.getWindow().getLocation().x); Options.DisplayWidth = Math.max(400, e.getWindow().getWidth()); Options.DisplayHeight = Math.max(400, e.getWindow().getHeight()); Options.save(); DocumentManager.CloseAll(); stopAllThreads(true, false); me.dispose(); } }); // Set up the menus using the above definitions. MenuManager.Singleton(this); setJMenuBar(MenuManager.getMenu()); // Create a display for any open documents. Root = DockingUtil.createRootWindow(new ViewMap(), true); TabWindow documents = new TabWindow(); ViewMap = new StringViewMap(); DocumentManager.init(this, Root, ViewMap, documents); DocumentManager.New(); // Create displays for a split REPL. History = new NonEditableTextArea(); REPL = new REPLTextArea(); ViewMap.addView("REPL - Execute", new View("REPL - Execute", null, REPL)); ViewMap.addView("REPL - History", new View("REPL - History", null, History)); SplitWindow replSplit = new SplitWindow(true, 0.5f, ViewMap.getView("REPL - Execute"), ViewMap.getView("REPL - History")); ViewMap.getView("REPL - Execute").getWindowProperties().setCloseEnabled(false); ViewMap.getView("REPL - History").getWindowProperties().setCloseEnabled(false); ViewMap.getView("REPL - Execute").getWindowProperties().setUndockEnabled(false); ViewMap.getView("REPL - History").getWindowProperties().setUndockEnabled(false); // Create the error/debug/display views. JPanel debugPanel = new JPanel(); debugPanel.setLayout(new GridLayout(2, 1)); Debug = new NonEditableTextArea(); debugPanel.add(Debug); DebugLogs = new NonEditableTextArea(); debugPanel.add(DebugLogs); ViewMap.addView("Debug", new View("Debug", null, debugPanel)); // Listen and report new error messages. ErrorManager.addErrorListener(new ErrorListener() { @Override public void logError(String msg) { Debug.append(msg + "\n"); } }); // Put everything together into the actual dockable display. SplitWindow fullSplit = new SplitWindow(false, 0.6f, documents, replSplit); Root.setWindow(fullSplit); add(Root); // Add a toolbar. ToolBar = new JToolBar(); ToolBarRun = new JButton(MenuManager.itemForName("Run").getAction()); ToolBarStop = new JButton(MenuManager.itemForName("Stop").getAction()); ToolBar.setFloatable(false); for (Action a : new Action[]{ MenuManager.itemForName("New").getAction(), MenuManager.itemForName("Open").getAction(), MenuManager.itemForName("Save").getAction(), MenuManager.itemForName("Close").getAction(), }) ToolBar.add(new JButton(a)); ToolBar.addSeparator(); for (Action a : new Action[]{ MenuManager.itemForName("Connect").getAction(), MenuManager.itemForName("Upload").getAction(), }) ToolBar.add(new JButton(a)); ToolBar.addSeparator(); for (Action a : new Action[]{ MenuManager.itemForName("Cut").getAction(), MenuManager.itemForName("Copy").getAction(), MenuManager.itemForName("Paste").getAction(), MenuManager.itemForName("Undo").getAction(), MenuManager.itemForName("Redo").getAction(), MenuManager.itemForName("Find/Replace").getAction(), }) ToolBar.add(new JButton(a)); ToolBar.addSeparator(); ToolBar.add(ToolBarRun); ToolBar.add(ToolBarStop); for (Action a : new Action[]{ MenuManager.itemForName("Format").getAction(), MenuManager.itemForName("Reset").getAction(), }) ToolBar.add(new JButton(a)); add(ToolBar, BorderLayout.PAGE_START); ToolBar.setVisible(Options.DisplayToolbar); // Disable items by default. setRunning(false); // Remove text on toolbar buttons. for (Component c : ToolBar.getComponents()) if (c instanceof JButton) ((JButton) c).setText(""); // Add a tool to show the current row and column. RowColumn = new JLabel("row:column"); ToolBar.addSeparator(); ToolBar.add(RowColumn); // Set up options specifically for OS X. if (OS.IsOSX) { try { com.apple.eawt.Application app = com.apple.eawt.Application.getApplication(); app.setDockIconImage(IconManager.icon("Wombat.png").getImage()); } catch (Exception e) { System.err.println("Error setting up OSX specific features:"); e.printStackTrace(); } } // Finally, intialize petite. initPetite(); }
9
@Override public StringConverter<?> findConverter(Class<?> cls) { if (cls.isArray() && cls.getComponentType().isPrimitive()) { if (cls == long[].class) { return LongArrayStringConverter.INSTANCE; } if (cls == int[].class) { return IntArrayStringConverter.INSTANCE; } if (cls == short[].class) { return ShortArrayStringConverter.INSTANCE; } if (cls == double[].class) { return DoubleArrayStringConverter.INSTANCE; } if (cls == float[].class) { return FloatArrayStringConverter.INSTANCE; } } return null; }
9
private static void updateVersions() { try { String path = VersionUtil.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); Attributes a = getManifest(path).getMainAttributes(); if (a.getValue("Plugin-Version") != null) { PLUGIN_VERSION = a.getValue("Plugin-Version"); } if (a.getValue("Minecraft-Version") != null) { MINECRAFT_VERSION = a.getValue("Minecraft-Version"); } if (a.getValue("CraftBukkit-Version") != null) { CRAFTBUKKIT_VERSION = a.getValue("CraftBukkit-Version"); } if (a.getValue("NMS-Package") != null) { NMS_PACKAGE = a.getValue("NMS-Package"); } } catch (Exception e) { Logger.log(Logger.LogLevel.SEVERE, "Failed to obtain Minecraft Server version.", e, true); } }
5
public void sendFeedbackMove(String feedback){ check(isMyTurn() && currentMove == FEEDBACK); check(masterMindLogic.checkValidFeedback(feedback)); if (feedback.equals("4b0w") || ((List<String>)state.get(GUESSHISTORY)).size() == (Integer) state.get(MAXTURN)){ this.sendFeedbackMoveVerify(feedback); } else { this.sendFeedbackMoveContinue(feedback); } }
3
private Token isReservedWord(Token token) { Token tok = token; for (ReservedWord rw : ReservedWord.values()) { //Si encontramos que en el enum ReservedWord existe el lexema que estoy comparando, entonces devuelvo el TokenType que tiene asociado en ese enum. //de lo contrario devuelvo el que ya estaba if (rw.name().equals(token.getLexema().toUpperCase())) { tok = new Token(rw.getReservedToken(), token.getLexema()); break; } } return tok; }
2
public static ArrayList<Critter> getViewableCritters(Critter self, Environment envi){ synchronized(envi.lock_critter){ Arc2D arc = getView(self); Ellipse2D circle = getCloseView(self); ArrayList<Critter> viewable = new ArrayList<Critter>(); Iterator<Critter> iter = envi.getCritters().listIterator(); while(iter.hasNext()){ Critter temp = iter.next(); if(temp.toString().equals(self.toString())){ continue; } if(arc.contains(temp.getPosition().x, temp.getPosition().y)){ viewable.add(temp); } else if(circle.contains(temp.getPosition().x, temp.getPosition().y)){ viewable.add(temp); } } return viewable; } }
4
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]){ if (!(sender instanceof Player)) { sender.sendMessage("This command can only be run by a player."); return true; } Player player = (Player)sender; if (args.length <= 0){ player.sendMessage(Util.edit(USE_HELP)); return true; } if (args[0].equalsIgnoreCase("help")){ helpCommand(player); } else if (args[0].equalsIgnoreCase("create")){ createCommand(player, args); } else if (args[0].equalsIgnoreCase("list")){ listCommand(player); } else if (args[0].equalsIgnoreCase("info")){ infoCommand(player); } else if (args[0].equalsIgnoreCase("reload")){ reloadCommand(player); } else { player.sendMessage(Util.edit(USE_HELP)); } return true; }
7
public boolean conflicts(String name, Scope inScope, int context) { int dot = name.indexOf('.'); if (dot >= 0) name = name.substring(0, dot); int count = scopes.size(); for (int ptr = count; ptr-- > 0;) { Scope scope = (Scope) scopes.elementAt(ptr); if (scope == inScope) return false; if (scope.conflicts(name, context)) { return true; } } return false; }
4
public void renderProjectile(int xp, int yp, Projectile p) { xp -= xOffset; yp -= yOffset; for (int y = 0; y < p.getSpriteSize(); y++) { int ya = y + yp; for (int x = 0; x < p.getSpriteSize(); x++) { int xa = x + xp; if (xa < -p.getSpriteSize() || xa >= width || ya < 0 || ya >= height) break; if (xa < 0) xa = 0; int col = p.getSprite().pixels[x + y * p.getSprite().SIZE]; if (col != 0xffff00ff) pixels[xa + ya * width] = col; } } }
8
public void start(){ try { Display.setTitle("openGLTutorialPongGame learning!"); Display.setResizable(true); Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT)); Display.setVSyncEnabled(VSYNC); Display.setFullscreen(FULLSCREEN); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } create(); resize(); isRunning = true; while (isRunning && !Display.isCloseRequested()) { if (Display.wasResized()) { resize(); render(); Display.update(); Display.sync(60); } } dispose(); Display.destroy(); }
4
private boolean matches(ProcessingEnvironment procEnv, boolean strict, List<? extends TypeMirror> parameterTypes, List<? extends TypeMirror> expectedParameterTypes) { for (int i = 0; i < parameterTypes.size(); i++) { boolean foundMatch = false; if (strict) { for (int j = 0; j < expectedParameterTypes.size(); j++) { if (procEnv.getTypeUtils().isSameType( parameterTypes.get(i), expectedParameterTypes.get(i))) { foundMatch = true; break; } } } else { for (int j = 0; j < expectedParameterTypes.size(); j++) { if (procEnv.getTypeUtils().isSubtype(parameterTypes.get(i), expectedParameterTypes.get(i))) { foundMatch = true; break; } } } if (!foundMatch) { return false; } } return true; }
9
public boolean accept(File f) { if (f.isFile()) { String name = f.getName(); int pos = name.lastIndexOf("."); if (pos > 0 && pos < name.length() - 1) { String suffix = name.substring(pos + 1); for (int i = 0; i < extensions.length; i++) { if (extensions[i].equals("*") || extensions[i].equals(suffix)) { return true; } } } return false; } else { return true; } }
6
public DataModel() { }
0
public boolean updateStateDevuelto(Prestamos p){ PreparedStatement ps; try { ps = mycon.prepareStatement( "UPDATE Prestamos "+ "SET estado='devuelto' "+ "WHERE id=?" ); ps.setInt(1, p.getId()); return (ps.executeUpdate()>0); } catch (SQLException ex) { Logger.getLogger(PrestamosCRUD.class.getName()).log(Level.SEVERE, null, ex); } return false; }
1
private final int jjMoveStringLiteralDfa7_0(long old0, long active0, long old1, long active1) { if (((active0 &= old0) | (active1 &= old1)) == 0L) return jjStartNfa_0(5, old0, old1); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(6, active0, active1); return 7; } switch(curChar) { case 103: if ((active1 & 0x1L) != 0L) return jjStartNfaWithStates_0(7, 64, 8); break; case 110: if ((active0 & 0x8000000000L) != 0L) return jjStartNfaWithStates_0(7, 39, 8); return jjMoveStringLiteralDfa8_0(active0, 0x10000000L, active1, 0L); case 117: return jjMoveStringLiteralDfa8_0(active0, 0x20000000L, active1, 0L); case 119: return jjMoveStringLiteralDfa8_0(active0, 0x1000000000L, active1, 0L); default : break; } return jjStartNfa_0(6, active0, active1); }
8
private static void method342(int i, int j, int k, int l, int i1) { if (j < topX || j >= bottomX) return; if (l < topY) { i1 -= topY - l; l = topY; } if (l + i1 > bottomY) i1 = bottomY - l; int j1 = 256 - k; int k1 = (i >> 16 & 0xff) * k; int l1 = (i >> 8 & 0xff) * k; int i2 = (i & 0xff) * k; int i3 = j + l * width; for (int j3 = 0; j3 < i1; j3++) { int j2 = (pixels[i3] >> 16 & 0xff) * j1; int k2 = (pixels[i3] >> 8 & 0xff) * j1; int l2 = (pixels[i3] & 0xff) * j1; int k3 = ((k1 + j2 >> 8) << 16) + ((l1 + k2 >> 8) << 8) + (i2 + l2 >> 8); pixels[i3] = k3; i3 += width; } }
5
public void lisaaYhteys(Piste yhteys, Suunta suunta){ //Suunta: 1=Pohjoinen, 2=itä, 3=etelä,4=lansi switch(suunta){ case Pohjoinen: Pohjoinen = yhteys; break; case Ita: Ita=yhteys; break; case Etela: Etela=yhteys; break; case Lansi: Lansi=yhteys; break; } }
4
private void parseEvent() { if(sEvt.matches(REGEX_CHATCOMMAND)) parseAsChatCommand(); else if(sEvt.matches(REGEX_GAMECOMMAND)) parseAsGameCommand(); else if(sEvt.matches(REGEX_JOINEVENT) || sEvt.matches(REGEX_QUITEVENT)) parseAsConnectionEvent(); else if(sEvt.matches(REGEX_KICKEVENT)) parseAsKickEvent(); else if(sEvt.matches(REGEX_OPEVENT) || sEvt.matches(REGEX_DEOPEVENT)) parseAsOppingEvent(); else if(sEvt.matches(REGEX_EXCEPTION)) type = Type.EXCEPTION; }
8
public static void insertVelo(Velo velo) { PreparedStatement stat; try { stat = ConnexionDB.getConnection().prepareStatement("insert into velo (serialNumber, dateMiseEnService, kmParcourus, etat, fk_id_borne) values (?,?,?,?,?)"); stat.setString(1, velo.getSerialNumber()); stat.setString(2, velo.getDateMiseEnService()); stat.setDouble(3, velo.getKmParcourus()); stat.setString(4, velo.getEtat()); stat.setInt(5, velo.getFk_id_borne()); stat.executeUpdate(); } catch (SQLException e) { while (e != null) { System.out.println(e.getErrorCode()); System.out.println(e.getMessage()); System.out.println(e.getSQLState()); e.printStackTrace(); e = e.getNextException(); } } }
2
public void quicksort() { SortierListe lLinkeListe = new SortierListe(); SortierListe lRechteListe = new SortierListe(); Integer pivot = null; if (this.laenge() > 0) { this.zumAnfang(); pivot = (Integer) this.aktuellesElement(); this.entferneAktuell(); // Pivot raus while (this.laenge() > 0) { this.zumAnfang(); if ((Integer) this.aktuellesElement() < pivot) { lLinkeListe.haengeAn(this.aktuellesElement()); this.entferneAktuell(); } else if ((Integer) this.aktuellesElement() >= pivot) { lRechteListe.haengeAn(this.aktuellesElement()); this.entferneAktuell(); } } } if (lLinkeListe.laenge() > 0) { lLinkeListe.quicksort(); } if (lRechteListe.laenge() > 0) { lRechteListe.quicksort(); } while (lLinkeListe.laenge() > 0) { lLinkeListe.zumAnfang(); this.haengeAn(lLinkeListe.aktuellesElement()); lLinkeListe.entferneAktuell(); } if (pivot != null) { this.haengeAn(pivot); } while (lRechteListe.laenge() > 0) { lRechteListe.zumAnfang(); this.haengeAn(lRechteListe.aktuellesElement()); lRechteListe.entferneAktuell(); } }
9
protected boolean isFinished() { return false; }
0
@Override public void mouseReleased(MouseEvent e) { Point p = e.getPoint(); int[] cubie = getCubie(p); if (cubie != null) { display.undoneActions.clear(); if (cubie[1] == 1 && cubie[2] == 1) { String turn = ""; if (e.getButton() == 1) { turn = this.getSide(getColor(cubie)).getName(); turn(getColor(cubie)); } else if (e.getButton() == 2) { turn = this.getSide(getColor(cubie)).getName() + "2"; for (int i = 0; i < 2; i++) { turn(getColor(cubie)); } } else if (e.getButton() == 3) { turn = this.getSide(getColor(cubie)).getName() + "I"; for (int i = 0; i < 3; i++) { turn(getColor(cubie)); } } display.actions.add("t:" + turn); } else { display.actions.add("c:" + cubie[0] + "," + cubie[1] + "," + cubie[2] + "," + getColor(cubie).getInt() + "," + selected.getInt()); setPiece(cubie, selected); } } }
8
public void removeChatGuiListener(ChatGuiListener listener) { chatGuiListener.remove(listener); }
0
@SuppressWarnings("rawtypes") public final static Producto jsonToProducto(String json) throws ParseException { Producto prod= new Producto(); JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { public List<String> creatArrayContainer() { return new LinkedList<String>(); } public Map<String, String> createObjectContainer() { return new LinkedHashMap<String, String>(); } }; Map map = (Map) parser.parse(json, containerFactory); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); if (entry.getKey().equals("id")) prod.setId(Long.parseLong(entry.getValue().toString())); else if (entry.getKey().equals("name")) { prod.setProducto(entry.getValue().toString()); System.out.println(entry.getValue().toString()); } else if (entry.getKey().equals("tipo")) prod.setTipo(entry.getValue().toString()); else if (entry.getKey().equals("cantidad")) prod.setcantidad(entry.getValue().toString()); else if (entry.getKey().equals("farmacia")) prod.setFarmacia(entry.getValue().toString()); else if (entry.getKey().equals("descripcion")) prod.setdescripcion(entry.getValue().toString()); else if (entry.getKey().equals("receta")) prod.setreceta(entry.getValue().toString()); else if (entry.getKey().equals("precio")) prod.setprecio(entry.getValue().toString()); } return prod; }
9
private void registerResources(Environment environment){ final Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Path.class); for (String beanName : beansWithAnnotation.keySet()) { Object resource = beansWithAnnotation.get(beanName); environment.jersey().register(resource); logger.info("Registering resource : " + resource.getClass().getName()); } }
1
public void execute() throws ClassNotFoundException, SQLException, IOException { DataWriter writer = new ExcelWriter(context); Class.forName(context.getJdbcDriver()); Connection connection = DriverManager.getConnection(context.getConnectionUrl()); PreparedStatement statement = null; ResultSet resultSet = null; try { statement = connection.prepareStatement(context.getQuery()); resultSet = statement.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); String[] headers = new String[metaData.getColumnCount()]; for (int i = 0; i < headers.length; i++) { headers[i] = metaData.getColumnLabel(i + 1); } writer.writeHeaders(headers); Object[] values = new Object[headers.length]; while (resultSet.next()) { for (int i = 0; i < values.length; i++) { values[i] = resultSet.getObject(i + 1); } writer.writeRowValues(values); } } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { } } if (statement != null) { try { statement.close(); } catch (SQLException e) { } } if (connection != null) { try { connection.close(); } catch (SQLException e) { } } writer.close(); } }
9
public final int[] randomCARule(int maxLength, int actualLength, Random randNum){ int[] itemArray = new int[maxLength]; for(int k =0;k < itemArray.length;k++) itemArray[k] = -1; if(actualLength == 1) return itemArray; int help =actualLength-1; if(help == maxLength-1){ help = 0; for(int h = 0; h < itemArray.length; h++){ if(h != m_instances.classIndex()){ itemArray[h] = m_randNum.nextInt((m_instances.attribute(h)).numValues()); } } } while(help > 0){ int mark = randNum.nextInt(maxLength); if(itemArray[mark] == -1 && mark != m_instances.classIndex()){ help--; itemArray[mark] = m_randNum.nextInt((m_instances.attribute(mark)).numValues()); } } return itemArray; }
8
public static boolean available(int port) { if ((port < MIN_PORT_NUMBER) || (port > MAX_PORT_NUMBER)) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; }
6
public static RandomListNode copyRandomList(RandomListNode head) { if (head == null) { return null; } RandomListNode p = head; while (p != null) { RandomListNode temp = new RandomListNode(p.label); temp.random = null; temp.next = p.next; p.next = temp; p = temp.next; } RandomListNode p1 = head; RandomListNode p2 = head.next; while (p1 != null && p2 != null) { if (p1.random != null) { p2.random = p1.random.next; } p1 = p2.next; if (p1 != null) { p2 = p1.next; } } p1 = head; p2 = head.next; RandomListNode head2 = p2; while(p1!=null && p2!= null){ p1.next = p2.next; p1 = p1.next; if(p1 != null){ p2.next = p1.next; p2 = p2.next; }else { p2.next = null; } } return head2; }
9
public Players(int num, String[] names, Deck deck) { this.numPlayers = num; this.playerList = new Player[this.numPlayers]; PlayerHand[] ph = new PlayerHand[this.numPlayers]; int numCardsInHand; // Determine how many cards will be in each deck if (this.numPlayers <= 4) { numCardsInHand = 7; } else { numCardsInHand = 5; } // Instantiate all the PlayerHands for (int i = 0; i < ph.length; i++) { ph[i] = new PlayerHand(); } // Deal the cards for (int i = 0; i < this.numPlayers; i++) { for (int j = 0; j < numCardsInHand; j++) { Card c = deck.deal(); ph[i].insert(c); } } // Note that the remaining cards will be used for the pool. // Since the Game constructor passes the Deck to the Players // constructor, // after the Players are created and the cards are dealt, the Game // constructor // will create the pool. // Create the players and add them to the player array for (int i = 0; i < this.numPlayers; i++) { this.playerList[i] = new Player(names[i], ph[i], i); } }
5
public void draw(Graphics2D g) { for( int row = rowOffset; row < rowOffset + numRowsToDraw; row++) { if(row >= numRows) break; for( int col = colOffset; col < colOffset + numColsToDraw; col++) { if(col >= numCols) break; if(map[row][col] == 0) continue; int rc = map[row][col]; int r = rc / numTilesAcross; int c = rc % numTilesAcross; g.drawImage( tiles[r][c].getImage(), (int)x + col * tileSize, (int)y + row * tileSize, null ); } } }
5
@Test(timeout = 700) public void alterOutput() throws Exception { C c = new C(); c.addListener(new Listener() { @Override public void notice(Type T, EventObject E) { if (T == Type.OUT) { DataflowEvent ce = (DataflowEvent) E; if (ce.getValue() instanceof Double) { assertEquals(1.2, ce.getValue()); ce.setValue(new Double(3.2)); } // System.out.println(" ---- " + ce.getValue() + " " + // ce.getValue().getClass()); } } }); c.in = "1"; c.execute(); // System.out.println(c.get(c.op2, "cmdOut")); assertEquals("CMD2(3.2)", c.out); }
2
public ByteChunk get( ByteChunk key ) { long indexPos = indexPos(key); FileLock fl = null; synchronized( this ) { try { try { if( fileChannel != null ) fl = fileChannel.lock(0, Long.MAX_VALUE, true); long chunkOffset = getLong( indexPos ); while( chunkOffset != 0 ) { ByteChunk c = getChunk( chunkOffset ); if( pairMatches( c, key ) ) { ByteChunk v = pairValue( chunkOffset, c ); if( v != null ) return v; } chunkOffset = next(c); } return null; } finally { if( fl != null ) { fl.release(); // On Windows 7 at least, this seems to be sufficient to // constructively work on the same file from multiple processes // even though the file will be reported by `dir` with its // old size until it is closed by a process. // // i.e. force(...) does not seem necessary for // synchronization between processes, which is good because // it's terribly slow. } } } catch( IOException e ) { throw new RuntimeException(e); } } }
6
public ListNode mergeKLists(ArrayList<ListNode> lists) { if (lists.isEmpty()) return null; if (lists.size()==1) return lists.get(0); ListNode header = new ListNode(0); ListNode p = header; while(true){ int min = Integer.MAX_VALUE; int minList = 0; int count = 0; for (int i = 0; i < lists.size(); i++) { // move one step for all lists ListNode index = lists.get(i); if (index!=null){ if (index.val < min){ min = index.val; minList = i; } } else{ count++; } } if (count==lists.size()) break; ListNode add = lists.get(minList); // add one new node p.next = add; p = p.next; lists.set(minList, add.next); } return header.next; }
7
private static boolean tryOSGILoadLibrary () { try { Class<?> fwUtilClass = NativeUnixSocket.class.getClassLoader().loadClass("org.osgi.framework.FrameworkUtil"); Method getBundleMethod = fwUtilClass.getMethod("getBundle", new Class[] { Class.class }); if ( getBundleMethod.invoke(null, NativeUnixSocket.class) != null ) { System.loadLibrary("junixsocket"); loaded = true; return true; } } catch ( Exception e ) {} return false; }
3
@Override public int compare(Achievement achievement1, Achievement achievement2) { if (achievement1.id < achievement2.id) return -1; else if (achievement1.id > achievement2.id) return 1; else return 0; }
2