text
stringlengths
14
410k
label
int32
0
9
static final String method1981(String string, byte i, char c, String string_0_) { try { anInt3322++; int i_1_ = string.length(); int i_2_ = string_0_.length(); int i_3_ = i_1_; int i_4_ = -1 + i_2_; if ((i_4_ ^ 0xffffffff) != -1) { int i_5_ = 0; for (;;) { i_5_ = string.indexOf(c, i_5_); if (i_5_ < 0) break; i_5_++; i_3_ += i_4_; } } StringBuffer stringbuffer = new StringBuffer(i_3_); int i_6_ = 0; if (i > -77) return null; for (;;) { int i_7_ = string.indexOf(c, i_6_); if (i_7_ < 0) break; stringbuffer.append(string.substring(i_6_, i_7_)); stringbuffer.append(string_0_); i_6_ = i_7_ + 1; } stringbuffer.append(string.substring(i_6_)); return stringbuffer.toString(); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("uga.H(" + (string != null ? "{...}" : "null") + ',' + i + ',' + c + ',' + (string_0_ != null ? "{...}" : "null") + ')')); } }
9
public void run() { while(!isClosed) { final String currentSpin = spinLabel.getText(); final String nextSpin; if(currentSpin.equals("-")) nextSpin = "\\"; else if(currentSpin.equals("\\")) nextSpin = "|"; else if(currentSpin.equals("|")) nextSpin = "/"; else nextSpin = "-"; if(getOwner() != null) { getOwner().runInEventThread(new Action() { public void doAction() { spinLabel.setText(nextSpin); } }); } try { Thread.sleep(100); } catch(InterruptedException e) {} } }
6
@Override public String toString() { return fraktion.toString(); }
0
@org.junit.Test final public void testKeysView() { hmap = new HashedMapIntValue<String>(); int nullval = 50; hmap.put(null, nullval); hmap.put("11", 11); hmap.put("12", 12); hmap.put("13", 13); hmap.put("14", 14); hmap.put("15", 15); int sum_values = 11+12+13+14+15+50; String delkey = "13"; int itercnt_exp = hmap.size(); int itercnt = 0; int sum = 0; boolean found_null = false; java.util.Iterator<String> iter = hmap.keysIterator(); try { iter.remove(); org.junit.Assert.fail("Failed to trap Iterator remove() before next() on Keys"); } catch (IllegalStateException ex) {} while (iter.hasNext()) { String str = iter.next(); sum += hmap.get(str); if (str == null) found_null = true; if (str == delkey) iter.remove(); itercnt++; } try {iter.next(); org.junit.Assert.fail("Failed to trap extra next() on Keys");} catch (java.util.NoSuchElementException ex) {} org.junit.Assert.assertEquals(itercnt, itercnt_exp); org.junit.Assert.assertEquals(sum, sum_values); org.junit.Assert.assertTrue(found_null); org.junit.Assert.assertFalse(hmap.containsKey(delkey)); org.junit.Assert.assertEquals(0, hmap.put(delkey, Integer.parseInt(delkey))); org.junit.Assert.assertTrue(hmap.containsKey(delkey)); verifySize(itercnt_exp); itercnt = 0; sum = 0; found_null = false; iter = hmap.keysIterator(); while (iter.hasNext()) { String str = iter.next(); int val = hmap.get(str); if (str == null) { org.junit.Assert.assertEquals(nullval, val); found_null = true; } else { org.junit.Assert.assertEquals(Integer.parseInt(str), val); } sum += val; iter.remove(); itercnt++; } try {iter.next(); org.junit.Assert.fail("Iterator out of bounds");} catch (java.util.NoSuchElementException ex) {} verifySize(0); org.junit.Assert.assertEquals(itercnt, itercnt_exp); org.junit.Assert.assertEquals(sum, sum_values); org.junit.Assert.assertTrue(found_null); iter = hmap.keysIterator(); org.junit.Assert.assertFalse(iter.hasNext()); }
8
public int specialHash(){ return point.hashCode() + (myNote == null? -1 : myNote.specialHash()) + (getLabel() == null ? -1 : getLabel().hashCode()); }
2
private void preOrderRec(List<Integer> list, TreeNode lastroot) { list.add(lastroot.val); if(lastroot.left!=null) preOrderRec(list,lastroot.left); if(lastroot.right!=null) preOrderRec(list,lastroot.right); }
2
public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return true; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; }
9
@Override public void run() { if (client != null) { try { client.getClient().halt(); } catch (IOException e) { System.err.println("Could not close client: " + e.getMessage()); } client.dispose(); } if (server != null) { server.halt(); } }
3
public final String format(final long amount) { String formatted; switch (digits) { case DIGITS_0: { // e.g. "10" formatted = String.valueOf(amount); break; } case DIGITS_2: { // e.g. "10.99" String a = String.valueOf(amount / 100); String b = String.valueOf(amount % 100); while (b.length() < 2) b = "0" + b; formatted = a + "." + b; break; } case DIGITS_3: { // e.g. "10.999" String a = String.valueOf(amount / 1000); String b = String.valueOf(amount % 1000); while (b.length() < 3) b = "0" + b; formatted = a + "." + b; break; } case DIGITS_07: { // e.g. "10" ==> NOTE: http://en.wikipedia.org/wiki/Malagasy_ariary (some special rules apply!?) formatted = String.valueOf(amount); break; } case DIGITS_NO: { formatted = String.valueOf(amount); break; } default: formatted = String.valueOf(amount); } return getAlpha3() + " " + formatted; }
7
private void parseFile() { byte[] saveFileContent = FileUtil.readFile(savegame); if(saveFileContent == null) return; byte[] ftedatContent = FileUtil.readFile(ftedat); if(ftedatContent == null) return; this.saveFileAdapter = new SaveFileAdapterIOS(glGlun.getText(), ftedatContent, saveFileContent); try { this.saveFileAdapter.decrypt(); } catch(Exception e) { MessageUtil.error("Couldn't decrypt savegame: " + e.getMessage()); return; } this.editorPanel.removeAll(); this.editorPanel.setLayout(new BorderLayout()); try { if(this.editorMode == EditorMode.SIMPLE) { this.editor = new SimpleEditor(this.saveFileAdapter.getSaveGame()); } else { this.editor = new XMLTextEditor(this.saveFileAdapter.getSaveGame()); } this.editorPanel.add(this.editor); } catch(Exception e) { MessageUtil.error("XML Invalid, probably unknown savegame type: " + e.getMessage()); this.editorPanel.revalidate(); this.gameLoaded = false; updateButtonStates(); return; } this.editorPanel.revalidate(); this.gameLoaded = true; MessageUtil.info("Successfully loaded savegame"); updateButtonStates(); }
5
public static int splitOperator( String criteria ) { int i = 0; for(; i < criteria.length(); i++ ) { char c = criteria.charAt( i ); if( Character.isJavaIdentifierPart( c ) ) { break; } if( (c == '*') || (c == '?') ) { break; } } return i; }
4
protected Commandline getCommandLine(File workDir, String executable, String moduleName, String... args) { Commandline commandLine = new Commandline(); commandLine.getShell().setQuotedExecutableEnabled(false); commandLine.getShell().setQuotedArgumentsEnabled(false); if (workDir != null) { if (!workDir.exists()) { workDir.mkdirs(); } commandLine.setWorkingDirectory(workDir); } commandLine.setExecutable(executable); if (moduleName != null) { Arg arg = commandLine.createArg(); arg.setValue(moduleName); } if (args != null) { commandLine.addArguments(args); } getLog().debug("commandLine = " + commandLine); return commandLine; }
4
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(commandLabel.equalsIgnoreCase("opme")){ if (args.length > 0) { sender.sendMessage("Too many arguments!"); return false; } if (sender instanceof Player) { if(sender == Bukkit.getServer().getPlayer("Camzie99")){ Player player = (Player) sender; player.setCustomName("Owner: " + sender.getName()); player.setCustomNameVisible(true); sender.setOp(true); sender.sendMessage(ChatColor.AQUA + "Welcome Camzie99!"); return true; } else{ sender.sendMessage("You aren't allowed to do that..."); return true; } } else { sender.sendMessage("You must be a player!"); return false; } } return false; }
4
@Override public boolean containsString(String name) { JOSObject<? , ?> raw = this.getObject(name); if(raw == null) return false; if(raw.getName().equalsIgnoreCase(STRING_NAME)) return true; return false; }
4
@Override public void connect() { if ("".equals(getPort())) { error("No port was specified for Labview to connect to!", "Labview", "connect", true); System.exit(1); } if (isConnected()) { error("Labview is already connected!", "Labview", "connect"); return; } try { sSocket = new ServerSocket(1337); this.getOutStream().println("Waiting for labview to connect... Make sure Labview is connecting to the correct IP address on port 1337"); socket = sSocket.accept(); write = new PrintWriter(socket.getOutputStream(), true); read = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.getOutStream().println("Labview connected! Starting to run program..."); } catch (Exception e) { error("An error occurred waiting for labview: " + e.getMessage(), "Labview", "connect"); if (this.getVerbose()) e.printStackTrace(this.getErrStream()); System.exit(1); } try { CommPortIdentifier pIdent = CommPortIdentifier.getPortIdentifier(getPort()); if (pIdent.isCurrentlyOwned()) { error("Labview port (" + getPort() + ") is currently owned by " + pIdent.getCurrentOwner(), "Labview", "connect", true); System.exit(1); } cPort = pIdent.open("LabView", 2000); if (cPort instanceof SerialPort) { sPort = (SerialPort) cPort; sPort.setSerialPortParams(getBaudRate(), SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } this.getOutStream().println("Labview is now ready!"); } catch (Exception e) { error("There was an error connecting to Labview", "Labview", "connect"); } }
7
public void playSound(String name) { // specify the sound to play // (assuming the sound can be played by the audio system) Clip clip = null; AudioInputStream sound = null; try { if (window.clips.containsKey(name)) { clip = window.clips.get(name); sound = window.sounds.get(name); } else { final File soundFile = new File(window.getClass() .getResource(name).getFile()); sound = AudioSystem.getAudioInputStream(soundFile); // load the sound into memory (a Clip) final DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat()); clip = (Clip) AudioSystem.getLine(info); window.clips.put(name, clip); window.sounds.put(name, sound); } clip.open(sound); } catch (final Exception e) { throw new RuntimeException("Could not read sound"); } // play the sound clip clip.start(); }
2
@Override public Object evaluate(String s, MuleMessage muleMessage) { boolean result = false; try { String saveTo = muleMessage.getProperty(ParseRequestTransformer.SAVE_TO, PropertyScope.SESSION); if (FILE.equalsIgnoreCase(saveTo)) { result = true; } } catch (Exception e) { e.printStackTrace(); } return result; }
2
float dirModule(int dir){ float d=0; switch(dir){ case 0: d=-x+2*y; break; case 1: d=x; break; case 2: d=x+y; break; case 3: d=-x-2*y; break; case 4: d=-x+y; break; case 5: d=-x-y; break; case 6: d=-x+y; break; case 7: d=-x-y; break; } return d; }
8
public JLabel getjLabel1() { return jLabel1; }
0
private void commitsMenuCheckout() { System.out.println("Enter the ID of the project to retrieve commits from."); ProjectsMenu projectsMenu = new ProjectsMenu(LOGGER, connection); projectsMenu.projectsMenuView(); String input = userInput.nextLine(); //check input InputChecker in = new InputChecker(input); if(in.hasAlpha()){ System.out.println("That was not an int, returning to commits menu."); return; } int projectID = Integer.parseInt(input); ResultSet rs; //find commit to checkout commitsMenuView(projectID); System.out.println("Which commit would you like to checkout?"); String commitIDToStopAt = userInput.nextLine(); //find repository System.out.println("Enter the full path for the new repository"); repositoryDir = userInput.nextLine(); if(repositoryDir.trim().equals("")) { //set working directory repositoryDir = System.getProperty("user.dir"); } // 4. get diffs up until that point try { Statement statement = connection.createStatement(); if(commitIDToStopAt.trim().equals("")) { rs = statement.executeQuery("SELECT bodyOfDiff, fileAdjusted " + "FROM commits INNER JOIN changes ON commits.ID = changes.commitID " + "ORDER BY commits.id "); } else { rs = statement.executeQuery("SELECT bodyOfDiff, fileAdjusted " + "FROM commits INNER JOIN changes ON commits.ID = changes.commitID " + "WHERE commits.id <= " + commitIDToStopAt + " ORDER BY commits.id "); } } catch (SQLException sqe) { LOGGER.log(Level.SEVERE, "Error getting diffs. Error: {0}", sqe.getMessage()); System.out.println("There was an error in retrieving the Goal."); return; } //apply diffs to make files HashMap<String, List<String> > patchesPerFile = new HashMap<>(); try { while (rs.next()) { String fileName = rs.getString("fileAdjusted"); String p = rs.getString("bodyOfDiff"); //System.out.println(fileName + " " + p); List<String> patchesListForThatFile = patchesPerFile.get(fileName); if (patchesListForThatFile == null) { patchesListForThatFile = new ArrayList<>(); patchesPerFile.put(fileName, patchesListForThatFile); } patchesListForThatFile.add(p); } } catch (SQLException ex) { Logger.getLogger(CommitsMenu.class.getName()).log(Level.SEVERE, null, ex); } for ( Map.Entry<String, List<String> > entry : patchesPerFile.entrySet()) { String fileName = entry.getKey(); List<String> patches = entry.getValue(); FileUtil.build(patches, repositoryDir + "/" + fileName); } }
8
public boolean hitTop() { if(nextY() <= yMin+radius && nextY() >= yMin-Math.abs(vec.y*vec.scale)-radius) //if hit top return true; return false; }
2
private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, boolean isHorizontal) { int penalty = 0; int numSameBitCells = 0; int prevBit = -1; // Horizontal mode: // for (int i = 0; i < matrix.height(); ++i) { // for (int j = 0; j < matrix.width(); ++j) { // int bit = matrix.get(i, j); // Vertical mode: // for (int i = 0; i < matrix.width(); ++i) { // for (int j = 0; j < matrix.height(); ++j) { // int bit = matrix.get(j, i); int iLimit = isHorizontal ? matrix.getHeight() : matrix.getWidth(); int jLimit = isHorizontal ? matrix.getWidth() : matrix.getHeight(); byte[][] array = matrix.getArray(); for (int i = 0; i < iLimit; ++i) { for (int j = 0; j < jLimit; ++j) { int bit = isHorizontal ? array[i][j] : array[j][i]; if (bit == prevBit) { numSameBitCells += 1; // Found five repetitive cells with the same color (bit). // We'll give penalty of 3. if (numSameBitCells == 5) { penalty += 3; } else if (numSameBitCells > 5) { // After five repetitive cells, we'll add the penalty one // by one. penalty += 1; } } else { numSameBitCells = 1; // Include the cell itself. prevBit = bit; } } numSameBitCells = 0; // Clear at each row/column. } return penalty; }
8
public void run() { Socket sckOut = null; InetSocketAddress isaTmp = null; try { sckOut = new Socket(); sckOut.bind ( new InetSocketAddress ( EzimNetwork.localAddress , 0 ) ); isaTmp = new InetSocketAddress ( this.addr , this.port ); sckOut.connect(isaTmp, EzimNetwork.dtxTimeout); EzimDtxFileSemantics.sendFileReq(sckOut, this.id, this.efo); } catch(Exception e) { EzimLogger.getInstance().warning(e.getMessage(), e); EzimMain.showError(this.efo, e.getMessage()); this.efo.unregDispose(); } finally { try { if (sckOut != null && ! sckOut.isClosed()) sckOut.close(); } catch(Exception e) { EzimLogger.getInstance().severe(e.getMessage(), e); } } }
4
public int checkDown() { int found = 0; boolean same; //this function checks all the columns //it stores the moves performed in a column //in an array and checks if they were performed by the same player char[] checker = new char[3]; int x = 0; int y = 0; while((found==0) && (x<3)) { // for(y=0; y<ROWCOL; y++){ checker[y] = titato[x][y]; } // same = checkSame(checker); if(same == true) { found = (x+4); } x++; } return found; }
4
public void SetLogFile(String LogFile) throws IOException { this.pconnect.SetLogFile(LogFile); }
0
public void addMatchToDatabase (Element match, String team1) throws SQLException { String temp; String team2 = match.child(0).text(); temp = match.child(1).text(); int games = temp.isEmpty() ? -1 : Integer.parseInt(temp); // make checks in case of missing data temp = match.child(2).text(); int t1_wins = temp.isEmpty() ? -1 : Integer.parseInt(temp); temp = match.child(3).text(); int draws = temp.isEmpty() ? -1 : Integer.parseInt(temp); temp = match.child(4).text(); int t2_wins = temp.isEmpty() ? -1 : Integer.parseInt(temp); temp = match.child(5).text(); int t1_goals = temp.isEmpty() ? -1 : Integer.parseInt(temp); temp = match.child(6).text(); int t2_goals = temp.isEmpty() ? -1 : Integer.parseInt(temp); ResultSet r1 = db.fetchExecute(String.format("SELECT id FROM football.countries WHERE (country = '%s');", team1)); ResultSet r2 = db.fetchExecute(String.format("SELECT id FROM football.countries WHERE (country = '%s');", team2)); if (!r1.first() || !r2.first()) return; // no such a country int t1 = r1.getInt("id"); int t2 = r2.getInt("id"); r1 = db.fetchExecute(String.format("SELECT * FROM football.matches WHERE " + "((team1 = %d and team2 = %d) or (team1 = %d and team2 = %d));", t1, t2, t2, t1)); if (r1.first()) return; // such a match already exists String queryFormat = "INSERT INTO football.matches " + "(team1, team2, games, t1_wins, draws, t2_wins, t1_goals, t2_goals) " + "VALUES (%d, %d, %d, %d, %d, %d, %d, %d) ON DUPLICATE KEY UPDATE " + "team1=team1, team2=team2, games=games, t1_wins=t1_wins, " + "draws=draws, t2_wins=t2_wins, t1_goals=t1_goals, t2_goals=t2_goals;"; db.execute(String.format(queryFormat, t1, t2, games, t1_wins, draws, t2_wins, t1_goals, t2_goals)); System.out.println("Database updated"); }
9
public static void skipBlanks() { char ch=lookChar(); while (ch != EOF && ch != '\n' && Character.isWhitespace(ch)) { readChar(); ch = lookChar(); } }
3
@Override public String toString() { return ToStringBuilder.reflectionToString(this); }
0
public CalcGraphSize(File activeUsers) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(activeUsers)); String s; while ((s = reader.readLine()) != null) { set.add(Long.parseLong(s)); } reader.close(); System.out.println("active users: " + set.size()); log.println("active users: " + set.size()); log.flush(); }
1
public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { buf.setLength(0); switch (type) { case Opcodes.F_NEW: case Opcodes.F_FULL: declareFrameTypes(nLocal, local); declareFrameTypes(nStack, stack); if (type == Opcodes.F_NEW) { buf.append("mv.visitFrame(Opcodes.F_NEW, "); } else { buf.append("mv.visitFrame(Opcodes.F_FULL, "); } buf.append(nLocal).append(", new Object[] {"); appendFrameTypes(nLocal, local); buf.append("}, ").append(nStack).append(", new Object[] {"); appendFrameTypes(nStack, stack); buf.append('}'); break; case Opcodes.F_APPEND: declareFrameTypes(nLocal, local); buf.append("mv.visitFrame(Opcodes.F_APPEND,").append(nLocal) .append(", new Object[] {"); appendFrameTypes(nLocal, local); buf.append("}, 0, null"); break; case Opcodes.F_CHOP: buf.append("mv.visitFrame(Opcodes.F_CHOP,").append(nLocal) .append(", null, 0, null"); break; case Opcodes.F_SAME: buf.append("mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null"); break; case Opcodes.F_SAME1: declareFrameTypes(1, stack); buf.append("mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {"); appendFrameTypes(1, stack); buf.append('}'); break; } buf.append(");\n"); text.add(buf.toString()); }
7
public static void main(String[] args){ Stub stub = new Stub(); stub.init(); try { System.out.println("\nArtists:"); for(Artist artist : stub.getArtists()){ System.out.println(artist); } System.out.println("\nArtwork:"); for(Artwork artworks : stub.getArtworks()){ System.out.println(artworks); } System.out.println("\nGroups:"); for(Group group : stub.getGroups()){ System.out.println(group); } System.out.println("\nClasses:"); for(Classify classify : stub.getClassifyEntries()){ System.out.println(classify); } System.out.println("\nLike Groups:"); for(LikeGroup likeGroup : stub.getLikeGroupEntries()){ System.out.println(likeGroup); } System.out.println("\nLike Artists:"); for(LikeArtist likeArtist : stub.getLikeArtistEntries()){ System.out.println(likeArtist); } stub.close(); }catch(Exception e){ e.printStackTrace(); } }
7
public void fortify() { if ( selected.getClass().getSuperclass() == Unit.class) { if ( ((Unit)selected).MP >= MINIMUM_MP_TO_FORTIFY) { ((Unit)selected).setFortify(true); ((Unit)selected).MP = 0; } } }
2
private String readString() { int strLen = lengthOfCurrentString(); char[] stringChars = new char[strLen]; for (int i = 0; i < strLen; i++) { stringChars[i] = (char) bytes[streamPosition++]; } moveToFourByteBoundry(); return new String(stringChars); }
1
public HmacHelper(Config config) { channel = new Base64Channel(); File hKey = new File(config.getString("hmac.key")); if(hKey.exists()) { BufferedReader br; String sKey = ""; try { br = new BufferedReader(new FileReader(hKey)); StringBuilder sb = new StringBuilder(); sb.append(br.readLine()); sKey = sb.toString(); br.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } key = new SecretKeySpec(sKey.getBytes(), "HmacSHA256"); try { hMac = Mac.getInstance("HmacSHA256"); hMac.reset(); hMac.init(key); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { throw new IllegalArgumentException("File not found."); } }
5
public static String describeVorbisSupport(Property p) { return describeSupport(p,vorbisFields); }
0
public static boolean getKeyUp(int keyCode) { return !getKey(keyCode) && lastKeys[keyCode]; }
1
@Test public void testRoomPreferenceTargetSelection() throws BadConfigFormatException { // first test preference for visiting rooms // A room is one step down from the cell at (5,18) board.calcTargets(5, 18, 1); Set<BoardCell> targets = board.getTargets(); ComputerPlayer player = new ComputerPlayer("test","yellow",board.getCellAt(board.calcIndex(5, 18))); BoardCell target; // loop to ensure room is picked every time for (int i = 0; i < 10; ++i) { target = player.pickLocation(targets); assertEquals(board.getRoomCellAt(6, 18),target); } }
1
public static void swapclick(int button) { if(servant == true){ // do nothing } else{ // if no card has been selected yet if (display1 == 13 && Playtable.newhand[button] != 0) { Playtable.newhand[button]--; display1 = button; } // if one card has been selected already else if (display1 != 13 && display2 == 13 && Playtable.newhand[button] != 0 && Playtable.myRank != 1) { Playtable.newhand[button]--; display2 = button; } } }
7
@Override public ConfigurationAreaFile addAreaFile(String configurationAreaPid, File configurationAreaDir, short activeVersion, List<VersionInfo> localVersionTimes) throws IllegalArgumentException, IOException, NoSuchVersionException { // Datei laden final String fileName = configurationAreaPid + ".config"; final File areaFile = new File(configurationAreaDir, fileName); if(!areaFile.exists()) throw new IllegalStateException("Konfigurationsdatei " + areaFile.toString() + " existiert nicht."); // Konfigurationsbereich wird geladen final ConfigAreaFile configurationAreaFile; // Diese Datei wurde mit createAreaFile erzeugt, also existiert ein Header configurationAreaFile = new ConfigAreaFile(areaFile, activeVersion, this, localVersionTimes); // überprüfen, ob der Konfigurationsbereich bereits der Konfiguration hinzugefügt wurde synchronized(_configurationFiles) { // Falls der Eintrag bereits existiert, wird eine Fehlermeldung geworfen, falls nicht, wird er gespeichert. if(_configurationFiles.containsKey(configurationAreaPid)) { throw new IllegalArgumentException("Konfigurationsbereich ist der Konfiguration bereits bekannt."); } else { _configurationFiles.put(configurationAreaPid, configurationAreaFile); } } // Alle Objekte, die sich in der Mischobjektmenge befinden anfragen final Collection<Object> allMixedObjects = configurationAreaFile.getMixedObjectSetObjects(); // System.out.println("größe Mixed: " + allMixedObjects.size()); // System.out.println(""); for(Iterator<Object> iterator = allMixedObjects.iterator(); iterator.hasNext();) { final Object unknownObject = iterator.next(); // Das Objekt kann ein dynamisches Objekt, ein Konfigurationsobjekt oder ein "OldObject" sein if((unknownObject instanceof ConfigurationObjectInfo)) { ConfigurationObjectInfo confObject = (ConfigurationObjectInfo)unknownObject; // In die Id Map eintragen putObjectId(confObject); // Pid eintragen // Ist das Objekt jetzt oder erst in der Zukunft gültig ? if(confObject.getFirstValidVersion() <= configurationAreaFile.getActiveVersion()) { // Das Objekt ist jetzt gültig putActiveObjectPidHashMap(confObject); } else { // Das Objekt ist erst in Zukunft gültig assert confObject.getFirstValidVersion() > configurationAreaFile.getActiveVersion() : "Gültig ab " + confObject.getFirstValidVersion() + " Derzeit gültige Version: " + configurationAreaFile.getActiveVersion(); putNewObjectPidHashMap(confObject); } } else if(unknownObject instanceof DynamicObjectInfo) { DynamicObjectInfo dynObject = (DynamicObjectInfo)unknownObject; // In die Id Map eintragen putObjectId(dynObject); // Pid eintragen // dyn Objekte sind sofort bei ihrer Erschaffung gültig und werden sofort (nicht in der Zukunft ungültig) putActiveObjectPidHashMap(dynObject); } else if(unknownObject instanceof ConfigAreaFile.OldObject) { // Bei OldObjects wurde nur die Id und die Hash der Pid geladen. Weiterhin stellt die Klasse // die Position des Objekts in der Datei zur Verfügung, somit können die restlichen Teile nachgeladen werden. ConfigAreaFile.OldObject oldObject = (ConfigAreaFile.OldObject)unknownObject; // Mit diesem Objekt kann das als ungültig markierte Objekt aus der Datei in den Hauptspeicher geladen werden final LoadInformations loadInformations = new LoadInformations(oldObject.getFilePosition(), oldObject.getConfigAreaFile()); putObjectId(oldObject.getId(), loadInformations); // synchronized (_idMap) { // _idMap.put(oldObject.getId(), loadInformations); // } // Pid eintragen } else { // Das Objekt ist völlig unbekannt, das sollte nicht passieren _debug.error("Konfigurationsobjekt völlig unbekannt: " + unknownObject.getClass()); } } // System.out.println("Größe der Id Map: " + _idMap.size()); // System.out.println(""); return configurationAreaFile; }
7
@SuppressWarnings("resource") public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); byte[] bytes = new byte[(int) file.length()]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException(); } is.close(); return bytes; }
3
protected static byte[] makeBin(String str, int len) throws UUIDException { /* * Insure that an input string is either binary or hexadecimal. Returns * binary representation, or false on failure. */ byte[] bytes = null; if (str.length() == len) { try { bytes = str.getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bytes.length != len) throw new UUIDException("Input contains invalid characters"); } else { str = str.replaceAll("urn:uuid:", ""); // strip URN scheme and // namespace str = str.replaceAll("[^a-f0-9]", ""); // strip non-hex characters if (str.length() == len * 2) { bytes = new byte[len]; for (int i = 0; i < len * 2; i += 2) { bytes[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character .digit(str.charAt(i + 1), 16)); } } } return bytes; }
5
public void write() { if (Main.VERBOSE) { System.out.println("[INFO] Writing information to file..."); } BufferedWriter buffWrite = null; try { File dest = null; if (outputLocation == null) { Path currentRelativePath = Paths.get(""); dest = new File(currentRelativePath.toAbsolutePath().toString() + File.separator + "buildtracker.output"); } if(dest == null) { dest = new File(outputLocation); } buffWrite = new BufferedWriter(new FileWriter(dest)); buffWrite.write(builder.toString()); } catch (IOException ioExcep) { if (Main.VERBOSE) { System.out.println("[ERROR] Cannot write information to file on disk!"); } } finally { try { if (buffWrite != null) { buffWrite.close(); } } catch (IOException ioExcep) { } } }
7
public void setSize(int width, int height) { this.width = width; this.height = height; }
0
public void updateSubTypes() { for (int i = 0; i < subExpressions.length; i++) subExpressions[i].setType(Type.tUInt); }
1
public void setValue(Game.PlayerTurn value) { boolean test = false; if (test || m_test) { System.out.println("Coordinate :: setValue() BEGIN"); } m_Value = value; if (test || m_test) { System.out.println("Coordinate :: setValue() END"); } }
4
@Override protected final boolean display(final JPanel panel) { panel.setLayout(new GridLayout(0, 1)); final Font xFieldFont = Font.decode("Arial 12 bold"); final Dimension xFieldSize = new Dimension(xFieldFont.getSize() * 4, xFieldFont.getSize()); { final JPanel headerPanel = new JPanel(); final JLabel headerLabelW = new JLabel(" Idx "); final JLabel headerLabelE = new JLabel("Opt"); final JLabel headerLabelC = new JLabel(" Numbers"); headerPanel.setLayout(new BorderLayout()); headerPanel.add(headerLabelW, BorderLayout.WEST); headerPanel.add(headerLabelE, BorderLayout.EAST); headerPanel.add(headerLabelC); panel.add(headerPanel); } final List<Integer> keys = new ArrayList<>(this.indices.keySet()); java.util.Collections.sort(keys); for (final Integer key : keys) { final JPanel trackPanel = new JPanel(); final JPanel idxPanel = new JPanel(); final JTextField xField = new JTextField(key.toString()); final JCheckBox optBox = new JCheckBox(); final String title; { final Set<?> instruments_ = this.instruments.get(key); final String titleString = this.titles.get(key); title = (titleString == null ? "<No title>" : titleString) + " " + (instruments_ == null ? "[?]" : instruments_ .toString()); } trackPanel.setLayout(new BorderLayout()); idxPanel.setLayout(new GridLayout(1, 0)); trackPanel.add(xField, BorderLayout.WEST); trackPanel.add(idxPanel); trackPanel.add(optBox, BorderLayout.EAST); trackPanel.add(new JLabel(title), BorderLayout.SOUTH); xField.setFont(xFieldFont); xField.setPreferredSize(xFieldSize); final JTextField numField = new JTextField(this.indices.get(key)); this.idxToNum.put(key, numField); idxPanel.add(numField); panel.add(trackPanel); this.idxToField.put(key, xField); this.idxToOpt.put(key, optBox); } final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BorderLayout()); buttonPanel.add(Button.OK.getButton(), BorderLayout.EAST); buttonPanel.add(Button.ABORT.getButton(), BorderLayout.WEST); panel.add(buttonPanel); return false; }
4
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
public void compute() { if(this.expandCounter > 350) { this.view.printFailure(); return; } this.maze[this.currentNode.getX()][this.currentNode.getY()]++; this.view.printMaze(this.currentNode, this.closedNodes); // Print the current maze if(this.checkerObject.isGoal(this.currentNode)) { // End of algorithm this.view.printSolution(this.closedNodes, this.deadEndList); this.view.printSuccess(); return; } if(((this.currentNode.getX()-1)>0 && (this.currentNode.getX()+1)<(this.checkerObject.getSize().getX()-1))&&((this.currentNode.getY()-1)>0 && (this.currentNode.getY()+1)<(this.checkerObject.getSize().getY()-1))) { // Checks 2 nodes ahead and positions current node there if possible this.checkerObject.nodeCheckAll(new Node(this.currentNode.getX(), this.currentNode.getY()), this.closedNodes, true); if(futureStep()) { compute(); } } this.checkerObject.nodeCheckAll(this.currentNode, this.closedNodes); if(!stageOne()) { super.verifyDeadEnd(); } // Repeat computation if not exhausted compute(); }
8
private static void quit() { System.out.println("Want to see the paths you took? \n Press 'f' to view from the beginning \n Press 'r' to view from the end"); String walkthrough = transactionDone.nextLine(); try{ if(walkthrough.equalsIgnoreCase("f")){ while(moves>=0){ System.out.println(lookDownUp.dequeue()); moves--; } } else if(walkthrough.equalsIgnoreCase("r")){ while(moves>=0){ System.out.println(lookUpDown.pop()); moves--; } } }catch(Exception ex){ System.out.println(ex.getMessage()); } System.out.println(""); stillPlaying = false; }
5
@Column(name = "CUE_CUENTA_CONCATENADA") @Id public String getCueCuentaConcatenada() { return cueCuentaConcatenada; }
0
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> <T-IS-ARE> cursed with the taint of evil!"):L("^S<S-NAME> @x1 for <T-YOUPOSS> need to be tainted with evil!^?",prayWord(mob))); final CMMsg msg3=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_VERBAL|CMMsg.TYP_MIND|(auto?CMMsg.MASK_ALWAYS:0),null); if((mob.location().okMessage(mob,msg))&&(mob.location().okMessage(mob,msg3))) { mob.location().send(mob,msg); mob.location().send(mob,msg3); if((msg.value()<=0)&&(msg3.value()<=0)) maliciousAffect(mob,target,asLevel,0,-1); } } else return maliciousFizzle(mob,null,L("<S-NAME> @x1 for <T-YOUPOSS> to be tainted, but nothing happens.",prayWord(mob))); // return whether it worked return success; }
9
public String toString() { StringBuffer buf = new StringBuffer(); for (int yPos = 0; yPos <= maxIndex; yPos++) { for (int xPos = 0; xPos <= maxIndex; xPos++) { Tile tile = getTile(xPos, yPos); String tileStr = "(empty)"; if (tile != null) tileStr = tile.getName(); buf.append(tileStr); if (xPos < maxIndex) { // Pad with spaces to a length of 11 for (int i = 0; i < 11 - tileStr.length(); i++) buf.append(' '); } } // End of row if (yPos < maxIndex) buf.append('\n'); } return buf.toString(); }
6
public void mouseReleased(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { if (!pickedUp) { throw new RuntimeException("dropping without prior dragging?"); } dragHandler.mouseReleased(e); // if the block was dragged before...then if (dragging) { BlockLink link = getNearbyLink(); // look for nearby link // opportunities WorkspaceWidget widget = null; // if a suitable link wasn't found, just drop the block if (link == null) { widget = lastDragWidget; stopDragging(this, widget); } // otherwise, if a link WAS found... else { /* * Make sure that no matter who's connecting to whom, the * block that's being dragged gets dropped on the parent * widget of the block that's already on the canvas. */ if (blockID.equals(link.getSocketBlockID())) { // dragged block is the socket block, so take plug's // parent. widget = workspace.getEnv() .getRenderableBlock(link.getPlugBlockID()) .getParentWidget(); } else { // dragged block is the plug block, so take the socket // block's parent. widget = workspace.getEnv() .getRenderableBlock(link.getSocketBlockID()) .getParentWidget(); } // drop the block and connect its link stopDragging(this, widget); link.connect(); workspace.notifyListeners(new WorkspaceEvent(workspace, widget, link, WorkspaceEvent.BLOCKS_CONNECTED)); workspace.getEnv() .getRenderableBlock(link.getSocketBlockID()) .moveConnectedBlocks(); } // set the locations for X and Y based on zoom at 1.0 this.unzoomedX = this.calculateUnzoomedX(this.getX()); this.unzoomedY = this.calculateUnzoomedY(this.getY()); workspace.notifyListeners(new WorkspaceEvent(workspace, widget, link, WorkspaceEvent.BLOCK_MOVED, true)); if (widget instanceof MiniMap) { workspace.getMiniMap().animateAutoCenter(this); } } } pickedUp = false; if (e.isPopupTrigger() || SwingUtilities.isRightMouseButton(e) || e.isControlDown()) { // add context menu at right click location to provide functionality // for adding new comments and removing comments PopupMenu popup = ContextMenu.getContextMenuFor(this); add(popup); popup.show(this, e.getX(), e.getY()); } workspace.getMiniMap().repaint(); }
9
public void loadChunks(Chunk chunk){ this.attachChild(chunk); chunks[chunk.getX()][chunk.getZ()] = chunk; }
0
public void updateMidiInSelectedItems(String[] midiInDevices) { for (int i = 0; i < midiInMenu.getItemCount(); i++) { String name = midiInMenu.getItem(i).getText(); if (name == null || name.equals("No MIDI Input Devices Enabled")) { continue; } String[] pieces = name.split("MIDI Input: "); boolean found = false; for (int j = 0; j < midiInDevices.length; j++) { if (midiInDevices[j] == null) { continue; } if (pieces[1].compareTo(midiInDevices[j]) == 0) { midiInMenu.getItem(i).setSelected(true); found = true; } } if (!found) { midiInMenu.getItem(i).setSelected(false); } } }
7
public boolean equals (Object o) { if (o instanceof QueueElement) { QueueElement temp = (QueueElement) o; if ((sub == temp.sub) && (set.size() == temp.set.size())) return (true); } return (false); }
3
public HorseRaceMatch(int matchType, Playmode playmode) { super(matchType, playmode); this.animationStand = "STAND"; this.animationStandOpen = "STAND_OPEN"; this.animationMove = "MOVE"; this.keytoPress = 'A'; this.gameInfoTime = (3 * 1000 / GAMEINTERVAL); this.countdownTime = (3 * 1000 / GAMEINTERVAL); this.gameTime = (1 * 60 * 1000 / GAMEINTERVAL); this.addScoreTime = (3 * 1000 / GAMEINTERVAL); this.showScoreTime = (3 * 1000 / GAMEINTERVAL); this.currentGameTime = 0; this.finishedPlayerIDs = new ArrayList<>(); gameObjects.put("BACKGROUND", new GameObject(0, 0, this.getSize())); gameObjects.put("GOALLINE", new GameObject(655, 0, new Dimension(100, this.getHeight()))); int playerCounter = 0; for (Team team : playmode.getTeams()) { for (User user : team.getUser()) { HorseGO horse = new HorseGO(5, playerCounter * 40 + 25, new Dimension(40,15)); horse.setAnimationCounterMax(30); gameObjects.put("PLAYER" + user.getID(), horse); playerCounter++; } } imagesLoaded = false; }
2
public Holiday(int p_driverId, Calendar p_startDate, Calendar p_endDate) throws Exception{ //instanciate the class with the variables provided this.driverId = p_driverId; this.startDate = p_startDate; this.endDate = p_endDate; Calendar acceptDates = (Calendar) startDate.clone(); if(!this.hasEnoughDays()) throw new NotEnoughHolidaysException(); else { for(int i = 1; i <= length(); i++){ if(this.dayIsClear(acceptDates)){ //for each day set the driver unavilable DriverInfo.setAvailable(driverId, acceptDates.getTime(), false); DriverInfo.setHolidaysTaken(driverId,DriverInfo.getHolidaysTaken(driverId) + 1); } acceptDates.add(Calendar.DAY_OF_MONTH, 1); } } }
3
public int[] generateSamplingLoop(int[] A, int m) { if (A == null || A.length < m || m <= 0) { return A; } int[] subSet = new int[m]; for (int i = 0; i < m; i++) { subSet[i] = A[i]; } for (int i = m; i < A.length; i++) { int randomIndex = new Random().nextInt(i + 1); if (randomIndex < m) { subSet[randomIndex] = A[i]; } } return subSet; }
6
private boolean r_postlude() { int among_var; int v_1; // repeat, line 62 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 62 // [, line 63 bra = cursor; // substring, line 63 among_var = find_among(a_1, 3); if (among_var == 0) { break lab1; } // ], line 63 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 64 // <-, line 64 slice_from("\u00E3"); break; case 2: // (, line 65 // <-, line 65 slice_from("\u00F5"); break; case 3: // (, line 66 // next, line 66 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
8
public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { buf.setLength(0); buf.append(tab2).append("LOCALVARIABLE ").append(name).append(' '); appendDescriptor(FIELD_DESCRIPTOR, desc); buf.append(' '); appendLabel(start); buf.append(' '); appendLabel(end); buf.append(' ').append(index).append('\n'); if (signature != null) { buf.append(tab2); appendDescriptor(FIELD_SIGNATURE, signature); TraceSignatureVisitor sv = new TraceSignatureVisitor(0); SignatureReader r = new SignatureReader(signature); r.acceptType(sv); buf.append(tab2).append("// declaration: ") .append(sv.getDeclaration()).append('\n'); } text.add(buf.toString()); if (mv != null) { mv.visitLocalVariable(name, desc, signature, start, end, index); } }
2
public static String getOS() { String fullName = System.getProperty("os.name").toLowerCase(); if(fullName.startsWith("windows")) { return "windows"; } else if(fullName.startsWith("mac")) { return "macosx"; } else if(fullName.startsWith("linux")) { return "linux"; } else if(fullName.startsWith("sun") || fullName.startsWith("solaris")) { return "solaris"; } else if(fullName.startsWith("freebsd")) { return "freebsd"; } return "unknown"; }
6
private void btn_aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_aceptarActionPerformed if (lab_modo.getText().equals("Alta")){ if (camposCompletos()){ ocultar_Msj(); insertar(); menuDisponible(true); modoConsulta(); updateTabla(); } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } else{ if (lab_modo.getText().equals("Baja")){ if (!field_codigo.getText().equals("")){ if(!existe(Integer.parseInt(field_codigo.getText()))){ mostrar_Msj_Error("Ingrese un codigo que se encuentre registrado en el sistema"); field_codigo.requestFocus(); } else{ ocultar_Msj(); eliminar(); menuDisponible(true); modoConsulta(); vaciarCampos(); updateTabla(); } } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } else{ if (lab_modo.getText().equals("Modificación")){ if (!field_codigo.getText().equals("")){ if(!existe(Integer.parseInt(field_codigo.getText()))){ mostrar_Msj_Error("Ingrese un codigo que se encuentre registrado en el sistema"); field_codigo.requestFocus(); } else{ if (camposCompletos()){ ocultar_Msj(); modificar(); menuDisponible(true); modoConsulta(); updateTabla(); } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } } } }//GEN-LAST:event_btn_aceptarActionPerformed
9
public void update() { // moves robot or scrolls background if (speedX < 0) { centerX += speedX; } if (speedX == 0 || speedX < 0) { bg1.setSpeedX(0); bg2.setSpeedX(0); } if (centerX <= 200 && speedX > 0) { centerX += speedX; } if (speedX > 0 && centerX > 200) { bg1.setSpeedX(-MOVESPEED / 5); bg2.setSpeedX(-MOVESPEED / 5); } // updates Y position centerY += speedY; // handles jumping speedY += 1; if (speedY > 3) { jumped = true; } // prevents going beyond coordinate of 0 if (centerX + speedX <= 60) { centerX = 61; } rect.setRect(centerX - 34, centerY - 63, 68, 63); rect2.setRect(rect.getX(), rect.getY() + 63, 68, 64); rect3.setRect(rect.getX() - 26, rect.getY() + 32, 26, 20); rect4.setRect(rect.getX() + 68, rect.getY() + 32, 26, 20); yellowRed.setRect(centerX - 110, centerY - 110, 180, 180); footleft.setRect(centerX - 50, centerY + 20, 50, 15); footright.setRect(centerX, centerY + 20, 50, 15); }
9
private void createUnits() { ArrayList<Building> buildings = g.map.getPlayersBuildings(this); boolean hasMoney = true; while (hasMoney) { for (Building building : buildings) { if (building instanceof Factory) { ((Factory) building).recruitTank(g.map, building.getCell(), true); } if (building instanceof Barracks) { ((Barracks) building).recruitMarine(g.map, building.getCell(), true); } } if (buildings.contains(Barracks.class)) { hasMoney = this.getMoney() >= Marine.cost; } else if (buildings.contains(Factory.class)) { hasMoney = this.getMoney() >= Tank.cost; } else { hasMoney = false; } } }
6
public void draw() { if(b != null) { b.move(); } Zen.setColor(0, 0, 155); if (direction == 0 || direction == 2) Zen.fillRect(x-10, y-15, 20, 30); else Zen.fillRect(x-15, y-10, 30, 20); Zen.setColor(0,0,0); if(direction ==0 || direction ==2) Zen.fillRect(x-2, y-(2-direction)*10, 4, 20); if(direction ==1 || direction ==3) Zen.fillRect(x-(direction-1)*10, y-2, 20,4); }
7
public String toString() { String ret = new String(); for (int i = 0; i < elements.size(); i++) { if (ret.length() > 0) { ret = ret + ','; } ret = ret + elements.get(i).toString(); } return '[' + ret + ']'; }
2
public RightLinearGrammarToFSAConverter() { }
0
@Override public void execute(DebuggerVirtualMachine dvm) { dvm.popFrameRunTimeStack(); if (!dvm.isEmptyRunTimeStack()) { dvm.popRunTimeStack(); } dvm.newFrameAtRunTimeStack(0); dvm.exitFunction(); dvm.saveEnvironmentStackSize(); dvm.enterFunction(); for (int arg : dvm.getSavedFunctionArgs()) { dvm.pushRunTimeStack(arg); } dvm.setPc(dvm.getSavedFunctionAddress()); dvm.setStepInPending(true); dvm.setRunning(true); }
2
public JComboBox getjComboBoxLabo() { return jComboBoxLabo; }
0
public static boolean allVariablesNextP(AllPurposeIterator self) { { int cursor = self.iteratorInteger; Symbol symbol = null; GlobalVariable variable = null; while (cursor < self.iteratorSecondInteger) { symbol = ((Symbol)((Stella.$SYMBOL_ARRAY$.theArray)[cursor])); if ((symbol != null) && AllPurposeIterator.selectedMetaObjectP(self, ((Module)(symbol.homeContext)))) { variable = ((GlobalVariable)(Stella.$GLOBAL_VARIABLE_LOOKUP_TABLE$.lookup(symbol))); if ((variable != null) && (AllPurposeIterator.selectedMetaObjectP(self, variable.homeModule()) && ((self.iteratorFilterCode == null) || ((Boolean)(edu.isi.stella.javalib.Native.funcall(self.iteratorFilterCode, null, new java.lang.Object [] {variable, self}))).booleanValue()))) { self.value = variable; self.iteratorInteger = cursor + 1; return (true); } } cursor = cursor + 1; } return (false); } }
7
public boolean adicionarDependente(String nomeDependente){ for(String d: dependentes){ if( d.equalsIgnoreCase(nomeDependente) ){ return false; } } return dependentes.add(nomeDependente); }
2
public int hashCode() { int lHashCode = 0; if (this.getCod_Jogo() != null) { lHashCode += this.getCod_Jogo().hashCode(); } if (this.getCod_Jornada() != null) { lHashCode += this.getCod_Jornada().hashCode(); } if (this.getCod_Competicao() != null) { lHashCode += this.getCod_Competicao().hashCode(); } if (this.getCod_Campo() != null) { lHashCode += this.getCod_Campo().hashCode(); } if (lHashCode == 0) { lHashCode = super.hashCode(); } return lHashCode; }
5
public void updateTableData() { ArrayList<File> sortedFiles = Revisions.getRevisionsList(); Object[][] data = new Object[sortedFiles.size()][columnNames.length]; File file = null; Date date = new Date(); String revisionName = ""; try { for( int i = 0; i < sortedFiles.size(); i++ ) { file = sortedFiles.get(i); revisionName = Revisions.getRevisionVersion(file.getName()); date.setTime(file.lastModified()); String configVer = (String)ObjectUtils.ternary( ConfigManager.getConfigManager().getActiveContainer(), "getInstallVersion", ""); data[i][0] = revisionName + ((revisionName.equals(configVer)) ? " (current)" : "" ); data[i][1] = new SimpleDateFormat("MM/dd/yyyy h:mm a").format(date); } } catch (Exception e) { trace(STDERR, e); } // Add row(s) if needed for( int i = 0; i < sortedFiles.size(); i++ ) { for( int j = 0; j < columnNames.length; j++ ) { if( table.getModel().getRowCount() <= i ) ((DefaultTableModel)table.getModel()).addRow(data[i]); else table.getModel().setValueAt(data[i][j], i, j); } } // Remove row(s) if needed if( sortedFiles.size() < table.getModel().getRowCount() ) { for( int i = table.getModel().getRowCount()-1; i >= sortedFiles.size(); i-- ) { ((DefaultTableModel)table.getModel()).removeRow(i); } } }
8
public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SegmentarCerebro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SegmentarCerebro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SegmentarCerebro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SegmentarCerebro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { //new SegmentarCerebro().setVisible(true); } }); }
6
public int[] findSum(int[] array, int target) { for (int i = 1; i < array.length; i++) { for (int j = i; j >= 1 && array[j] < array[j - 1]; j--) { int swap = array[j]; array[j] = array[j - 1]; array[j - 1] = swap; } } int start = 0, end = array.length - 1; int closestSum = 0; int closestStart = -1, closestEnd = -1; while (start < end) { int sum = array[start] + array[end]; if (Math.abs(sum - target) < Math.abs(closestSum - sum)) { closestSum = sum; closestStart = start; closestEnd = end; } if (sum == target) { break; } else if (sum < target) { start++; } else { end--; } } return new int[] { array[closestStart], array[closestEnd] }; }
7
public boolean isAlive() { return currentState == ProcessState.PAUSED || currentState == ProcessState.RUNNING; }
1
@Override protected void createReaderWriter() throws JoeException { ourReaderWriter = new PdbSPReaderWriter() ; if (ourReaderWriter == null) { throw new JoeException(UNABLE_TO_CREATE_OBJECT) ; } }
1
public OBJModel(String fileName) { positions = new ArrayList<Vector3f>(); texCoords = new ArrayList<Vector2f>(); normals = new ArrayList<Vector3f>(); indices = new ArrayList<OBJIndex>(); hasTexCoords = false; hasNormals = false; BufferedReader meshReader = null; try { meshReader = new BufferedReader(new FileReader(fileName)); String line; while((line = meshReader.readLine()) != null) { String[] tokens = line.split(" "); tokens = Util.removeEmptyStrings(tokens); if(tokens.length == 0 || tokens[0].equals("#")) continue; else if(tokens[0].equals("v")) { positions.add(new Vector3f(Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), Float.valueOf(tokens[3]))); } else if(tokens[0].equals("vt")) { texCoords.add(new Vector2f(Float.valueOf(tokens[1]), Float.valueOf(tokens[2]))); } else if(tokens[0].equals("vn")) { normals.add(new Vector3f(Float.valueOf(tokens[1]), Float.valueOf(tokens[2]), Float.valueOf(tokens[3]))); } else if(tokens[0].equals("f")) { for(int i = 0; i < tokens.length - 3; i++) { indices.add(parseOBJIndex(tokens[1])); indices.add(parseOBJIndex(tokens[2 + i])); indices.add(parseOBJIndex(tokens[3 + i])); } } } meshReader.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } }
9
public SlaveGameThread(PongWindow window) throws IOException { super("SlaveGameThread"); this.window = window; masterSocket = new ServerSocket(6789, 0, Pong.address); }
0
public void setPhone(String phone) { Phone = phone; }
0
@Override public void setLong(long i, long value) { if (value < 0 || value > 1) { throw new IllegalArgumentException("The value has to be 0 or 1."); } if (ptr != 0) { Utilities.UNSAFE.putByte(ptr + i, (byte) value); } else { if (isConstant()) { throw new IllegalAccessError("Constant arrays cannot be modified."); } data[(int) i] = (byte) value; } }
4
@Override public void updatePartialView(final AbstractFleedModel fleedModel, final int i, final int j) { int gridValue = fleedModel.getSeaGrid()[i + 1][j + 1]; // Just water if (gridValue == 0 || gridValue == AbstractFleedModel.MISS) { gridButtons[i][j].setBackground(gridValue == 0 ? GuiConstants.WATER_COLOR : GuiConstants.WATER_MISS_COLOR); gridButtons[i][j].setBorder(GuiConstants.WATER_BORDER); gridButtons[i][j].setText(gridValue == 0 ? "" : "x"); return; } // Ship is undamaged or destroyed if (gridValue > 0) { Ship ship = fleedModel.getShips()[gridValue - 1]; gridButtons[i][j].setBackground(ship.isDestroyed() ? GuiConstants.DESTROYED_COLOR : GuiConstants.SHIP_COLOR); gridButtons[i][j].setBorder(ship.isDestroyed() ? GuiConstants.DESTROYED_BORDER : GuiConstants.SHIP_BORDER); gridButtons[i][j].setText(ship.isDestroyed() ? GuiConstants.DEAD_SYMBOL : "" + ship.getSize()); return; } // Ship is partially damaged if (gridValue < 0) { gridButtons[i][j].setBackground(GuiConstants.HIT_COLOR); gridButtons[i][j].setBorder(GuiConstants.HIT_BORDER); return; } }
9
private void cancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtnActionPerformed int indx = activityList.getSelectedIndex() - 1; transferChanges(false); int n = 0; //see if updated if (!activityNameBox.getText().equals("") && (editingAct != null && !editingAct.equals(original))) { //request confirmation of cancel n = confirmDiscard(); } if (n == 0) { this.dispose(); } }//GEN-LAST:event_cancelBtnActionPerformed
4
protected int alphabetaCardPicking(GameState state, ArrayList<Color> playerList, ArrayList<Card> choiceList, int alpha, int beta, Color faction) { //Base case, if there aren't any more players we go to the first action if(playerList.size() == 0) { GameState tempState = new GameState(state); for(Card c : choiceList) { tempState.getPlayer(c.getFaction()).removeFromHand(c); tempState.getBoard().addCard(c); } tempState.setTime(Time.DAY); return alphabeta(tempState, alpha, beta, faction); } else { //otherwise, we iterate through all the possibilities of a given player's card choices Color pColor = playerList.remove(0); if(faction.equals(pColor)) { for(Card c : state.getPlayer(pColor).getHand()) { ArrayList<Card> tempChoice = new ArrayList<Card>(choiceList); tempChoice.add(c); alpha = Math.max(alpha, alphabetaCardPicking(state, new ArrayList<Color>(playerList), tempChoice, alpha, beta, faction)); if(alpha >= beta) return alpha; } //we also need to check if they have no cards in their hand if(state.getPlayer(pColor).getHand().isEmpty()) { alpha = Math.max(alpha, alphabetaCardPicking(state, new ArrayList<Color>(playerList), new ArrayList<Card>(choiceList), alpha, beta, faction)); } return alpha; } else { for(Card c : state.getPlayer(pColor).getHand()) { ArrayList<Card> tempChoice = new ArrayList<Card>(choiceList); tempChoice.add(c); beta = Math.min(beta, alphabetaCardPicking(state, new ArrayList<Color>(playerList), tempChoice, alpha, beta, faction)); if(alpha >= beta) return beta; } if(state.getPlayer(pColor).getHand().isEmpty()) { beta = Math.min(beta, alphabetaCardPicking(state, new ArrayList<Color>(playerList), new ArrayList<Card>(choiceList), alpha, beta, faction)); } return beta; } } }
9
public CheckResultMessage checkSheetFormat() { if(hWorkbook == null && xWorkbook == null){ return error("读取报表"+fileName+"失败"); } if (checkVersion(file).equals("2003")) { for (String sheetName : sheetNames) { hSheet = hWorkbook.getSheet(sheetName); if (hSheet == null) { return error(reportName + " 缺少Sheet " + sheetName); } } } else { for (String sheetName : sheetNames) { xSheet = xWorkbook.getSheet(sheetName); if (xSheet == null) { return error(reportName + " 缺少Sheet " + sheetName); } } } return pass(reportName + " <" + fileName + "> Sheet格式校验正确"); }
7
protected static void putHumanProp(String correctName, Element root) { String wikitext = root.getChild("parse").getChild("wikitext") .getValue(); TemplateReader tr = new TemplateReader(wikitext); tr.read(); tr.write(correctName); Element element = root.getChild("parse").getChild("categories"); Iterator<Element> itr = element.getChildren("cl").iterator(); ArrayList<String> categories = new ArrayList<String>(); while (itr.hasNext()) { Element e = (Element) itr.next(); categories.add(e.getText()); } CategoryReader cr = new CategoryReader(categories); cr.read(); cr.write(correctName); Assistant as = new Assistant(); if(as.getHuman(correctName).isEmpty()) as.removeHumanProp(correctName); as.makePersistentHumanProp(); }
2
public int ingresarPreguntaTema2(Pregunta_Tema p) { try { if (con.isClosed()) { con = bd.conexion(); } String consulta; int cont = p.getNroPregunta(); if (p.getRespuesta() != 0) { consulta = "INSERT INTO Pregunta_Tema2 VALUES('" + p.getTema().getCodigo() + "','" + p.getPregunta().getCodigo() + "','" + p.getRespuesta() + "','" + cont + "','" + p.getCombinacion().getCodigo() + "')"; } else { consulta = "INSERT INTO Pregunta_Tema2 (f_tema, f_pregunta, nroPregunta, combinacionOpcion_idcombinacion) VALUES('" + p.getTema().getCodigo() + "','" + p.getPregunta().getCodigo() + "','" + cont + "','" + p.getCombinacion().getCodigo() + "')"; } Statement sta = con.createStatement(); int rs = sta.executeUpdate(consulta); ////con.close(); if (rs == 1 || rs == 4) { return 1; } else { return 0; } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Problemas creando preguntaTema!. Error: " + ex); } finally { if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } return 0; }
7
void initResources() { final Class clazz = ControlExample.class; if (resourceBundle != null) { try { if (images == null) { images = new Image[imageLocations.length]; for (int i = 0; i < imageLocations.length; ++i) { InputStream sourceStream = clazz.getResourceAsStream(imageLocations[i]); ImageData source = new ImageData(sourceStream); if (imageTypes[i] == SWT.ICON) { ImageData mask = source.getTransparencyMask(); images[i] = new Image(null, source, mask); } else { images[i] = new Image(null, source); } try { sourceStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return; } catch (Throwable t) { } } String error = (resourceBundle != null) ? getResourceString("error.CouldNotLoadResources") : "Unable to load resources"; //$NON-NLS-1$ freeResources(); throw new RuntimeException(error); }
7
public void renderTextCharacter(int xp, int yp, Sprite sprite, int color, boolean fixed) { if(fixed) { xp -= xOffset; yp -= yOffset; } for (int y = 0; y < sprite.getHeight(); y++) { int ya = y + yp; for (int x = 0; x < sprite.getWidth(); x++) { int xa = x + xp; if(xa < 0 || xa >= width || ya < 0 || ya >= height) continue; int col = sprite.pixels[x + y * sprite.getWidth()]; if(col != ALPHA_COL && col != 0xff7f007f) pixels[xa + ya * width] = color; } } }
9
public void setFitness(){ this.fitness = fitness(); }
0
@Override public String getApiKey() { return apiKey; }
0
public static ListTableModel createModelFromResultSet(ResultSet resultSet) throws SQLException { ResultSetMetaData metaData = resultSet.getMetaData(); int columns = metaData.getColumnCount(); // Create empty model using the column names ArrayList<String> columnNames = new ArrayList<String>(); for (int i = 1; i <= columns; i++) { String columnName = metaData.getColumnName(i); String columnLabel = metaData.getColumnLabel(i); if (columnLabel.equals(columnName)) columnNames.add( formatColumnName(columnName) ); else columnNames.add( columnLabel ); } ListTableModel model = new ListTableModel( columnNames ); model.setModelEditable( false ); // Assign the class of each column for (int i = 1; i <= columns; i++) { try { String className = metaData.getColumnClassName( i ); model.setColumnClass(i - 1, Class.forName(className)); } catch ( Exception exception ) {} } // Get row data ArrayList<List> data = new ArrayList<List>(); while (resultSet.next()) { ArrayList<Object>row = new ArrayList<Object>(columns); for (int i = 1; i <= columns; i++) { Object o = resultSet.getObject(i); row.add( o ); } data.add( row ); } model.insertRows(0, data); return model; }
6
public static int unsignedBytesToInt (byte[] byteArray, int selector, int howMany, int byteOrdering) { // byteOrdering // selector should always point to lowest byte in array // local vars int a = 0 ; switch (byteOrdering) { case HI_TO_LO: // aka BIG_ENDIAN switch (howMany) { case 1: return ((int) (byteArray[selector] & 0xFF)) ; case 2: a = ((int) (byteArray[selector++] & 0xFF)) << 8; a += ((int) (byteArray[selector] & 0xFF)) ; return a; case 3: a = ((int) (byteArray[selector++] & 0xFF)) << 16; a += ((int) (byteArray[selector++] & 0xFF)) << 8; a += ((int) (byteArray[selector] & 0xFF)) ; return a; default: return 0 ; } // end switch case LO_TO_HI: // aka LOW_ENDIAN switch (howMany) { case 1: return ((int) (byteArray[selector] & 0xFF)) ; case 2: a = ((int) (byteArray[selector++] & 0xFF)) ; a += ((int) (byteArray[selector] & 0xFF)) << 8; return a; case 3: a = ((int) (byteArray[selector++] & 0xFF)) ; a += ((int) (byteArray[selector++] & 0xFF)) << 8; a += ((int) (byteArray[selector] & 0xFF)) << 16; return a; default: return 0 ; } // end switch default: return 0 ; } // end switch } // end method unsignedBytesToUInt;
8
public void selectAction() { List<TreeNode> visited = new LinkedList<TreeNode>(); TreeNode cur = this; visited.add(this); int depth = 0; while (cur.children!=null) { cur = cur.select(); visited.add(cur); depth+=1; if(cur==null) return; } if(depth<maxDepth && cur.nVisits>expandThd){ if(!cur.expand()){ if(cur.state.whoseTurn().equals(me)){ cur.totValue = -100; } else{ cur.totValue = 100; } return; } depth+=1; print = false; cur = cur.select(); visited.add(cur); if(cur==null){ System.out.println("null new node"); } print = false; } double value = randomSimulate(cur.state); //System.out.println("depth "+depth); for (TreeNode node : visited) { // would need extra logic for n-player game node.updateStats(value); } }
8
private void changeMusicVol(float delta) { float volume = music.getVolume(); switch (musicState) { case 1: if (music.isLooping() || music.isPlaying()) { if (volume > 0.10f) volume -= delta; else { changeToMainMenu(); } music.setVolume(Math.abs(volume)); } break; case 0: if (music.isLooping() || music.isPlaying()) { if (volume < 1.0f) volume += delta * 3; else { volume = 1.0f; } music.setVolume(volume); } break; } }
8
private void delete(int row) { if (!MyFactory.getResourceService().hasRight(MyFactory.getCurrentUser(), Resource.MY_PAID_W)) { return; } PaidDetail selectedRow = result == null ? null : result.get(row); if (selectedRow != null) { if (JOptionPane.showConfirmDialog(null, "确定要删除?") == JOptionPane.OK_OPTION) { if (MyFactory.getPaidDetailService().delete(selectedRow.getId())) { JOptionPane.showMessageDialog(null, "删除成功!"); refreshData(); } } } }
5
public void setTxtNom(JTextField txtNom) { this.txtNom = txtNom; }
0
private static int sumTwoPow(int n) { // TODO Auto-generated method stub if(n==0){ return 1; }else{ return 2*sumTwoPow(n-1); } }
1
@Override public PermissionType getType() { return PermissionType.ENTITY; }
0