method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
541f6330-3b3b-4d39-8159-311f14fc4a41
5
@Override public String getColumnName(int column) { switch(column) { case ID : return "ID"; case MEDECIN : return "Médecin"; case SPECIALISATION : return "Spécialisation"; case DATE : return "Date"; case HEURE : return "Heure"; default: return "NO DATA"; } }
d589154d-6fb4-4e64-9cb6-fe0d7e249650
9
private String cleanFontName(String fontName) { // crystal report ecoding specific, this will have to made more // robust when more examples are found. if (fontName.indexOf('+') >= 0) { int index = fontName.indexOf('+'); String tmp = fontName.substring(index + 1); try { Integer.parseInt(tmp); fontName = fontName.substring(0, index); } catch (NumberFormatException e) { if (logger.isLoggable(Level.FINE)) { logger.fine("error cleaning font base name " + fontName); } } } // clean up the font name, strip a subtyp reference from name while (fontName.indexOf('+') >= 0) { int index = fontName.indexOf('+'); fontName = fontName.substring(index + 1, fontName.length()); } // strip commas from basefont name and replace with dashes if (subtype.equals("Type0") || subtype.equals("Type1") || subtype.equals("MMType1") || subtype.equals("TrueType")) { if (fontName != null) { // normalize so that java.awt.decode will work correctly fontName = fontName.replace(',', '-'); } } return fontName; }
08b2cbff-b888-4c67-9e20-49ac98615411
8
public Object retrieve(String key) { if(key == null) { return null; } totalAccess++; if(entryMap.containsKey(key)) { LFUEntry entry = entryMap.get(key); pq.remove(entry); entry.hit++; pq.add(entry); if(debug) System.out.println("Hit cache entry: " + key); return entry.value; } else if(refresherMap.containsKey(key)) { LFUEntry newEntry = new LFUEntry(key, refresherMap.get(key)); newEntry.hit++; if(size > 0) { if(entryMap.size() >= size) { LFUEntry pollEntry = pq.poll(); entryMap.remove(pollEntry.key); } pq.add(newEntry); entryMap.put(key, newEntry); } if(debug) System.out.println("New cache entry: " + key); return newEntry.value; } else { if(debug) System.out.println("Please provide according refresher to initilize key!"); return null; } }
76d31ee0-0e92-40ec-839b-ce3432588f87
8
@Override public void unInvoke() { // undo the affects of this spell if(affected instanceof CagedAnimal) { final CagedAnimal target=(CagedAnimal)affected; final MOB mob=target.unCageMe(); super.unInvoke(); if(canBeUninvoked()) { final Ability A=mob.fetchEffect(ID()); if(A!=null) mob.delEffect(A); mob.recoverCharStats(); mob.recoverPhyStats(); setChildStuff(mob, target); final Room R=CMLib.map().roomLocation(target); if(R!=null) mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> feel(s) like <S-HIS-HER> old self again.")); } } else if(affected instanceof MOB) { final MOB mob=(MOB)affected; super.unInvoke(); if(canBeUninvoked()) if((mob.location()!=null)&&(!mob.amDead())) mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> feel(s) like <S-HIS-HER> old self again.")); } }
14a34a69-7338-44d3-8f35-f255a764236d
2
public static void main(String[] args) { Factory factory; if (args.length > 0) { factory = new PCFactory(); } else { factory = new NotPCFactory(); } for (int i = 0; i < 3; ++i) { System.out.print(factory.makePhrase() + " "); } System.out.println(); System.out.println(factory.makeCompromise()); System.out.println(factory.makeGrade()); }
c194cdc0-c000-49b4-8e28-926f478a9337
5
@Override public void actionPerformed(ActionEvent e) { /* When combo box changed, redraw preview panel. */ if (e.getSource()==m_mapList) { m_previewContainer.removeAll(); m_previewPanel = DrawSwatches(m_mapList.getSelectedIndex()); m_previewContainer.add(m_previewPanel); m_previewPanel.repaint(); m_previewPanel.revalidate(); } if (e.getSource()==m_closeButton) { m_mapList.setEnabled(true); CloseFrame(); } if (e.getSource()==m_saveButton) { GroupJVTApplication.dataVisualizer.SelectChartTab(); //line added SaveAndClose(); } if (e.getSource() == m_CustomButton) { ColourSelection select = new ColourSelection(); m_custom = select.InitMap(); if (m_custom == null) { } else { m_mapList.setEnabled(false); m_previewContainer.removeAll(); m_previewPanel = DrawSwatches(CUSTOM); m_previewContainer.add(m_previewPanel); m_previewPanel.repaint(); m_previewPanel.revalidate(); } } }
882dc084-23cd-4819-b555-b44fac892eb8
4
@Override public List<BankRequiredItem> getItemsNeededFromBank() { List<BankRequiredItem> list = new ArrayList<BankRequiredItem>(); if (ctx.equipment.select().id(ids).isEmpty() && ctx.backpack.select().id(ids).isEmpty()) { if (ctx.bank.opened()) { final Item item = ctx.bank.select().id(ids).sort(new Comparator<Item>() { @Override public int compare(Item o1, Item o2) { return Integer.valueOf(o1.id()).compareTo(o2.id()); } }).reverse().poll(); if (item.valid()) { list.add(new BankRequiredItem(1, true, slot, item.id())); } } list.add(new BankRequiredItem(1, true, slot, ids)); } return list; }
25d477a2-0089-4adf-b494-918698adcdfb
1
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just did a sonic blow!"); return random.nextInt((int) agility) * 2; } return 0; }
f4e4639e-4aaf-417f-b106-07d8eb6c77c2
1
public static String getStackTrace(Throwable t) { String stackTrace = null; try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); sw.close(); stackTrace = sw.getBuffer().toString(); } catch (Exception ex) { } return stackTrace; }
1c303920-f213-4469-9535-4c07ad55f56f
8
private void processGridResource_Polling(Sim_event ev) { Integer res_id_Integer; int res_id; AvailabilityInfo resAv = null; // Polls the resources that are available right now, as those // which are out of order were totally removed for (int i = 0; i < resList_.size(); i++) { res_id_Integer = (Integer) resList_.get(i); res_id = res_id_Integer.intValue(); pollResource(res_id); } // receive the polling back int resListSize = resList_.size(); for (int i = 0; i < resListSize; i++) { do { super.sim_pause(50); resAv = pollReturn(); } while (resAv == null); res_id = resAv.getResID(); /***************** // NOTE: this keeps printing at every n seconds interval. if (record_ == true) { System.out.println(super.get_name() + ": receives a poll response from " + GridSim.getEntityName(res_id) + ". resID: " + res_id + ". Is res available? " + resAv.getAvailability() + ". Clock: " + GridSim.clock()); } ****************/ // Find the AvailabilityInfo object corresponding to the resource // which has answered this poll request // and, if the resource is out of order, remove it from the // list of available resources. for (int j = 0; j < resList_.size(); j++) { if (((Integer) resList_.get(j)).intValue() == res_id) { // Only do anything when the res is out of order if (!resAv.getAvailability()) { removeResource(res_id); } } } // for } // for /**********/ if (record_) { if (resList_.size() == 0) { System.out.println(super.get_name() + ": After polling, no resource in the GIS. "); } } /*********/ // Schedule the following polling event. super.send(super.get_id(), GridSimTags.POLLING_TIME_GIS, GridSimTags.GRIDRESOURCE_POLLING); }
a13f0d9b-cc2c-41b6-b190-43ec874ee100
6
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String fct = request.getParameter("fct"); // Remplir BDD if(fct.compareTo("create")==0) { UserModel user = DataStore.getUser("user001"); if(user==null) { // Users UserModel usermod001 = new UserModel("user001","fake_bob","fake_bob@fake.com"); UserModel usermod002 = new UserModel("user002","fake_john","fake_john@fake.com"); UserModel usermod003 = new UserModel("user003","fake_emilie","fake_emilie@fake.com"); UserModel usermod004 = new UserModel("user004","fake_lola","fake_lola@fake.com"); UserModel usermod005 = new UserModel("user005","fake_tom","fake_tom@fake.com"); UserModel usermod006 = new UserModel("user006","fake_joe","fake_joe@fake.com"); UserModel usermod007 = new UserModel("user007","fake_estelle","fake_estelle@fake.com"); UserModel usermod008 = new UserModel("user008","fake_max","fake_max@fake.com"); DataStore.storeUser(usermod001); DataStore.storeUser(usermod002); DataStore.storeUser(usermod003); DataStore.storeUser(usermod004); DataStore.storeUser(usermod005); DataStore.storeUser(usermod006); DataStore.storeUser(usermod007); DataStore.storeUser(usermod008); // Teams TeamModel teammod001 = new TeamModel("team001","fake_ChicagoBulls","Chicago","Central"); TeamModel teammod002 = new TeamModel("team002","fake_BostonCeltics","Boston","Atlantic"); TeamModel teammod003 = new TeamModel("team003","fake_NewYorkNicks","New-York","Atlantic"); TeamModel teammod004 = new TeamModel("team004","fake_HoustonRockets","Houston","Southwest"); DataStore.storeTeam(teammod001); DataStore.storeTeam(teammod002); DataStore.storeTeam(teammod003); DataStore.storeTeam(teammod004); // Schedules SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date date001 = null; Date date002 = null; Date date003 = null; Date date004 = null; Date date005 = null; try { date001 = sdf.parse("2014-01-22T20:15:00"); date002 = sdf.parse("2014-02-10T20:20:00"); date003 = sdf.parse("2014-03-25T20:00:00"); date004 = sdf.parse("2014-10-01T20:25:00"); date005 = sdf.parse("2014-02-29T20:45:00"); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } ScheduleTeamModel schedmod001 = new ScheduleTeamModel(Sport.NBA,"sched001",date001, false, teammod001.getTeam_id(),teammod004.getTeam_id()); ScheduleTeamModel schedmod002 = new ScheduleTeamModel(Sport.NBA,"sched002",date002, false, teammod002.getTeam_id(),teammod003.getTeam_id()); ScheduleTeamModel schedmod003 = new ScheduleTeamModel(Sport.NBA,"sched003",date003, false, teammod003.getTeam_id(),teammod004.getTeam_id()); ScheduleTeamModel schedmod004 = new ScheduleTeamModel(Sport.NBA,"sched004",date004, false, teammod003.getTeam_id(),teammod001.getTeam_id()); ScheduleTeamModel schedmod005 = new ScheduleTeamModel(Sport.NBA,"sched005",date005, false, teammod004.getTeam_id(),teammod001.getTeam_id()); DataStore.storeSchedule(schedmod001); DataStore.storeSchedule(schedmod002); DataStore.storeSchedule(schedmod003); DataStore.storeSchedule(schedmod004); DataStore.storeSchedule(schedmod005); // Paris ParisVictoryModel paris001 = new ParisVictoryModel(usermod001.getUser_id(), schedmod001.getSched_id(), 5, Teams.HOME); ParisVictoryModel paris002 = new ParisVictoryModel(usermod002.getUser_id(), schedmod001.getSched_id(), 2, Teams.AWAY); ParisVictoryModel paris003 = new ParisVictoryModel(usermod002.getUser_id(), schedmod003.getSched_id(), 10, Teams.AWAY); ParisVictoryModel paris004 = new ParisVictoryModel(usermod003.getUser_id(), schedmod003.getSched_id(), 5, Teams.AWAY); ParisVictoryModel paris005 = new ParisVictoryModel(usermod004.getUser_id(), schedmod003.getSched_id(), 15, Teams.HOME); ParisVictoryModel paris006 = new ParisVictoryModel(usermod005.getUser_id(), schedmod003.getSched_id(), 15, Teams.HOME); ParisScoreModel paris007 = new ParisScoreModel(usermod005.getUser_id(), schedmod002.getSched_id(), 10, Teams.ALL); paris007.setScore_team_home(154); paris007.setScore_team_away(125); ParisScoreModel paris008 = new ParisScoreModel(usermod006.getUser_id(), schedmod002.getSched_id(), 1, Teams.HOME); paris008.setScore_team_home(80); ParisScoreModel paris009 = new ParisScoreModel(usermod007.getUser_id(), schedmod002.getSched_id(), 1, Teams.AWAY); paris009.setScore_team_away(80); ParisScoreModel paris010 = new ParisScoreModel(usermod008.getUser_id(), schedmod002.getSched_id(), 2, Teams.ALL); paris010.setScore_team_home(80); paris010.setScore_team_away(80); DataStore.storeNewParis(paris001); DataStore.storeNewParis(paris002); DataStore.storeNewParis(paris003); DataStore.storeNewParis(paris004); DataStore.storeNewParis(paris005); DataStore.storeNewParis(paris006); DataStore.storeNewParis(paris007); DataStore.storeNewParis(paris008); DataStore.storeNewParis(paris009); DataStore.storeNewParis(paris010); //APIRequest.getInstance().updateScheduleRequest(Sport.NBA); //APIRequest.getInstance().updateLeagueHierarchyRequest(Sport.NBA); } } else if(fct.compareTo("remove")==0) { DataStore.cleanAll(); UserService userService = UserServiceFactory.getUserService(); response.sendRedirect(userService.createLogoutURL("/")); } else if(fct.compareTo("finish")==0) { ScheduleModel stm = DataStore.getSchedule("sched001"); if(stm!=null) { ResultScoreModel result001 = new ResultScoreModel("sched001", 80, 60); ResultScoreModel result002 = new ResultScoreModel("sched002", 80, 80); ResultScoreModel result003 = new ResultScoreModel("sched003", 80, 90); ResultScoreModel result004 = new ResultScoreModel("sched004", 20, 90); ResultScoreModel result005 = new ResultScoreModel("sched005", 13, 26); DataStore.storeResult(result001); DataStore.storeResult(result002); DataStore.storeResult(result003); DataStore.storeResult(result004); DataStore.storeResult(result005); DataStore.updateSchedule("sched001", result001); DataStore.updateSchedule("sched002", result002); DataStore.updateSchedule("sched003", result003); DataStore.updateSchedule("sched004", result004); DataStore.updateSchedule("sched005", result005); } } response.sendRedirect("/"); }
abc3e35b-ebd3-4bd6-beaa-fb8cabc4af62
1
public void clean(){ try{ socket.close(); }catch(Exception e){ } }
2f28a81a-57fe-47f6-9b86-c973955db4a4
4
private void connect() { send(0, Main.player.getName()); String data = recive().trim(); String[] text = data.split("/"); if (!(text.length < 2)) { if (text[1].equalsIgnoreCase("success")) { System.out.println("Connected to Server"); connected = true; } else { connected = false; } if (text.length > 2) { String[] player = text[2].split(";"); for (String p : player) { String[] info = p.split(","); enemies.add(new Enemy(info[0], Float.parseFloat(info[1]), Float.parseFloat(info[2]))); } } } }
0c02af1b-6b5d-446e-9df6-0220c3d3961b
7
* @param offset * @param kindofsym * @return GeneralizedSymbol */ public static GeneralizedSymbol internBootstrapSymbolAt(String name, int offset, int kindofsym) { { ExtensibleSymbolArray symbolarray = null; GeneralizedSymbol symbol = null; switch (kindofsym) { case 0: symbol = Symbol.lookupSymbol(name); break; case 1: symbol = Surrogate.lookupSurrogate(name); break; case 2: symbol = Keyword.lookupKeyword(name); break; default: { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + kindofsym + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } if (symbol != null) { if (!(symbol.symbolId == offset)) { Stella.STANDARD_WARNING.nativeStream.println("Warning: intern-bootstrap-symbol-at: `" + symbol + "' is already interned at offset `" + symbol.symbolId + "'"); } return (symbol); } symbolarray = Stella.selectSymbolArray(kindofsym); if (ExtensibleSymbolArray.legalSymbolArrayOffsetP(symbolarray, offset) && (GeneralizedSymbol.getGeneralizedSymbolFromOffset(symbolarray, offset) != null)) { symbol = GeneralizedSymbol.getGeneralizedSymbolFromOffset(symbolarray, offset); Stella.STANDARD_WARNING.nativeStream.println("Warning: intern-bootstrap-symbol-at: `" + symbol + "' is already interned at offset `" + offset + "'"); return (symbol); } { ExtensibleSymbolArray array = Stella.selectSymbolArray(kindofsym); return (GeneralizedSymbol.helpInternGeneralizedSymbol(name, kindofsym, array, offset, ((Module)(Stella.$MODULE$.get())))); } } }
b9f7f3e1-1710-4414-a104-5363469a9a0c
9
public void load() throws IOException { boolean before = SoundStore.get().isDeferredLoading(); SoundStore.get().setDeferredLoading(false); if (in != null) { switch (type) { case OGG: target = SoundStore.get().getOgg(in); break; case WAV: target = SoundStore.get().getWAV(in); break; case MOD: target = SoundStore.get().getMOD(in); break; case AIF: target = SoundStore.get().getAIF(in); break; default: Log.error("Unrecognised sound type: "+type); break; } } else { switch (type) { case OGG: target = SoundStore.get().getOgg(ref); break; case WAV: target = SoundStore.get().getWAV(ref); break; case MOD: target = SoundStore.get().getMOD(ref); break; case AIF: target = SoundStore.get().getAIF(ref); break; default: Log.error("Unrecognised sound type: "+type); break; } } SoundStore.get().setDeferredLoading(before); }
b9250b98-7a9d-436b-bffd-9ce83c5ab3a8
7
public boolean pointVisibleTest(Point p){ boolean ret=false; if( angleBetween(this.forward,p.difference(this.location))<this.maxangl && distanceToPoint(p)>mindistance && distanceToPoint(p)<maxdistance) { double[] transform=this.cameraTransform(p); if( transform[0]<Main.WIDTH+100 && transform[0]>-100 && transform[1]>-Main.HEIGHT-100 && transform[1]<100){ ret=true; } } return ret; }
d985d9a2-943f-42de-8bfb-75a87a68a10a
0
public List findByEmail(Object email) { return findByProperty(EMAIL, email); }
089a64e1-65b4-4fae-9473-54364468bd17
3
public void sortByCost() { Collections.sort( images, new Comparator<Card>() { public int compare(Card a, Card b) { if (a instanceof Climax) { //climaxes should sort to be after all level cards if (b instanceof Climax) { return 0; } return 1; } if (b instanceof Climax) { return -1; } return Integer.compare(a.getCost(), b.getCost()); } }); }
a00a94e0-46dc-404b-be0c-a121e2c09553
5
public void Solve() { HashMap<String, HashSet<Integer>> results = Compute(new ArrayList<Integer>(), _maxDigits); String result = ""; int max = 0; for (Map.Entry<String, HashSet<Integer>> entry : results.entrySet()) { int number = 1; while (entry.getValue().contains(number)) { number++; } System.out.println(entry.getKey() + " - " + (number - 1)); if (max < number) { max = number; result = entry.getKey(); System.out.println(result + " - " + (max - 1) + " <--"); } else if (max == number) { System.out.println("Duplicate result: " + entry.getKey()); result = result.compareTo(entry.getKey()) < 0 ? result : entry.getKey(); } } System.out.println("Result=" + result); }
b33d5b3c-7a18-488c-952f-67caa612eb64
8
private static void addToMap(File file, HashMap<String, Holder> map) throws Exception { System.out.println(file.getAbsolutePath()); boolean human = file.getName().indexOf("Human") != -1; String[] splits = file.getName().split("_"); String fileName = splits[1] + "_" + splits[2]; Holder h = map.get(fileName); if( h == null) { h = new Holder(); map.put(fileName, h); } HashMap<String, Boolean> foundMap = human ? h.foundInHuman : h.foundInReference; if( foundMap.size() != 0) throw new Exception("Map not empty"); BufferedReader reader =new BufferedReader(new InputStreamReader( new GZIPInputStream( new FileInputStream( file)))); for(String s= reader.readLine(); s != null; s = reader.readLine()) { StringTokenizer sToken = new StringTokenizer(s); String firstToken = sToken.nextToken(); if( firstToken.length() != 1) throw new Exception("Unexpected " + firstToken); String seqName = new String( sToken.nextToken()); if( foundMap.containsKey(seqName)) throw new Exception("Duplicate sequence " + seqName); if( firstToken.equals("U")) foundMap.put(seqName, false); else if ( firstToken.equals("C")) foundMap.put(seqName, true); else throw new Exception("Unexpected first token " + s); } reader.close(); }
67930520-a887-41d3-a8da-b8a8ce15f1a0
8
private void showSong(Song song) { lblSongTitle.setText(song.getTitle()); if (!song.getArtists().isEmpty()) { String artists = "by "; for (int i = 0; i < song.getArtists().size(); i++) { if (i < song.getArtists().size() - 2) { artists += song.getArtists().get(i) + ", "; } else if (i < song.getArtists().size() - 1) { artists += song.getArtists().get(i) + " and "; } else { artists += song.getArtists().get(i) + "."; } } lblSongArtist.setText(artists); } else { lblSongArtist.setText("no artists uploaded"); } lblSongUser.setText("Uploaded by " + song.getUser().getUsername()); lblSongSpeed.setText("Speed: " + song.getSpeed().getName()); String lyrics = "<html>"; for(String line : song.getLyrics()){ lyrics += "<p>" + line + "</p>"; } lyrics += "</html>"; songLyricText.setContentType("text/html"); songLyricText.setText(lyrics); String chords = "<html>"; if(song.getChordSheets().size() == 0){ chords += "<br><br><br><center>No chords uploaded for this song.</center></html>"; } else { } songChordsText.setContentType("text/html"); songChordsText.setText(chords); JButton[] tagButtons = new JButton[song.getTags().size()]; for (int i = 0; i < song.getTags().size(); i++) { tagButtons[i] = new JButton(song.getTags().get(i).getName()); tagButtons[i].setBounds(0, 0, 10, 10); tagButtons[i].setFont(new Font("Lucida Grande", Font.PLAIN, 14)); tagsPanel.add(tagButtons[i]); tagsPanel.revalidate(); tagsPanel.repaint(); } JButton[] genreButtons = new JButton[song.getGenres().size()]; for (int i = 0; i < song.getGenres().size(); i++) { genreButtons[i] = new JButton(song.getGenres().get(i) .getName()); genreButtons[i].setBounds(0, 0, 10, 10); genreButtons[i].setFont(new Font("Lucida Grande", Font.PLAIN, 14)); genrePanel.add(genreButtons[i]); genrePanel.revalidate(); genrePanel.repaint(); } }
29834319-1257-4d7b-ab05-70448eec254b
0
public void print() { int y = 10; // local variable declaration System.out.println(x+""+y); }
e480b138-8a80-4326-99d0-03eb7e795527
3
public static List<String> getFolder(File dict) { List<String> files = new ArrayList<String>(); if (dict.listFiles().length > 0) for (File file : dict.listFiles()) { if (file.isDirectory()) { files.add(file.getName()); } } return files; }
f587267a-5f24-4d71-ab74-73e6f0e5e8d6
1
private void getCityCollection(AbstractDao dao, List<Direction> directions) throws DaoException { for (Direction dir : directions) { Criteria crit = new Criteria(); crit.addParam(DAO_ID_DIRECTION, dir.getIdDirection()); List<LinkDirectionCity> links = dao.findLinkDirectionCity(crit); dir.setCityCollection(getCityInfo(dao, links)); } }
40541ab3-ab84-4bf8-b8eb-2fc3d9b26483
0
public FactoryOfCapturingsForCpuForPiece(Position position, Player cpu, int largestCapture){ super(position,cpu,largestCapture); }
4c3e0b6d-2e67-479c-9932-f003d4f12fd2
4
private static double getMedianPixel(Image image, ChannelType color, int x, int y, int maskWidth, int maskHeight) { List<Double> pixelsAffected = new ArrayList<Double>(); for (int i = -maskWidth / 2; i <= maskWidth / 2; i++) { for (int j = -maskHeight / 2; j <= maskHeight / 2; j++) { if (image.validPixel(x + i, y + j)) { pixelsAffected.add(image.getPixel(x + i, y + j, color)); } } } Collections.sort(pixelsAffected, new Comparator<Double>() { public int compare(Double arg0, Double arg1) { return (int) (arg0 - arg1); } }); double val; int size = pixelsAffected.size(); if (size % 2 == 0) { val = ((double) (pixelsAffected.get(size / 2) + pixelsAffected .get(size / 2 + 1))) / 2; } else { val = pixelsAffected.get(size / 2); } return val; }
8bda3244-f2e2-46a8-b234-b1690b52bc5b
1
public final String getSHA(String s) { try { MessageDigest md5 = MessageDigest.getInstance("SHA"); md5.update(s.getBytes(), 0, s.length()); signature = new BigInteger(1, md5.digest()).toString(16); } catch(NoSuchAlgorithmException e) { e.printStackTrace(); } return signature; }
f31e76d9-764a-45e5-be1a-1bddbfb90a03
2
private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed String first = firstNameTextField.getText(); String last = lastNameTextField.getText(); String maristID = maristUsernameTextField.getText(); String pw1 = UserModel.encodePassword(new String(passwordTextField.getPassword())); String pw2 = UserModel.encodePassword(new String(confirmPasswordTextFIeld.getPassword())); if(pw1.equals(pw2)) { User user = new User(first, last, maristID, pw1); MongoHelper.save(user, "users"); user = (User) MongoHelper.fetch(user, "users"); if(UserModel.isValidUser(user)) { JOptionPane.showMessageDialog(this, "User created successfully!"); this.dispose(); } } else { JOptionPane.showMessageDialog(this, "You entered different passwords!"); } }//GEN-LAST:event_createButtonActionPerformed
5305e9cd-aa04-4367-8e66-21b9ab4c22ce
3
public String searchForCost(ArrayList<String[]> actualNode, String IPComing){ String returnValue = "0"; String[] tempStringArray = null; for(int i=0; i<actualNode.size(); i++){ tempStringArray = actualNode.get(i); if(tempStringArray[0].equals(IPComing) && tempStringArray[1].equals(IPComing)){ returnValue = tempStringArray[2]; return returnValue; } } return returnValue; }
669e86c8-cdea-4f39-b9fa-b0eeaa635b82
7
public void undo() { if (DEBUG) log("Attempting to undo TaskRemoval"); if (taskViewsToUpdate != null) { if (DEBUG) log("Get existing tasks from TaskCommander"); ArrayList<Task> tasks = TaskCommander.getTasks(); if (DEBUG) log("Add the task contained in this command to the existing tasks list"); tasks.add(task); if (DEBUG) log("Add the task to the taskViewToUpdate"); for (TaskView taskView : taskViewsToUpdate) { taskView.addTask(task); } } else { if (DEBUG) log("taskViewToUpdate is null, therefore the run command does nothing."); } }
0b6093d8-f28c-40bd-a6df-02ca8e45e21e
3
public boolean testCollisions( Tester t ) { LinkedList<Explosion> explosionList1 = new LinkedList( ); LinkedList<Explosion> explosionList2 = new LinkedList( ); LinkedList<Enemies> scaryList1 = new LinkedList( ); LinkedList<Enemies> scaryList2 = new LinkedList( ); LinkedList<Enemies> scaryList3 = new LinkedList( ); LinkedList<Enemies> scaryList4 = new LinkedList( ); LinkedList<Enemies> scaryList5 = new LinkedList( ); LinkedList<Enemies> scaryList6 = new LinkedList( ); LinkedList<Rocks> rockList1 = new LinkedList( ); LinkedList<Rocks> rockList2 = new LinkedList( ); explosionList1.add( new Explosion( 1, new Posn( 200, 200 ) ) ); explosionList2.add( new Explosion( 2, new Posn( 200, 200 ) ) ); scaryList1.add( new Baddy( new Posn( 210, 200 ), "images/leftbaddy.png", 3 ) ); scaryList2.add( new Baddy( new Posn( 210, 200 ), "images/leftbaddy.png", 3 ) ); scaryList3.add( new Baddy( new Posn( 210, 200 ), "images/rightbaddy.png", 1 ) ); scaryList4.add( new Baddy( new Posn( 210, 200 ), "images/upbaddy.png", 2 ) ); scaryList5.add( new Baddy( new Posn( 210, 200 ), "images/downbaddy.png", 0 ) ); rockList1.add( new DRock( new Posn( 200, 200 ) ) ); rockList2.add( new NDRock( new Posn( 200, 200 ) ) ); Hero hero1 = new Hero( new Posn( 150, 150 ) ); Hero hero2 = new Hero( new Posn( 150, 150 ), "images/downhero.png", false, 1 ); OverWorld world1 = new OverWorld( hero0, bombListEMPTY, explosionList1, rockListEMPTY, scaryList1 ); OverWorld world2 = new OverWorld( hero0, bombListEMPTY, explosionList2, rockListEMPTY, scaryListEMPTY, 2, 3, 3, 1 ); OverWorld world3 = new OverWorld( hero0, bombListEMPTY, explosionList1, rockList1, scaryListEMPTY ); OverWorld world4 = new OverWorld( hero0, bombListEMPTY, explosionList2, rockListEMPTY, scaryListEMPTY ); OverWorld world5 = new OverWorld( hero0, bombListEMPTY, explosionList1, rockList2, scaryListEMPTY ); OverWorld world6 = new OverWorld( hero0, bombListEMPTY, explosionList2, rockList2, scaryListEMPTY ); OverWorld world7 = new OverWorld( hero1, bombListEMPTY, explosionListEMPTY, rockListEMPTY, scaryList2 ); OverWorld world8 = new OverWorld( hero2, bombListEMPTY, explosionListEMPTY, rockListEMPTY, scaryList2, 2, 3, 2, 0 ); OverWorld world9 = new OverWorld( hero2, bombListEMPTY, explosionListEMPTY, rockListEMPTY, scaryList3, 2, 3, 2, 0 ); OverWorld world10 = new OverWorld( hero2, bombListEMPTY, explosionListEMPTY, rockListEMPTY, scaryList4, 2, 3, 2, 0 ); OverWorld world11 = new OverWorld( hero2, bombListEMPTY, explosionListEMPTY, rockListEMPTY, scaryList5, 2, 3, 2, 0 ); return // this also tests increasing spending points! t.checkExpect( world1.onTick( ), world2, "test removing enemies" + "\n") && t.checkExpect( world3.onTick( ), world4, "test removing destructable rocks" + "\n") && t.checkExpect( world5.onTick( ), world6, "test not removing non-destructable rocks" + "\n") && t.checkOneOf( "test enemy hitting hero" + "\n", world7.onTick( ), world8, world9, world10, world11); }
ab0f2530-aa3c-4a91-ba01-6b2cf603980e
4
private static void validatePassport(String passport) throws TechnicalException { if (passport == null || passport.isEmpty() || passport.length() > PASSPORT_SIZE) { throw new TechnicalException(PASSPORT_ERROR_MSG); } String regex = "[A-Z]{2}\\d{7}"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(passport); if (! m.matches()) { throw new TechnicalException(PASSPORT_ERROR_MSG); } }
031204f3-5c0a-4f60-8570-7b12f5f42e9b
2
private static boolean haveItem(String string) { for(ItemLabel item : stack){ if(item.item.name.equals(string)) return true; } return false; }
1789d127-9c98-47f1-9573-826773985dd4
6
public String[] getBorderColors() { try { String[] clrs = new String[5]; if( borderElements.get( "top" ) != null ) { clrs[0] = borderElements.get( "top" ).getBorderColor(); } if( borderElements.get( "left" ) != null ) { clrs[1] = borderElements.get( "left" ).getBorderColor(); } if( borderElements.get( "bottom" ) != null ) { clrs[2] = borderElements.get( "bottom" ).getBorderColor(); } if( borderElements.get( "right" ) != null ) { clrs[3] = borderElements.get( "right" ).getBorderColor(); } if( borderElements.get( "diagonal" ) != null ) { clrs[4] = borderElements.get( "diagonal" ).getBorderColor(); } return clrs; } catch( NullPointerException e ) { return new String[5]; } }
021c629e-dbbc-43c1-a740-8ae1544de78d
1
public void visitIincInsn(final int var, final int increment) { buf.setLength(0); buf.append(tab2) .append("IINC ") .append(var) .append(' ') .append(increment) .append('\n'); text.add(buf.toString()); if (mv != null) { mv.visitIincInsn(var, increment); } }
268d8661-6e1b-4c79-8e48-3ff0669ebc81
4
private void pelaajanAmmustenOsumatunnistusKokonaisuus(Iterator it, Kuti kuti, int kutiX, int kutiY) { while (it.hasNext()) { ufo = (Ufo) it.next(); int ufox = ufo.getX(); int ufoy = ufo.getY(); if (ufo.isVisible() && kuti.isVisible()) { if (ufonOsumaTunnistus(kutiX, ufox, kutiY, ufoy)) { ufoTuhoutuuOsumasta(ufo, kuti); } } } }
61d5d69b-612e-4553-8914-e260dd819bab
2
private RequestData getRequestData(HttpServletRequest request){ RequestData rd = new RequestData(); rd.page = request.getParameter("page"); if (request.getParameter("id") == null){ rd.id = Long.valueOf(0); } else{ try{ rd.id = Long.valueOf(request.getParameter("id")); } catch (NumberFormatException e){ rd.id = Long.valueOf(0); } } rd.action = request.getParameter("action"); return rd; }
92c37c39-398b-49b7-a3c5-6db6790ee1e6
5
public void initialize() throws ResourceInitializationException { // extract configuration parameter settings String oPath = (String) getUimaContext().getConfigParameterValue("outputFile"); // Output file should be specified in the descriptor if (oPath == null) { throw new ResourceInitializationException( ResourceInitializationException.CONFIG_SETTING_ABSENT, new Object[] { "outputFile" }); } // If specified output directory does not exist, try to create it outFile = new File(oPath.trim()); if (outFile.getParentFile() != null && !outFile.getParentFile().exists()) { if (!outFile.getParentFile().mkdirs()) throw new ResourceInitializationException( ResourceInitializationException.RESOURCE_DATA_NOT_VALID, new Object[] { oPath, "outputFile" }); } try { fileWriter = new FileWriter(outFile); } catch (IOException e) { throw new ResourceInitializationException(e); } }
0c9210db-235b-474d-b3cf-d9df9f5e0f1b
7
public void promptMove(GoEngine g){ int bestValue=Integer.MIN_VALUE; List<Coord> bestMoves = new ArrayList<Coord>(); Board testBoard = new Board(); int alpha=Integer.MIN_VALUE; int beta=Integer.MAX_VALUE; for(int r=0;r<9;r++){ for(int c=0;c<9;c++){ g.board.calculateTerritory(); if(g.board.checkValid(r, c, piece)&&g.board.getTerritory(r, c)!=piece){ testBoard.CopyBoard(g.board); testBoard.placePiece(r, c, piece); int testValue = minimax(testBoard,maxDepth-1,1,alpha,beta); //System.out.println(testValue); if(testValue>bestValue){ bestMoves.clear(); bestMoves.add(new Coord(r,c)); bestValue=testValue; }else if(testValue==bestValue){ bestMoves.add(new Coord(r,c)); } } } } if(bestMoves.size()>0){ Coord move = bestMoves.get(rand.nextInt(bestMoves.size())); g.board.placePiece(move.row, move.col, piece); }else{ g.board.passTurn(); } }
2bb1bfa6-946d-4890-8d57-e229a2650937
6
private void drawWest(Terrain[][] currentBoard, Entities[][] currentObjects, Graphics g) { //This is the opposite of east, so easy to figure out when you figure out east :) Location playerDir = boardState.getPlayerCoords(); for (int i = 0; i < currentBoard.length; i++) { for (int j = 0; j < currentBoard[0].length; j++) { double x = ((j + 5 - playerDir.y) * 0.5 * width / 10) - ((i - currentBoard.length + 6 + playerDir.x) * 0.5 * width / 10) + (10 / 1.75) * (int) width / 13; double y = ((j + 5 - playerDir.y) * 0.5 * height / (15)) + ((i - currentBoard.length + 6 + playerDir.x) * 0.5 * height / (15)) + (10 / 3) * (int) height / 21; if (currentBoard[currentBoard.length - 1 - i][j] != null) g.drawImage( currentBoard[currentBoard.length - 1 - i][j].img, (int) x, (int) y, (int) width / 10, (int) height / 15, null); else { System.out.println("Error!"); } } } for (int i = 0; i < currentBoard.length; i++) { for (int j = 0; j < currentBoard[0].length; j++) { if (currentObjects[currentObjects.length - 1 - i][j] != null) { double x = ((j + 5 - playerDir.y) * 0.5 * width / 10) - ((i - currentBoard.length + 6 + playerDir.x) * 0.5 * width / 10) + (10 / 1.75) * (int) width / 13 - (currentObjects[currentObjects.length - 1 - i][j].imgs[3].getWidth(null) * (width / startingWidth) - width/10)/2; double y = ((j + 5 - playerDir.y) * 0.5 * height / 15) + ((i - currentBoard.length + 6 + playerDir.x) * 0.5 * height / 15) + (10 / 3) * (int) height / 21 + (0.75 * height / 15) - (currentObjects[currentObjects.length - 1 - i][j].imgs[3].getHeight(null) * (height / startingHeight)); g.drawImage( currentObjects[currentObjects.length - 1 - i][j].imgs[3], (int) x, (int) y, (int) (currentObjects[currentObjects.length - 1 - i][j].imgs[3] .getWidth(null) * (width / startingWidth)), (int) (currentObjects[currentObjects.length - 1 - i][j].imgs[3] .getHeight(null) * (height / startingHeight)), null); } } } }
a095aa26-3f77-49c9-9940-a0a5d7d6d913
4
public void move(){ // Is this enemy one of the inital 3 switch(priority){ case 1: case 2: case 3:{ initialEnemyMove(); break; } case 4:{ attackingMove(); break; } } }
27db49bd-4a16-42b3-a751-991be9a23142
5
public static void unJar(File jarFile, File toDir) throws IOException { JarFile jar = new JarFile(jarFile); try { Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); if (!entry.isDirectory()) { InputStream in = jar.getInputStream(entry); try { File file = new File(toDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { jar.close(); } }
a28ed1f8-d9ef-4744-a783-c8956344162c
4
public boolean isCorrectPassword(Account a) { Account tempAccount = null; for (int i = 0; i < al.accountList.length; i++) { if (al.accountList[i].getiban().equals(a.getiban()) && al.accountList[i].getOwner().equals(a.getOwner())) { tempAccount = al.accountList[i]; } } if (tempAccount.getPassword().equals(a.getPassword())) { return true; } System.out.println("Your password is error!!"); return false; }
9eb0fea5-944b-408c-a9e3-33ae831ff6ee
2
public Tile(byte[] buf) { t = (char) Utils.ub(buf[0]); id = Utils.ub(buf[1]); w = Utils.uint16d(buf, 2); try { img = ImageIO.read(new ByteArrayInputStream(buf, 4, buf.length - 4)); } catch (IOException e) { throw (new LoadException(e, Resource.this)); } if (img == null) throw (new LoadException("Invalid image data in " + name, Resource.this)); }
8a748c54-3c1d-4bb5-99ff-0cf3e4667915
4
public void sendAddUser() throws IOException{ String str = new String("adduser"+ "," + hostFld.getText()+ ","+ jobFld.getText() + "," + pwdFld.getText()); System.out.println(str); InetAddress serverAddr= null; try { serverAddr= InetAddress.getByName(GlobalV.serverIP); } catch (UnknownHostException e1) { e1.printStackTrace(); } Socket socket = null; try { System.out.println("sending adduser to server"); socket = new Socket(serverAddr, GlobalV.sendingPortLogin); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println(str); System.out.print("adduser sent"); socket.close(); }
6536b138-2ef8-452e-8739-b9a02e9d4402
5
public int clearRows() { // piece has NOT been placed // if committed is already false, then we've // backed up already. WE only need to clear rows. if (committed) { saveBackup(); committed = false; } int rowsCleared = 0; // make array of rows that are filled, falsify such rows boolean[] filledRows = new boolean[height]; for (int y = 0; y < maxHeight; y++) { if (isFilled(y)) { filledRows[y] = true; falsifyRow(y); rowsCleared += 1; } } for (int i = filledRows.length - 1; i >= 0; i--) { if (filledRows[i]) { shiftRowsDown(i); } } lowerHeights(rowsCleared); sanityCheck(); return rowsCleared; }
5df41e77-5ae9-4725-b1cb-44bf5f8c1ad6
6
public static Boolean isSlotMachinePart(Block b) { Set<String> keys = null; try { keys = Global.config().getConfigurationSection("machines").getKeys(false); } catch(Exception e) { return false; } for(String k : keys) { SlotMachine s = new SlotMachine(k); if(s.getFirstItemFrame().equals(b.getLocation())) return true; if(s.getSecondItemFrame().equals(b.getLocation())) return true; if(s.getThirdItemFrame().equals(b.getLocation())) return true; if(s.getLever().equals(b.getLocation())) return true; } return false; }
eaf1d13d-983c-475e-bca0-6819691f3a63
1
@Override public void loadMemory(Data[] programCode) { for (Data line : programCode) { MEMORY[pointer] = line; //Load pointer location with line of program code pointer++; } fireUpdate(display()); }
3a67a785-fd92-4848-aeb3-af0ff5b06c17
1
public boolean isCheckedIcon(String name) { Component comp = fetchComponent(null, name); if (comp instanceof JRadioButton) { JRadioButton radioButt = (JRadioButton) comp; return radioButt.isSelected(); } return false; }
d56042e9-e871-4bbd-995f-e24a1ddf00f4
3
public void onAction(String sender, String login, String hostname, String target, String action) { if (target.equalsIgnoreCase(DarkIRC.currentChan.name)) { GUIMain.add_line("*" + sender + " " + action); } else { for (int i = 0; i < DarkIRC.channelsList.size(); i++) { // System.out.println(DarkIRC.channelsList.get(i).name + " = " // + target); if (DarkIRC.channelsList.get(i).name.equalsIgnoreCase(target)) { Logs.makeLog(DarkIRC.channelsList.get(i) + ".log", Logs.readLog(DarkIRC.channelsList.get(i) + ".log") + "*" + sender + " " + action + "\n"); GUIMain.jTabbedPane2.setForegroundAt(i, Color.RED); // GUIMain.jTabbedPane2.setIconAt(i, new // ImageIcon(this.getClass().getResource("Black-Internet-icon.png"))); } } } }
00b6322a-fc14-496b-9f5c-48142556e1ae
0
public Color getColor() { return color; }
da0c7237-7722-4934-a8bc-0fea8cbc68e1
9
protected void launch(AppDesc appDesc) throws LaunchException { //create new appcontext if required if(appDesc.useNewAppContext()) { try { Class cls = Class.forName("sun.awt.SunToolkit"); //Method m = cls.getMethod("createNewAppContext", new Class[]{}); //m.invoke(null, new Object[]{}); Reflection r = Reflection.getToolKit(); r.callStatic(cls, "createNewAppContext"); } catch(Throwable exp) { //We can ignore this logger.log(Level.WARNING, "Error setting new App Context: "+exp.getMessage(), exp); } } try { //first process the AppDescURL document if it has one appDesc.processAppDescURL(); AppClassLoader loader = appDesc.getNewAppClassLoader(null); //Print out URLS for debugging if(logger.isLoggable(Level.INFO)) { StringBuffer urlText = new StringBuffer(); urlText.append("ClassPath for App:"+appDesc.getName()+"\n"); urlText.append(loader.getClassPathString()); logger.info(urlText.toString()); } //Set the Context Class Loader for this Thread Thread.currentThread().setContextClassLoader(loader); //Set ClassLoader for UI Defaults. This is in case the App wants to change its Look and Feel if(appDesc.useNewAppContext()) { javax.swing.UIManager.getDefaults().put("ClassLoader", loader); } AppInstance appInstance = new AppInstance(loader); String mainClassName = appDesc.getMainClass(); //Try and get the mainclass from the jar manifest if(mainClassName == null || mainClassName.equals("")) { mainClassName = loader.getMainClassFromJars(); } //Don't have a Main class throw an Exception if(mainClassName == null) { throw new LaunchException("no main class specified"); } //execute the main method of the application Class mainCls = loader.loadClass(mainClassName); Method mainM = mainCls.getMethod("main", new Class[]{String[].class}); logger.info("Calling " + mainClassName); String args[] = appDesc.getMainArgs(); if(args == null) args = new String[0]; mainM.invoke(null, new Object[]{args}); } catch(Exception exp) { exp.printStackTrace(); throw new LaunchException(exp); } }
7a046ad9-9c1a-4ef1-90b6-87120bdeb3b2
4
@Override public void mouseDragged(MouseEvent e) { Point dragged = e.getLocationOnScreen(); int dragX = getDragDistance(dragged.x, pressed.x, snapSize.width); int dragY = getDragDistance(dragged.y, pressed.y, snapSize.height); int locationX = location.x + dragX; int locationY = location.y + dragY; // Mouse dragged events are not generated for every pixel the mouse // is moved. Adjust the location to make sure we are still on a // snap value. while (locationX < edgeInsets.left) { locationX += snapSize.width; } while (locationY < edgeInsets.top) { locationY += snapSize.height; } Dimension d = getBoundingSize(destination); while (locationX + destination.getSize().width + edgeInsets.right > d.width) { locationX -= snapSize.width; } while (locationY + destination.getSize().height + edgeInsets.bottom > d.height) { locationY -= snapSize.height; } // Adjustments are finished, move the component destination.setLocation(locationX, locationY); }
055ea1ea-ecc7-49ae-9257-a80bec180fef
0
@Override public void selectionChanged(TreeSelectionEvent e) { calculateEnabledState(e.getTree()); }
b0863187-9499-49d1-869d-562a579a3c58
6
public static NumberWrapper minusComputation(NumberWrapper x, NumberWrapper y) { { double floatresult = Stella.NULL_FLOAT; { Surrogate testValue000 = Stella_Object.safePrimaryType(x); if (Surrogate.subtypeOfIntegerP(testValue000)) { { IntegerWrapper x000 = ((IntegerWrapper)(x)); { Surrogate testValue001 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue001)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); return (IntegerWrapper.wrapInteger(((int)(x000.wrapperValue - y000.wrapperValue)))); } } else if (Surrogate.subtypeOfFloatP(testValue001)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue - y000.wrapperValue; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue001 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } } } else if (Surrogate.subtypeOfFloatP(testValue000)) { { FloatWrapper x000 = ((FloatWrapper)(x)); { Surrogate testValue002 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue002)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); floatresult = x000.wrapperValue - y000.wrapperValue; } } else if (Surrogate.subtypeOfFloatP(testValue002)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue - y000.wrapperValue; } } else { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); stream001.nativeStream.print("`" + testValue002 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace())); } } } } } else { { OutputStringStream stream002 = OutputStringStream.newOutputStringStream(); stream002.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream002.theStringReader()).fillInStackTrace())); } } } return (FloatWrapper.wrapFloat(floatresult)); } }
dd64664e-a1b6-4f30-bab9-a9efffe4ab1b
8
public static boolean writeUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle("Select File for Output"); File selectedFile; while (true) { int option = fileDialog.showSaveDialog(null); if (option != JFileChooser.APPROVE_OPTION) return false; // user canceled selectedFile = fileDialog.getSelectedFile(); if (selectedFile.exists()) { int response = JOptionPane.showConfirmDialog(null, "The file \"" + selectedFile.getName() + "\" already exists. Do you want to replace it?", "Replace existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) break; } else { break; } } PrintWriter newout; try { newout = new PrintWriter(new FileWriter(selectedFile)); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + selectedFile.getName() + "\" for output.\n" + "(Error :" + e + ")"); } if (!writingStandardOutput) { try { out.close(); } catch (Exception e) { } } out = newout; writingStandardOutput = false; outputFileName = selectedFile.getName(); outputErrorCount = 0; return true; }
5796c6cf-0cfd-44b4-910f-948a7b3322c3
0
@Override public Object getPropertyDefault(String key) { return default_values.get(key); }
c01b2794-f52c-4862-be30-3b9635ac94a6
4
public PDFFontEncoding(String fontType, PDFObject encoding) throws IOException { if (encoding.getType() == PDFObject.NAME) { // if the encoding is a String, it is the name of an encoding // or the name of a CMap, depending on the type of the font if (fontType.equals("Type0")) { type = TYPE_CMAP; cmap = PDFCMap.getCMap(encoding.getStringValue()); } else { type = TYPE_ENCODING; differences = new HashMap<Character,String>(); baseEncoding = this.getBaseEncoding(encoding.getStringValue()); } } else { // loook at the "Type" entry of the encoding to determine the type String typeStr = encoding.getDictRef("Type").getStringValue(); if (typeStr.equals("Encoding")) { // it is an encoding type = TYPE_ENCODING; parseEncoding(encoding); } else if (typeStr.equals("CMap")) { // it is a CMap type = TYPE_CMAP; cmap = PDFCMap.getCMap(encoding); } else { throw new IllegalArgumentException("Uknown encoding type: " + type); } } }
ae1bfdc6-3f1d-4f9d-8bc4-fd81575ab6fb
0
public void setR(float r) { this.r = r; }
3b45fb39-ac36-452a-b380-317d64e54b3e
3
public ArrayList returnTree() { if(isEmpty()) return null; ArrayList<Node<Word>> list1 = levelOrderTraversal(root); ArrayList<Word> list2 = new ArrayList<Word>(); for(int i=0;i < list1.size();i++) { if(list1.get(i) != null) { list2.add(list1.get(i).data()); } else { list2.add(null); } } return list2; }
3fb026da-3341-4d93-b178-3dc0485798cd
6
void resetColorsAndFonts () { super.resetColorsAndFonts (); Color oldColor = itemForegroundColor; itemForegroundColor = null; setItemForeground (); if (oldColor != null) oldColor.dispose(); oldColor = itemBackgroundColor; itemBackgroundColor = null; setItemBackground (); if (oldColor != null) oldColor.dispose(); Font oldFont = font; itemFont = null; setItemFont (); if (oldFont != null) oldFont.dispose(); oldColor = cellForegroundColor; cellForegroundColor = null; setCellForeground (); if (oldColor != null) oldColor.dispose(); oldColor = cellBackgroundColor; cellBackgroundColor = null; setCellBackground (); if (oldColor != null) oldColor.dispose(); oldFont = font; cellFont = null; setCellFont (); if (oldFont != null) oldFont.dispose(); }
8bbb8fa4-b83d-481a-a484-f66e21c611ef
9
public static void main(String[] args) throws Throwable{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); for(StringTokenizer st;(st=new StringTokenizer(in.readLine()))!=null;){ M=parseInt(st.nextToken());L=parseInt(st.nextToken()); if(M==0&&L==0)break; int N=parseInt(in.readLine().trim()); st=new StringTokenizer(in.readLine()); arr=new int[N];sum=new int[N]; for(int i=0,s=0;i<N;i++)sum[i]=(s+=(arr[i]=parseInt(st.nextToken()))); mem=new int[N][M+1]; if(function(0, 0)){ ArrayList<Integer> res=new ArrayList<Integer>(); for(int i=0,j=0;i<N;j+=mem[i][j]==1?arr[i]:0,i++)if(mem[i][j]==1)res.add(i+1); sb.append(res.size()+" "); for(int n:res)sb.append(n+" "); sb.append("\n"); } else sb.append("Impossible to distribute\n"); } System.out.print(new String(sb)); }
bd1121e5-a598-4840-971b-fc74c7bec23d
0
public OutputStream getOutputStream() { return os; }
1d89fd1c-fd5d-4c47-93f5-8f36de7c738e
0
public Distance add(Distance second) { double sum = number + second.number; return new Distance(sum, unit); }
7a4e5269-7342-4725-89bf-634ae2042a92
7
public static int discrete(double[] a) { double EPSILON = 1E-14; double sum = 0.0; for (int i = 0; i < a.length; i++) { if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]); sum = sum + a[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries not equal to one: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniform(); sum = 0.0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; if (sum > r) return i; } } }
1437a54e-e81d-4c68-b7a2-1c18992f60a6
3
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setText(value.toString()); setBackground(isSelected ? list.getSelectionBackground() : list.getBackground()); setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); setFont(list.getFont()); setBorder((cellHasFocus) ? UIManager.getBorder("List.focusCellHighlightBorder") : m_noFocusBorder); return this; }
9387690f-f703-4782-b892-f92aa9651e2a
5
public void checkCredentials (String userName, String passWord) { HttpConnector request = new HttpConnector(); try { stream = request.authenticate(userName, passWord); try { JSONObject json = new JSONObject(stream.toString()); valid = (Boolean) json.get("valid"); if(valid == true){ AppFiles files = new AppFiles(); files.setJSONList(json); } } catch (JSONException jse) { System.out.println("Exception: " + jse); } } catch (IOException ioe) { System.out.println(ioe); } if (valid){ /** * User is valid, gechecked via json * Nu moet de user een folderpath hebben */ frame.setMessage("Inlog gelukt"); this.user.setUsername(userName); setProperty("username", userName); String path = this.user.getFolderpath(); if (null == path){ this.fileChooser = new FileDestinationChooser(); this.fileChooser.setInstanceController(this); frame.clearFileBoxContent(); frame.setFileBoxContent(fileChooser); } else { // lijst met bestanden opvragen loadFolder(); } } }
8ed7fbb0-dd37-4c77-a1e1-8d2b176325bf
2
@Override public void run() { if (validArgs) { zip(); } else { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
81cc8872-fa0c-4912-9b8c-5bd9b4353c18
4
public Map<?, ?> getMap() throws IOException { return (Map<?, ?>)getValue(); }
64fc5f91-5d99-4382-9afa-c54dff31d072
5
public static void main(String[] args) { // args[0] = Number of times to complete - default 10 try { n = Integer.parseInt(args[0]); } catch (Exception e) { n = 10; } // Set up fractal FractalColourScheme scheme = FractalColourScheme.DEFAULT; BaseFractalAlgorithm algorithm = new MandelbrotAlgorithm(100, 2); FractalPanel fractal = new FractalPanel(algorithm); fractal.setColourScheme(scheme); fractal.setSize(width, height); Complex test1 = new Complex(-1.995, 1.55925); Complex test2 = new Complex(-0.931647, -0.66725521); Complex test3 = new Complex(0.151654, 0.313412); // int tileX = 50, tileY = FractalPanel.Renderer.MAX_TILE_AREA / 50; // Get classes Class<Complex> cClass = Complex.class; Class<BaseFractalAlgorithm> faClass = BaseFractalAlgorithm.class; Class<FractalPanel> fpClass = FractalPanel.class; Class<FractalColourScheme> fcsClass = FractalColourScheme.class; // Set up results double[] complexAdd = new double[n]; double[] complexSquare = new double[n]; double[] complexMod = new double[n]; double[] coordinateConversion = new double[n]; double[] algorithmTime = new double[n]; double[] colourMapping = new double[n]; double[] pixelRender = new double[n]; double[] tileRender = new double[n]; double[] totalRender = new double[n]; // Loop through n tests for (int i = 0; i < n; i++) { try { // Complex addition complexAdd[i] = getTime(cClass.getMethod("add", cClass), test2, test3); // Complex squaring complexSquare[i] = getTime(cClass.getMethod("square"), test2); // Complex modulus complexMod[i] = getTime(cClass.getMethod("modulusSquared"), test2); // Arbitrary coordinate conversion coordinateConversion[i] = getTime(fpClass.getMethod("getCartesian", int.class, int.class), fractal, width / 3, height / 3); // Fully diverging complex number algorithmTime[i] = getTime(faClass.getMethod("divergenceRatio", cClass), algorithm, test1); // Diverging complex number algorithmTime[i] += getTime(faClass.getMethod("divergenceRatio", cClass), algorithm, test2); // Non-diverging complex number algorithmTime[i] += getTime(faClass.getMethod("divergenceRatio", cClass), algorithm, test3); // Average algorithmTime[i] /= 3; // Fully diverging colour colourMapping[i] = getTime(fcsClass.getMethod("calculateColour", double.class), scheme, 0.0); // Diverging colour colourMapping[i] += getTime(fcsClass.getMethod("calculateColour", double.class), scheme, 0.667); // Non-diverging colour colourMapping[i] += getTime(fcsClass.getMethod("calculateColour", double.class), scheme, 1.0); // Average colourMapping[i] /= 3; // Fully diverging pixel pixelRender[i] = getTime(fpClass.getMethod("getPixelColour", int.class, int.class), fractal, width, height); // Diverging pixel pixelRender[i] = getTime(fpClass.getMethod("getPixelColour", int.class, int.class), fractal, width / 3, (2 * height) / 5); // Non-diverging pixel pixelRender[i] = getTime(fpClass.getMethod("getPixelColour", int.class, int.class), fractal, width / 2, height / 2); // Average pixelRender[i] /= 3; // Total rendering totalRender[i] = getTime(fpClass.getMethod("repaint"), fractal); } catch (InvocationTargetException ex) { // Abandon this test if it fails // If the exception is in the program, print it out Throwable ex2 = ex.getTargetException(); System.err.println("Test " + i + " failed: " + ex2.getMessage()); ex2.printStackTrace(); n--; } catch (Exception ex) { // Abandon this test if it fails System.err.println("Test " + i + " failed: " + ex.getMessage()); ex.printStackTrace(); n--; } } // Headers String output = "Complex Add,Complex Square,Complex Mod,Coordinate Conversion,Algorithm Time,Colour Mapping,Pixel Render,Total Render\n"; // Sort test results Arrays.sort(complexAdd); Arrays.sort(complexSquare); Arrays.sort(complexMod); Arrays.sort(coordinateConversion); Arrays.sort(algorithmTime); Arrays.sort(colourMapping); Arrays.sort(pixelRender); Arrays.sort(tileRender); Arrays.sort(totalRender); // Take median of tests and print output += complexAdd[n / 2] + ","; output += complexSquare[n / 2] + ","; output += complexMod[n / 2] + ","; output += coordinateConversion[n / 2] + ","; output += algorithmTime[n / 2] + ","; output += colourMapping[n / 2] + ","; output += pixelRender[n / 2] + ","; output += totalRender[n / 2]; try { // Write to file BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write(output); writer.close(); System.out.println("Results written to " + filename); } catch (IOException ex) { System.err.println("Could not write to file, displaying instead:"); System.out.println(output); } }
aad49abd-bdcd-43b7-bbf7-4d1c81de8032
1
public void run() { for (int i = 1; i <= ConcurrentHashMapDemo.NUMBER; i++) { map.get(key); } synchronized (lock) { counter--; } }
d171fc6d-3d07-479b-8bb6-da73b77cf689
2
public boolean isElement() { if(miniCompounds.length == 1 && miniCompounds[0].isElement()) return true; return false; }
2da150bd-050c-4b0e-947f-c1fbf85544f7
0
@Test public void testDeleteByKey() { fail("Not yet implemented"); }
f1db56d6-3f1f-455a-808c-46b53b921c22
2
public void receive() { try { MulticastSocket socket = new MulticastSocket(DPORT); socket.joinGroup(InetAddress.getByName(ADDRESS)); byte[] buf = new byte[SIZE]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); Object o = toObject(packet.getData()); if (o instanceof Message) { Message m = (Message) o; System.out.println( "Receiver received: " + m.geContent() + " from " + m.geName()); } socket.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } }
089ecda6-5533-4bc2-a504-9c66cbd550d9
7
private boolean checkParameters(int high, int width, int minesNumber) { if (high < 9 || high > 24) return false; if (width < 9 || width > 30) return false; if (minesNumber < 10 || minesNumber >= high * width || minesNumber > 668) return false; return true; }
746f1f95-1d99-4aa4-80b2-1cbb6a609013
1
public int getNumberOfTeamPlayers(String teamName, String matchName){ try { cs = con.prepareCall("{ call GET_TEAM_PLAYERCOUNT(?,?,?) }"); cs.setString(1, teamName); cs.setString(2, matchName); cs.registerOutParameter(3, Types.INTEGER); cs.executeQuery(); //System.out.println("number of players in team: " + cs.getInt(3)); return cs.getInt(3); } catch (SQLException e) { e.printStackTrace(); } return 0; }
212928c6-8597-441e-a75d-420ed4fba5ab
3
public static boolean isNullOrEmpty(final String s){ boolean isEmpty = false; if(s == null){ isEmpty = true; } if(!isEmpty){ if(s.toCharArray().length == 0){ isEmpty = true; } } return isEmpty; }
8a864419-6816-4dc1-8abf-0c79d130b724
3
public void shotFired(){ try { file = new FileInputStream("sound/cannonshot.wav"); } catch (FileNotFoundException ex) { System.out.println("file not found apparently"); Logger.getLogger(Sounds.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { System.out.println("io exception in sound"); } try { sound = new AudioStream(file); // My sound file had like, a 1 second delay, which sounded bad // So these skips skip right up until the beginning of the fire // Also, it's necessary to have all 4, a single 380,000 won't work sound.skip(100000); sound.skip(100000); sound.skip(100000); sound.skip(80000); } catch (IOException ex) { Logger.getLogger(Sounds.class.getName()).log(Level.SEVERE, null, ex); } AudioPlayer.player.start(sound); }// end shotFired()
1bb8c73e-bafa-4562-b50e-4d096282df1a
9
@Override public void actionPerformed(ActionEvent emain) { Object links = emain.getSource(); if(links==quitapp){ quitApp(); } else if(links==newmember) { boolean b=openChildWIndow("Add New Record"); if(b==false){ newmember numember= new newmember(conne); screen.add(numember); numember.setVisible(true); } } else if(links==delmember){ boolean b=openChildWIndow("Delete Member"); if(b==false){ try { loaddel(); } catch (SQLException ex) { Logger.getLogger(kpa_home.class.getName()).log(Level.SEVERE, null, ex); } } } else if (links==configu){ JFrame parent = (JFrame) getParent(); JDialog Edit = new status_choice( parent,conne); Edit.show(); } else if(links == enquire){ boolean b=openChildWIndow("Add New Record"); if(b==false){ newmember numember= new newmember(conne); screen.add(numember); numember.setVisible(true); } } }
bba1e441-cd3b-4ee2-bc08-4c9c99858bba
9
public void close() { for(Map.Entry<ObjectName, Set<ObjectNameAwareListener>> entry: registeredNotificationListeners.entrySet()) { for(ObjectNameAwareListener listener: entry.getValue()) { try { removeNotificationListener(listener.getObjectName(), listener); } catch (Exception e) {} } entry.getValue().clear(); } registeredNotificationListeners.clear(); if(remoteClassLoader!=null) { try { mbeanServerConnection.unregisterMBean(remoteClassLoader.getObjectName()); remoteClassLoader=null; } catch (Exception e) {} } if(remotedMBeanServer!=null) { try { mbeanServerConnection.unregisterMBean(remotedMBeanServer.getObjectName()); remotedMBeanServer=null; } catch (Exception e) {} } if(connector!=null) { try { connector.close(); } catch (Exception e) {} connected.set(false); } }
df3bc92a-ee7f-4c76-85e1-1390c46c5ae7
9
public static HTTPResponse doHTTPRequest(HTTPRequest request) throws Exception{ HTTPResponse response = new HTTPResponse(); try{ HttpURLConnection conn; URL url = new URL(request.getURL()); // Open connection if (url.getProtocol().equalsIgnoreCase("https")){ conn = (HttpsURLConnection)url.openConnection(); } else{ conn = (HttpURLConnection)url.openConnection(); } // Set request method conn.setRequestMethod(request.getMethod().toString()); // Set request parameters conn.setDoOutput(request.getBody()!=null); conn.setUseCaches(false); conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(true); // Set request timeouts conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); // Set HTTP Accept header if (request.getAccept()!=null){ conn.setRequestProperty("Accept", request.getAccept()); } // Set request content type if (request.getContentType()!=null){ conn.setRequestProperty("Content-Type", request.getContentType()); } // Add Basic HTTP Authentication if (request.getUsername()!=null && request.getPassword()!=null){ Base64 enc = new Base64(-1); String encAuth = enc.encodeToString((request.getUsername()+":"+request.getPassword()).getBytes("UTF-8")); conn.setRequestProperty("Authorization", "Basic "+encAuth); } // Add request body if (request.getBody()!=null){ OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(),"UTF-8"); osw.write(request.getBody()); osw.close(); } // Connect conn.connect(); response.setResponseCode(conn.getResponseCode()); response.setContentType(conn.getHeaderField("Content-Type")); // Read response InputStream in; if (response.getResponseCode() >= 400){in = conn.getErrorStream();} else{in = conn.getInputStream();} ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int n; while ((n=in.read(buffer))!=-1){ bout.write(buffer, 0, n); } bout.close(); // Set response body response.setBody(bout.toByteArray()); // Disconnect conn.disconnect(); } catch(Exception e){ throw e; } return response; }
2b7db79b-4d43-4c90-9b81-2c260b7cc2c6
2
private void debugMode(String s, boolean ln) { if (debug) { if (ln) { System.out.println(s); } else { System.out.print(s); } } }
430aaa40-6b6c-4347-9b90-5c53652bf0e4
4
public void measure(long time) { updateMessages(); if (list.size() > 0) { double defdist = 1.0 / list.size(); Message prevMessage = null; for (Message message : list) { message.defDist = defdist; message.prevM = prevMessage; if (prevMessage != null) prevMessage.nextM = message; prevMessage = message; } prevMessage.nextM = null; for (Message message : list) { message.measure(time); } } }
ccf84111-580e-40dd-befb-126b33b0f0de
4
public void act(){ if (clicked){ if (counter >= 10){ counter = 0; clicked = false; } else{ counter++; hoverCounter = 0; this.setImage (bg[2]); } } else if (selected){ selected = false; this.setImage (bg[1]); if (hoverCounter >= 50){ map.hm.setData (this); int[] co = setCo(); map.addObject (map.hm, co[0], co[1]); } } else{ this.setImage (bg[0]); } }
8e866cd4-e67e-46ba-8bf0-13ae0c255c91
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GUIView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUIView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUIView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUIView.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 GUIView().setVisible(true); } }); }
c63f7513-2423-4455-90d6-a448ffc3adcc
3
public Selector duplicate(Object selectionObject, Class<?> selectionClass) throws SQLException { try { Constructor<? extends Selector> constr = getClass().getConstructor(Object.class,Class.class,boolean.class); return constr.newInstance(selectionObject,selectionClass,this.isStrictInheritance()); } catch (Exception e) { throw new SQLException(e); } }
80a98985-7b73-4802-aa02-04667bd4099a
9
private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); }
675c0aa3-6d48-4386-9093-4cd889542fea
0
public VertexSet copy(){ VertexSet tmp = new VertexSet(); tmp.addVertexSet(this); return tmp; }
633179e5-e42a-4161-8860-ae85d22dc48e
1
public boolean collide(Actor player) { if(loc.contains(player.getBox().getCenterX(), player.getBox().getCenterY())) { return true; } return false; }
6acd3a55-e16f-487d-8bcf-eee0056f5853
8
public void gridletPause(int gridletId, int userId, boolean ack) { boolean status = false; // Find in EXEC List first int found = gridletInExecList_.indexOf(gridletId, userId); if (found >= 0) { // updates all the Gridlets first before pausing updateGridletProcessing(); // Removes the Gridlet from the execution list ResGridlet rgl = (ResGridlet) gridletInExecList_.remove(found); // if a Gridlet is finished upon cancelling, then set it to success // instead. if (rgl.getRemainingGridletLength() == 0.0) { found = -1; // meaning not found in Queue List gridletFinish(rgl, Gridlet.SUCCESS); System.out.println(super.get_name() + ".gridletPause(): Cannot pause" + " Gridlet #" + gridletId + " for User #" + userId + " since it has FINISHED."); } else { status = true; rgl.setGridletStatus(Gridlet.PAUSED); // change the status gridletPausedList_.add(rgl); // add into the paused list // Set the PE on which Gridlet finished to FREE super.resource_.setStatusPE( PE.FREE, rgl.getMachineID(), rgl.getPEID() ); // empty slot is available, hence process a new Gridlet allocateQueueGridlet(); } } else { // Find in QUEUE list found = gridletQueueList_.indexOf(gridletId, userId); } // if found in the Queue List if (status == false && found >= 0) { status = true; // removes the Gridlet from the Queue list ResGridlet rgl = (ResGridlet) gridletQueueList_.remove(found); rgl.setGridletStatus(Gridlet.PAUSED); // change the status gridletPausedList_.add(rgl); // add into the paused list } else { // Find in the AR Waiting List found = gridletWaitingList_.indexOf(gridletId, userId); } // if found in the AR waiting list if (status == false && found >= 0) { status = true; // removes the Gridlet from the waiting list ResGridlet rgl = (ResGridlet) gridletWaitingList_.remove(found); rgl.setGridletStatus(Gridlet.PAUSED); // change the status gridletPausedList_.add(rgl); // add into the paused list } // if not found anywhere in both exec and paused lists else if (found == -1) { System.out.println(super.get_name() + ".gridletPause(): Error - cannot " + "find Gridlet #" + gridletId + " for User #" + userId); } // sends back an ack if required if (ack == true) { super.sendAck(GridSimTags.GRIDLET_PAUSE_ACK, status, gridletId, userId); } }
3fa4d955-92dd-48d0-82e6-6c1f015aed3d
0
protected void catchException(Object object, Exception exception) { fireServerExceptionEvent(new ExceptionEvent(object, exception)); }
b50d74a7-41f8-412a-bd36-5c772390f33b
3
public void add(String letter) { boolean found = false; Probability proTemp = null; for (Probability pro : probs) { if (pro.afterLetter == letter) { found = true; proTemp = pro; } } if (found) { proTemp.incProb(); } else { probs.add(new Probability(letter)); } }
40d3be1d-f3ba-4e10-8b8b-e4e6bcc61bcc
1
public void testFactory_standardHoursIn_RPeriod() { assertEquals(0, Hours.standardHoursIn((ReadablePeriod) null).getHours()); assertEquals(0, Hours.standardHoursIn(Period.ZERO).getHours()); assertEquals(1, Hours.standardHoursIn(new Period(0, 0, 0, 0, 1, 0, 0, 0)).getHours()); assertEquals(123, Hours.standardHoursIn(Period.hours(123)).getHours()); assertEquals(-987, Hours.standardHoursIn(Period.hours(-987)).getHours()); assertEquals(1, Hours.standardHoursIn(Period.minutes(119)).getHours()); assertEquals(2, Hours.standardHoursIn(Period.minutes(120)).getHours()); assertEquals(2, Hours.standardHoursIn(Period.minutes(121)).getHours()); assertEquals(48, Hours.standardHoursIn(Period.days(2)).getHours()); try { Hours.standardHoursIn(Period.months(1)); fail(); } catch (IllegalArgumentException ex) { // expeceted } }
785baa55-f08f-4a4e-afd5-d0286333c449
4
public TextureRegion getRegion(int i, int j) { if(i < 0 || j < 0 || i >= regions.length || j >= regions.length) throw new ArrayIndexOutOfBoundsException(); return regions[i][j]; }
7289ab60-d74a-4d0b-9f4d-ad55d0b530c8
8
public List<Tuple<Integer,Integer>> aStar ( Tuple<Integer,Integer> start, Tuple<Integer,Integer> goal) { this.callsToAStar++; log.debug("A* is looking for a path from " + start + " to " + goal); // Set closedSet = empty set HashSet<Tuple<Integer,Integer>> closedSet = new HashSet<Tuple<Integer,Integer>>(); // The set of tentative nodes to be evaluated HashSet<Tuple<Integer,Integer>> openSet = new HashSet<Tuple<Integer,Integer>>(); // initially containing the start node openSet.add(start); // The map of navigated nodes. // Initially set to empty map HashMap<Tuple<Integer,Integer>,Tuple<Integer,Integer>> cameFrom = new HashMap<Tuple<Integer,Integer>,Tuple<Integer,Integer>>(); HashMap<Tuple<Integer,Integer>,Integer> g_score = new HashMap<Tuple<Integer,Integer>,Integer>(); g_score.put(start,0); // Cost from start along best known path. // Estimated total cost from start to goal through y. HashMap<Tuple<Integer,Integer>,Integer> f_score = new HashMap<Tuple<Integer,Integer>,Integer>(); f_score.put(start, g_score.get(start) + heuristicCostEstimate(start, goal)); while ( !openSet.isEmpty() ) { // current := the node in openset having the lowest f_score[] value int lowestF = Integer.MAX_VALUE; Tuple<Integer,Integer> current = null; for ( Tuple<Integer,Integer> node : openSet ) { if ( f_score.get(node) < lowestF ) { lowestF = f_score.get(node); current = node; } } if ( current.equals(goal) ) { //List<Tuple<Integer,Integer>> path = reconstructPath(cameFrom, goal); /* for ( Tuple<Integer,Integer> point : path ) { //log.debug(point + " is valid: " + this.validBoard[point.x][point.y]); } */ return reconstructPath(cameFrom, goal); } //remove current from openset openSet.remove(current); //add current to closedset closedSet.add(current); HashSet<Tuple<Integer,Integer>> neighbor_nodes = getNeighborNodes(current); // log.trace("Neighboring nodes: " + neighbor_nodes.size()); // for each neighbor in neighbor_nodes(current) for ( Tuple<Integer,Integer> neighbor : neighbor_nodes ) { // if neighbor in closedset if ( closedSet.contains(neighbor) ) continue; int tentative_g_score = g_score.get(current) + 1; // log.trace("Open set size:" + openSet.size()); if ( !openSet.contains(neighbor) || tentative_g_score < g_score.get(neighbor) ) { // add neighbor to openset // log.trace("adding a neighbor to openSet with tentative_g_score" + tentative_g_score); openSet.add(neighbor); cameFrom.put(neighbor, current); g_score.put(neighbor, tentative_g_score); f_score.put(neighbor, g_score.get(neighbor) + heuristicCostEstimate(neighbor, goal)); } } } // Failure log.error("A* is returning null! This should never happen!"); return null; }
21b8a538-f71c-4dd1-9d24-f1fa2ba47d98
6
public synchronized void playbackLastMacro() { if (currentMacro!=null) { Action[] actions = getActions(); int numActions = actions.length; List macroRecords = currentMacro.getMacroRecords(); int num = macroRecords.size(); if (num>0) { undoManager.beginInternalAtomicEdit(); try { for (int i=0; i<num; i++) { MacroRecord record = (MacroRecord)macroRecords.get(i); for (int j=0; j<numActions; j++) { if ((actions[j] instanceof RecordableTextAction) && record.id.equals( ((RecordableTextAction)actions[j]).getMacroID())) { actions[j].actionPerformed( new ActionEvent(this, ActionEvent.ACTION_PERFORMED, record.actionCommand)); break; } } } } finally { undoManager.endInternalAtomicEdit(); } } } }
33f390e9-f59d-424f-b0ec-a1e2701bce38
5
@Override public void onWake() { System.out.println("\n" + agent.getLocalName() + " is done waiting for offers, " + "picking best offer for " + item.getName()); Map<AID, Integer> offers = agent.pullOffers(item); if (offers.size() == 0){ System.out.println("We've received " + offers.size() + " offers."); }else{ Set<AID> sellers = offers.keySet(); int lowestPrice = 1000000000; AID bestSeller = null; for(AID seller: sellers){ if(offers.get(seller) < lowestPrice){ lowestPrice = offers.get(seller); bestSeller = seller; } } //Cancel other transactions ACLMessage cancelOrders = new ACLMessage(ACLMessage.CANCEL); cancelOrders.setContent(item.getName()); for(AID seller: sellers){ if(!seller.equals(bestSeller)){ cancelOrders.addReceiver(seller); } } agent.send(cancelOrders); System.out.println(bestSeller.getLocalName() + " had the best offer, and we accept it.\n"); myAgent.addBehaviour(new BuyItemBehaviour(myAgent, bestSeller, item, lowestPrice)); } agent.addBehaviour(new AskForItemBehaviour(agent, 100)); }
26d3fa1f-4cbb-4943-82f8-6f36f77063ba
1
protected void readScaleFactorSelection() { for (int i = 0; i < num_subbands; ++i) ((SubbandLayer2)subbands[i]).read_scalefactor_selection(stream, crc); }
b49e396f-fec7-4404-a61d-3765f2ea324e
4
public void hit(int damage) { if (dead || flinching) return; health -= damage; sfx.get("enemyhit").play(); if (health < 0) health = 0; if (health == 0) { LevelCompletedState.eDead++; LevelCompletedState.score++; dead = true; } flinching = true; flinchTimer = System.nanoTime(); }
efbdd76d-3def-4c9d-834d-23dc807b6808
7
public void removeValue(Comparable rowKey, Comparable columnKey) { setValue(null, rowKey, columnKey); // 1. check whether the row is now empty. boolean allNull = true; int rowIndex = getRowIndex(rowKey); DefaultKeyedValues row = (DefaultKeyedValues) this.rows.get(rowIndex); for (int item = 0, itemCount = row.getItemCount(); item < itemCount; item++) { if (row.getValue(item) != null) { allNull = false; break; } } if (allNull) { this.rowKeys.remove(rowIndex); this.rows.remove(rowIndex); } // 2. check whether the column is now empty. allNull = true; int columnIndex = getColumnIndex(columnKey); for (int item = 0, itemCount = this.rows.size(); item < itemCount; item++) { row = (DefaultKeyedValues) this.rows.get(item); if (row.getValue(columnIndex) != null) { allNull = false; break; } } if (allNull) { for (int item = 0, itemCount = this.rows.size(); item < itemCount; item++) { row = (DefaultKeyedValues) this.rows.get(item); row.removeValue(columnIndex); } this.columnKeys.remove(columnIndex); } }