method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
3e906fc4-ecd2-45b7-8617-2e00497ff329
5
private static void write(final InputStream in, final OutputStream out) { try { final byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } catch (final Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final Exception e) { e.printStackTrace(); } } }
e351882c-be1b-4667-8479-0e09c92d4da8
9
public void start() { if( !requestNewMatch() ) { return; } String gameStatusFromLastLoop = ""; // actual game loop while(true) { //get game status String lastGameStatusAnswerString = requestMatchStatus(); if( lastGameStatusAnswerString.equals(gameStatusFromLastLoop)) { System.out.print("."); continue; } System.out.print("\n"); gameStatusFromLastLoop = lastGameStatusAnswerString; // get game status int[] grid = createGrid(lastGameStatusAnswerString); AITools.visualizeGrid(grid); if( isErrorAnswer(lastGameStatusAnswerString) ) { return; } if( isDrawGame(lastGameStatusAnswerString) ) { return; } int winNumber = isGameWon(lastGameStatusAnswerString); if( winNumber != 0 ) { if( winNumber == _playerNumber ) { System.out.println("I've won!"); } else { System.out.println(_opponentName + " has won..."); } return; } if( !isItMyTurn(lastGameStatusAnswerString) ) { //wait a sec, then try again try { Thread.sleep(AITools.SLEEP_MILLIS); } catch (InterruptedException e) { e.printStackTrace(); } continue; } //so it's my turn String action = _profile.getNextAction(grid, _playerNumber); // send next action System.out.println("sending action: " + action); postAction(action); // continue in loop gameStatusFromLastLoop = ""; } }
045e01a0-2ca9-4cce-a902-d895d68b6344
7
public void loop() throws IOException { acceptor = new ServerSocket(PORT); service = new GLSRequestHandler(this); while (true) { System.out.println ("Waiting for connections on port " + PORT); //This waits for an incomming message socket = acceptor.accept(); JInPiqi.request req = read_message(); JOutPiqi.response response = null; GLI inst = new GLIExample(service); if (req.hasInit()) { response = inst.init(req.getInit().getUseridListList()); } else if (req.hasHandleAction()) { JInPiqi.handle_action a = req.getHandleAction(); response = inst.handle_action(a.getUserid(), a.getCommandName(), a.getCommandArgsList(), a.getState()); } else if (req.hasHandleUserJoin()) { JInPiqi.handle_user_join j = req.getHandleUserJoin(); response = inst.handle_user_join(j.getUserid(), j.getState()); } else if (req.hasHandleUserLeave()) { JInPiqi.handle_user_leave j = req.getHandleUserLeave(); response = inst.handle_user_leave(j.getUserid(), j.getState()); } else if (req.hasHandleTimer()) { JInPiqi.handle_timer j = req.getHandleTimer(); response = inst.handle_timer(j.getId(), j.getDelta(), j.getState()); } else if (req.hasHandleTimerComplete()) { JInPiqi.handle_timer_complete j = req.getHandleTimerComplete(); response = inst.handle_timer_complete(j.getId(), j.getDelta(), j.getState()); } else { System.out.println("Unknown command " + req); } write_message(response); socket.getOutputStream().close(); socket.close(); } }
4fdf9911-2ed7-495e-8b81-64b51838e3bb
8
protected void rapproche(Cellule cible){ if(!this.curent.personne.isEmpty()){ this.curent.personne.remove(this); } if (Math.abs(this.curent.coord.x -cible.coord.x) >= Math.abs(this.curent.coord.y - cible.coord.y)) { if (this.curent.coord.x != cible.coord.x){ if (this.curent.coord.x> cible.coord.x){ this.curent = this.curent.env.getCellule(this.curent.coord.x-1, this.curent.coord.y); } else if (this.curent.coord.x< cible.coord.x) this.curent = this.curent.env.getCellule(this.curent.coord.x+1, this.curent.coord.y); } } else if (this.curent.coord.y != cible.coord.y){ if (this.curent.coord.y> cible.coord.y){ this.curent = this.curent.env.getCellule(this.curent.coord.x, this.curent.coord.y-1); } else if (this.curent.coord.y< cible.coord.y){ this.curent = this.curent.env.getCellule(this.curent.coord.x, this.curent.coord.y+1);} } this.coord = curent.coord; this.curent.personne.add(this); }
d5eacfa6-a74d-4cfe-8db4-e8ce73b9d800
2
public String shortName() { if (isIntegral()) { return "" + Type.INTEGER_CHAR; } // Use R rather than L for readability. if (isReference()) { return "R"; } Assert.isTrue(desc.length() == 1, "Short name too long: " + desc); return desc; }
1710f903-dfaf-43e8-82e9-75138864a815
0
public int getStatus() { return Status; }
663f7bc5-86c5-4e59-95b8-f06ae9d4913b
9
public void update() { // Moves character or scrolls background accordingly 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; } rectBody.setRect(centerX - 34, centerY - 63 , 68, 63); rectLegs.setRect(rectBody.getX(), rectBody.getY() + 63, 68, 64); rectLeft.setRect(rectBody.getX() - 26, rectBody.getY()+32, 26, 20); rectRight.setRect(rectBody.getX() + 68, rectBody.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); }
47d461e0-dbb2-4f48-9770-65c463205f38
1
@Override public double observe() { double observed = 0; for (int i = 0; i < k; i++) { observed += borel.observe(); } return observed; }
548812b9-bc5c-47b5-8b6f-9f197ea0bb78
6
private int ssCompare (final int p1, final int p2, final int depth) { final int[] SA = this.SA; final byte[] T = this.T; final int U1n, U2n; // pointers within T int U1, U2; for ( U1 = depth + SA[p1], U2 = depth + SA[p2], U1n = SA[p1 + 1] + 2, U2n = SA[p2 + 1] + 2; (U1 < U1n) && (U2 < U2n) && (T[U1] == T[U2]); ++U1, ++U2 ); return U1 < U1n ? (U2 < U2n ? (T[U1] & 0xff) - (T[U2] & 0xff) : 1) : (U2 < U2n ? -1 : 0); }
b57ddcdf-9779-4915-96fe-9ff48ba97ad4
9
private void Process_IsEmpty(List<Production> productions){ // First step is to select symbols that are on the left side of the epsilon production // as empty symbols. for (int i = 0; i < productions.size(); ++i){ if (productions.get(i).mRightSymbolsIndices.get(0) == Utilities.ProductionEpsilonCode) mSymbolsEx.get(productions.get(i).mLeftNonTerminalSymbolIndex).mIsEmpty = true; } // Now we do the same for the symbols that are on the left side of a productions that has // all empty symbols on the right side. Boolean goAgain = true; while (goAgain){ goAgain = false; for (int i = 0; i < productions.size(); ++i){ Boolean allEmptyOnTheRightSide = true; for (int j = 0; j < productions.get(i).mRightSymbolsIndices.size(); ++j){ if (productions.get(i).mRightSymbolsIndices.get(j) != Utilities.ProductionEpsilonCode && mSymbolsEx.get(productions.get(i).mRightSymbolsIndices.get(j)).mIsEmpty == false){ allEmptyOnTheRightSide = false; break; } } if (allEmptyOnTheRightSide && mSymbolsEx.get(productions.get(i).mLeftNonTerminalSymbolIndex).mIsEmpty == false){ goAgain = true; mSymbolsEx.get(productions.get(i).mLeftNonTerminalSymbolIndex).mIsEmpty = true; } } } }
639a8a73-73f0-4e5e-825a-66094512e945
9
public void switchMediaLibraryToMappedDrives() { if (mediaDir != null) { for (int i = 0; i < mediaDir.length; i++) { UNCFile file = new UNCFile(mediaDir[i]); if (file.onNetworkDrive()) { mediaDir[i] = file.getDrivePath(); } } } if (mediaLibraryDirectoryList != null) { for (int i = 0; i < mediaLibraryDirectoryList.length; i++) { UNCFile file = new UNCFile(mediaLibraryDirectoryList[i]); if (file.onNetworkDrive()) { mediaLibraryDirectoryList[i] = file.getDrivePath(); } } } if (mediaLibraryFileList != null) { for (int i = 0; i < mediaLibraryFileList.length; i++) { UNCFile file = new UNCFile(mediaLibraryFileList[i]); if (file.onNetworkDrive()) { mediaLibraryFileList[i] = file.getDrivePath(); } } } }
bcd824da-cf29-4dfb-a8da-61cdfd34df88
9
public void addGold() { int randNum; for(int i=0;;i++) { randNum=random.nextInt(totalBoardSize); if(randNum>(boardSize*2) && isCorrectPit(randNum) && isCorrectGold(randNum)) break; } findNeighbour(randNum); for(WumpusWorldVO w:wwList) { if(w.getBoardNo()==randNum) w.setGold(true); } for(WumpusWorldVO w:wwList) { for(int i=0;i<4;i++) { if(neighbours[i]==w.getBoardNo()) w.setGlitter(true); } } }
e00e8aa6-dae3-41b2-851f-b993db9e9897
7
public void testCheckedPoolKeyedObjectPool() throws Exception { try { PoolUtils.checkedPool((KeyedObjectPool<Object, Object>)null, Object.class); fail("PoolUtils.checkedPool(KeyedObjectPool, Class) must not allow a null pool."); } catch(IllegalArgumentException iae) { // expected } try { PoolUtils.checkedPool((KeyedObjectPool<?, ?>)createProxy(KeyedObjectPool.class, (List<String>)null), null); fail("PoolUtils.checkedPool(KeyedObjectPool, Class) must not allow a null type."); } catch(IllegalArgumentException iae) { // expected } final List<String> calledMethods = new ArrayList<String>(); @SuppressWarnings("unchecked") KeyedObjectPool<Object, Object> op = createProxy(KeyedObjectPool.class, calledMethods); KeyedObjectPool<Object, Object> cop = PoolUtils.checkedPool(op, Object.class); final List<String> expectedMethods = invokeEveryMethod(cop); assertEquals(expectedMethods, calledMethods); op = new BaseKeyedObjectPool<Object, Object>() { @Override public Integer borrowObject(Object key) { return new Integer(0); } @Override public void returnObject(Object key, Object obj) {} @Override public void invalidateObject(Object key, Object obj) {} }; @SuppressWarnings("rawtypes") final KeyedObjectPool rawPool = op; @SuppressWarnings("unchecked") KeyedObjectPool<Object, Object> cop2 = PoolUtils.checkedPool(rawPool, String.class); try { cop2.borrowObject(null); fail("borrowObject should have failed as Integer !instanceof String."); } catch (ClassCastException cce) { // expected } try { cop2.returnObject(null, new Integer(1)); fail("returnObject should have failed as Integer !instanceof String."); } catch (ClassCastException cce) { // expected } try { cop2.invalidateObject(null, new Integer(2)); fail("invalidateObject should have failed as Integer !instanceof String."); } catch (ClassCastException cce) { // expected } }
3e1f108a-0d3b-4db9-9449-6157be17b480
3
public void DFS(int[] num){ //index is how many numbers do not add the list if(list.size() == length){ result.add(new ArrayList<Integer>(list)); return; } for(int i=0; i< length ;i++){ if(flag[i]) continue; list.add(num[i]); flag[i] = true; DFS(num); list.remove(list.size() -1); // rall back flag[i] = false; } }
13682147-628f-4606-b5d5-85c1cc4e0c4d
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { Physical target=mob; if((auto)&&(givenTarget!=null)) target=givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(mob,target,null,L("<T-NAME> <T-IS-ARE> already affected by @x1.",name())); 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> become(s) divinely favored."):L("^S<S-NAME> @x1 for divine favor.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> @x1, but there's no answer.",prayWord(mob))); // return whether it worked return success; }
9753b85e-4a24-4c73-a8ab-aa2a346b1f6a
1
public void setCurrentProfile(String username) { LOGGER.log(Level.INFO, "Setting current profile to: " + username); if (!profiles.containsKey(username)) { System.out.println("Tried to set current profile to one that doesn't exist."); return; } currentProfile = profiles.get(username); }
44d3d29c-cd5c-479d-8d60-aa181477857e
8
public static HashMap<String, String> readTokens() { final HashMap<String, String> result = new HashMap<>(); try { final Scanner input = new Scanner( new File("/etc/firedog/tokens.cf")); try { while (input.hasNextLine()) { final String line = input.nextLine().trim(); if (line.isEmpty()) continue; final char c = line.charAt(0); if (c == '#' || c == ':' || c == ';' || c == '-') continue; final String[] split = line.split("=", 2); if (split.length < 2) continue; result.put(split[0], split[1]); } return result; } finally { input.close(); } } catch (FileNotFoundException e) { return result; } }
7b178353-a680-4fd7-8e8e-e42b333313f1
1
public boolean ModificarTipoCultivo(TipoCultivo p){ if (p!=null) { cx.Modificar(p); return true; }else { return false; } }
888203c0-9a9c-4a3a-babc-e2602345a00f
0
public int GetMinimumPassenger() { return minimumPassenger; }
3372d23e-8d61-4d77-8cf3-9514d9574031
7
private JAutoPanel window_login() { JAutoPanel frame = new JAutoPanel(this.desktop); JLabel eMafiaText = new JLabel("eMafia"); JLabel usernameText = new JLabel("Username:"); JTextField usernameField = new JTextField(15); usernameField.setName("username"); JLabel passwordText = new JLabel("Password:"); JPasswordField passwordField = new JPasswordField(15); passwordField.setName("password"); JButton loginBut = new JButton("Login"); Action loginAction = new AbstractAction("Login") { private static final long serialVersionUID = 1L; @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { String username = null; Component[] theList = ((Component) e.getSource()).getParent() .getComponents(); for (Component comp : theList) { if (comp instanceof JTextField && comp.getName().equals("username")) { ((JTextField) comp).setEditable(false); username = ((JTextField) comp).getText(); } if (comp instanceof JPasswordField && comp.getName().equals("password")) { ((JPasswordField) comp).setEditable(false); Framework.Telnet.var1 = ((JPasswordField) comp) .getText(); } if (comp instanceof JButton) { if (((JButton) comp).getText().equals("Login")) {// can't // use // getName // without // errors.. ((JButton) comp).setEnabled(false); } } } Framework.Telnet.write(username); } }; passwordField.setAction(loginAction); loginBut.setAction(loginAction); JButton registerBut = new JButton("Register"); registerBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Framework.Telnet.write("new"); } }); // registerBut.setEnabled(false);//Disabled until there is a // registartion JPanel loginFieldsPanel = new JPanel(); GroupLayout loginFieldsLayout = new GroupLayout(loginFieldsPanel); loginFieldsPanel.setLayout(loginFieldsLayout); loginFieldsLayout.setAutoCreateGaps(true); loginFieldsLayout.setAutoCreateContainerGaps(true); loginFieldsLayout.setHorizontalGroup(loginFieldsLayout .createSequentialGroup() .addComponent(eMafiaText) .addGroup( loginFieldsLayout .createParallelGroup( GroupLayout.Alignment.LEADING) .addComponent(usernameText) .addComponent(passwordText) .addComponent(loginBut)) .addGroup( loginFieldsLayout .createParallelGroup( GroupLayout.Alignment.LEADING) .addComponent(usernameField) .addComponent(passwordField) .addComponent(registerBut))); loginFieldsLayout.setVerticalGroup(loginFieldsLayout .createSequentialGroup() .addComponent(eMafiaText) .addGroup( loginFieldsLayout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent(usernameText) .addComponent(usernameField)) .addGroup( loginFieldsLayout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent(passwordText) .addComponent(passwordField)) .addGroup( loginFieldsLayout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent(loginBut) .addComponent(registerBut))); frame.add(loginFieldsPanel); frame.setSize(frame.getPreferredSize()); frame.setAutoCenter(); return frame; }
aeff80e2-1964-4e34-a04a-e3178788d41c
6
@Override public double regress(double[] x) { for(int i = 0; i < x.length; i++){ this.input.get(i).input(x[i]); } //Propagate stuff for(Neuron n : this.input) n.propagate(); for(List<Neuron> list : this.hidden){ for(Neuron n : list) n.propagate(); } for(Neuron n : this.output) n.propagate(); double[] r = new double[this.output.size()]; for(int i = 0; i < r.length; i++){ r[i] = this.output.get(i).getLatestOutput(); } return r[0]; }
54c79a12-bfc1-41a5-b67b-9edfe457feff
1
public void changeZoom() { for(int i=0;i<markers;i++) { marker[i].changeZoom(); } }
a449bb5a-03f7-4e2f-8962-efc7e7b26a9a
1
private void getApps() throws IOException { List<String> listOfApps = device.getPackageController().getPackages(); DefaultListModel model = new DefaultListModel(); for (String str : listOfApps) { String[] arr = str.split(":"); model.addElement(arr[1]); } jList1.setModel(model); }
94a3ca0d-1f01-4304-9dd2-b1ea6055ab05
7
public int compareSeniorities(Instructor instructor, Course course) { //Never give up our first assigned course if(courses.size() == 1 && CourseAssignment.round != 1) return 1; //If we're getting a third before they get a second if( (courses.size() + 1 - instructor.getCourses().size()) >= 2 ) { return -1; } //If they're getting a third before we're get a second if(instructor.getCourses().size() + 1 - courses.size() >= 2) { return 1; } String workArea = course.getWorkArea(); int thisSeniority = (seniorities.get(workArea) == null) ? 0 : seniorities.get(workArea); int thatSeniority = (instructor.getSeniorities().get(workArea) == null) ? 0 : instructor.getSeniorities().get(workArea); int seniorityComparison = thatSeniority - thisSeniority; if (seniorityComparison != 0) { return seniorityComparison; } else { int dateComparison = instructor.getTAF().getDateOfSubmission().compareTo(taf.getDateOfSubmission()); return dateComparison; } }
2b791c98-7d71-47f2-a734-abe0fc18fe5a
2
public boolean connectedTo(WayOsm way){ boolean encontrado = false; for (int x = 0; !encontrado && x < this.nodos.size(); x++) encontrado = way.getNodes().contains(this.nodos.get(x)); return encontrado; }
5672443e-d30c-4904-926c-0e2dcd96e6d9
5
public void getInput() { String userCommand; Scanner inFile = new Scanner(System.in); do { this.display(); // display the menu // get commaned entered userCommand = inFile.nextLine(); userCommand = userCommand.trim().toUpperCase(); switch (userCommand) { case "O": this.helpMenuControl.displayGameObjective(); break; case "1": this.helpMenuControl.displayOnePlayerHelp(); break; case "2": this.helpMenuControl.displayTwoPlayerHelp(); break; case "Q": break; default: new MemoryGameError().displayError("Invalid command. Please enter a valid command."); continue; } } while (!userCommand.equals("Q")); return; }
ee9084b2-8efb-4bc7-b8e1-c803d2f79101
8
public void playSound(byte inputSound)//From my 2nd year project ^_^ { if(sound) { try { stream = null; switch(inputSound) { case(START): stream = AudioSystem.getAudioInputStream(sound_Start); break; case(KILLED): stream = AudioSystem.getAudioInputStream(sound_Killed); break; case(ALIVE): stream = AudioSystem.getAudioInputStream(sound_Alive); break; case(SHOOT): stream = AudioSystem.getAudioInputStream(sound_Shoot); break; case(ATROHIT): stream = AudioSystem.getAudioInputStream(sound_AtroHit); break; } // Open a data line to play our type of sampled audio. // Use SourceDataLine for play and TargetDataLine for record. DataLine.Info info = null; info = new DataLine.Info(Clip.class, stream.getFormat()); Clip clip = (Clip) AudioSystem.getLine(info); clip.open(stream); clip.start(); } catch (IOException e1) { setSound(false); System.out.println("Sound file not found"); System.out.println(e1.toString()); } catch (Exception e)// Throws IOException or UnsupportedAudioFileException { setSound(false); System.out.println("Sound System"); System.out.println(e.toString()); } } }
4ef658f9-b08c-4303-898c-b9633212ee8d
4
@Override public boolean isVisibleAt(int posX, int posY) { if((posX/zoom) > originX && (posX/zoom) < (originX + getWidth())) if((posY/zoom) > originY && (posY/zoom) < (originY + getHeight())) return true; return false; }
a25c71f5-9304-4ca0-abdd-c8f05f7ec325
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Organisation)) { return false; } Organisation other = (Organisation) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
30ea49b4-ae15-41f0-a419-29b189ba59b7
9
public static float waitTime(int[] arriveTimes, int[] executeTimes, int q) { if (arriveTimes == null || executeTimes == null || arriveTimes.length != executeTimes.length) return 0; Queue<Process> queue = new LinkedList<Process>(); int curTime = 0, waitTime = 0; int index = 0; int length = arriveTimes.length; while (!queue.isEmpty() || index < length) { if (!queue.isEmpty()) { Process cur = queue.poll(); waitTime += curTime - cur.arrivalTime; curTime += Math.min(cur.executeTime, q); for (; index < length && arriveTimes[index] <= curTime; index++) queue.offer(new Process(arriveTimes[index], executeTimes[index])); if (cur.executeTime > q) queue.offer(new Process(curTime, cur.executeTime - q)); } else { queue.offer(new Process(arriveTimes[index], executeTimes[index])); curTime = arriveTimes[index++]; } } return (float) waitTime / length; }
4e7bd53f-75cc-4cc0-a7b8-68b4d843dfd1
0
private void initialize() { final int INSET = 50; dimWindow = Toolkit.getDefaultToolkit().getScreenSize(); Dimension minDimWindows = new Dimension(300,300); new JDesktopPane(); setResizable(true); setBounds(INSET, INSET, dimWindow.width - INSET*2, dimWindow.height - INSET*2); this.setMinimumSize(minDimWindows); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setLayout(new BorderLayout()); ImageIcon icon = new ImageIcon(Main.ICO_PATH + "chart_stock.png"); this.setIconImage(icon.getImage()); listDataOut = new ListDataOut(); initMenuBar(); initButtonBar(); initUpperBars(); initStatusBar(); // dataBase = new FileDataBase(); initTreeView(); /*dataArrays = new ArraysDataBase();*/ initTable(); initPopupMenu(); addWindowFocusListener(new WindowAdapter() { /** * Invoked when the Window is set to be the focused Window, which means * that the Window, or one of its subcomponents, will receive keyboard * events. * * @since 1.4 */ @Override public void windowGainedFocus(WindowEvent e) { super.windowGainedFocus(e); setDataBase(); setUpArraysColumn(mainTable.getColumnModel().getColumn(4)); mainTable.updateUI(); } }); }
d4b33296-380f-49d5-96a5-7f5b3be62136
2
private int buscarCliente(String host) { int numero = -1; for (int i = 0; i < clientes.size(); i++) { if (clientes.get(i).getHost().equals(host)) { numero = i; } } return numero; }
1c9b3dad-32f0-4dc2-9afe-475362e1e65e
8
private void handleWhoisResponse(int code, String response) { String[] parts = response.split(" ", 3); String nickname = parts[1]; response = parts[2]; PrivateMessagingListener listener = getPrivateMessagingListener(nickname); if (listener == null) { if (serverEventsListener == null) { return; } else { serverEventsListener.privateMessageWithoutListenerReceived( nickname, "[zaslány údaje o uživateli]"); listener = getPrivateMessagingListener(nickname); } } if (code == RPL_WHOISCHANNELS) { response = response.substring(1); } else if (code == RPL_WHOISIDLE) { response = response.substring(0, response.indexOf(" ") ); } switch (code) { case RPL_WHOISUSER: listener.whoisUser(response); break; case RPL_WHOISSERVER: listener.whoisServer(response); break; case RPL_WHOISIDLE: listener.whoisIdle(response); break; case RPL_WHOISCHANNELS: listener.whoisChannels(response); break; } }
439c5000-5728-48a6-9dc0-62f66159e61b
0
public SchlangenGlied getPreviousGlied() { return previousGlied; }
5b50a5f0-4e86-4646-a753-0a9ac9e7088d
6
public XYSeries[] getAggegatedSeries() { final XYSeriesCollection seriesCollection = new XYSeriesCollection(); for (int types = 0; types < 255; types++) { if ((exists(types)) && (!hidden.contains(Integer.toString(types)))) { // LOGGER.debug("class conatins : " + hidden.contains(Integer.toString(types)) + " type " + Integer.toString(types)); final XYSeries series = new XYSeries("Mes. " + types); for (int i = 0; i < duration; i++) { if (countUntil(types, i) > 0) { series.add(i, countUntil(types, i)); } } seriesCollection.addSeries(series); } } XYSeries[] series = new XYSeries[seriesCollection.getSeriesCount()]; for (int i = 0; i < seriesCollection.getSeriesCount(); i++) { series[i] = seriesCollection.getSeries(i); } return series; }
08091bcf-9382-458b-8814-a3e9ce663d10
4
public void doLoopAction() { switch (whatcha) { case PLAYING: stage.doLoopAction(); break; case PAUSE: pauzeMenu.doLoopAction(); break; case MAIN: mainMenu.doLoopAction(); break; case SELECTSTAGE: stageSelector.doLoopAction(); break; } }
5ecfd594-2629-4274-bd44-b6897f72aefd
8
private void refreshMonLocsAtRisk() { TreeMap<Integer,Integer> atRiskLocs = new TreeMap<Integer,Integer>(); Iterator<Integer> atRiskPeople = this.mySim.getAtRiskPeople().iterator(); Iterator<Integer> implocs = this.trackLocations.keySet().iterator(); while (implocs.hasNext()) { atRiskLocs.put(implocs.next(), new Integer(0)); } while (atRiskPeople.hasNext()) { Integer person = atRiskPeople.next(); Iterator<Integer> locs = this.mySim.locsVisited.get(person).iterator(); while (locs.hasNext()) { Integer loc = locs.next(); if (this.trackLocations.containsKey(loc)); EpiSimUtil.incMapValue(atRiskLocs, loc, -1); } } Iterator<Integer> itr = atRiskLocs.keySet().iterator(); monitoredLocs = new HashSet<Integer>(this.numMonitors); for (int i = 0; i < this.numMonitors;) { Integer next = itr.next(); if (next != null && !this.monitoredLocs.contains(next)&& !this.isClosed(next, this.mySim.curTime)) { monitoredLocs.add(next); i++; } } System.out.println("Locations monitored with at-risk score >=\t"+atRiskLocs.get(itr.next())); }
c761ae62-9d36-46f5-a208-7dcf7e8efcfb
5
final void method3642(int i, Class348_Sub1[] class348_sub1s) { do { try { for (int i_281_ = 0; i_281_ < i; i_281_++) ((NativeToolkit) this).aClass348_Sub1Array8132[i_281_] = class348_sub1s[i_281_]; anInt7988++; ((NativeToolkit) this).anInt8151 = i; if (!((NativeToolkit) this).aClass196_8184.method1450(-94)) break; method3823((byte) 51); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("wga.FF(" + i + ',' + (class348_sub1s != null ? "{...}" : "null") + ')')); } break; } while (false); }
ef3e4e42-4222-40bb-b66d-11d77d5c9161
5
@SuppressWarnings({ "unchecked", "rawtypes" }) private Collection<Object> newCollection(Class<?> type) { if (SortedSet.class.isAssignableFrom(type)) return new TreeSet(); else if (LinkedHashSet.class.isAssignableFrom(type)) return new LinkedHashSet(); else if (Set.class.isAssignableFrom(type)) return new HashSet(); else if (List.class.isAssignableFrom(type)) return new ArrayList(); else { throw new ParameterException("Parameters of Collection type '" + type.getSimpleName() + "' are not supported. Please use List or Set instead."); } }
8a03f6c7-2ab1-4a51-be4d-76e8e084d133
0
public Sandwich() { System.out.println("Sandwich()"); }
4abc2b87-b8b4-4eb9-b696-caeb6f10c412
0
public String[] getParameters() { return this.parameters; }
10f42b2a-8a6f-46f7-b26f-5a1a46c3c95c
5
private void dealBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dealBActionPerformed (new SwingWorker<String, Object>() { @Override public String doInBackground() { Board b = Board.getInstance(); Company companies[] = b.getCompanies(); Company c = (Company) JOptionPane.showInputDialog(BoardPanel.this, "Select company to sell to...", "Patent Deal", JOptionPane.QUESTION_MESSAGE, null, companies, companies[0]); if (c == null) { return "Deal cancelled"; } String str = JOptionPane.showInputDialog(BoardPanel.this, "Enter your agreement amount ", "Patent Deal", JOptionPane.QUESTION_MESSAGE); if (str == null || str.isEmpty()) { return "Deal cancelled"; } try { int amt = Integer.parseInt(str); c.decrMoney(amt); c.incrPatentCount(); Company co = b.getCompany(b.getSelectIndex()); co.incrMoney(amt); c.decrPatentCount(); return co + " sold 1 patent to " + c; } catch (NumberFormatException e) { return "Deal cancelled"; } } @Override protected void done() { try { msgTP.setText(get()); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(System.err); } } }).execute(); }//GEN-LAST:event_dealBActionPerformed
06ce3e73-affe-4ad1-ac5b-f3456db07da2
7
public int comparer(Comparer comparer, Task taskX, Task taskY, int colIndex) { int result = 0; if (colIndex == 0) { result = comparer.compare(taskX.getTaskID(), taskY.getTaskID()); } else if (colIndex == 1) { result = comparer.compare(taskX.getTitle().toUpperCase(), taskY .getTitle().toUpperCase()); } else if (colIndex == 2) { result = comparer.compare(taskX.getAssignedTo().getUserName() .toUpperCase(), taskY.getAssignedTo().getUserName() .toUpperCase()); } else if (colIndex == 3) { result = comparer.compare(taskX.getStatus().toString(), taskY .getStatus().toString()); } else if (colIndex == 4) { result = comparer.compare(taskX.getDueDate(), taskY.getDueDate()); } else if (colIndex == 5) { result = comparer.compare(taskX.getPriority().toString(), taskY .getPriority().toString()); } else if (colIndex == 6) { result = comparer.compare(taskX.getDescription().toUpperCase(), taskY.getDescription().toUpperCase()); } return result; }
eb8ba070-2eeb-4c6e-a834-c64300fe70af
7
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null){ return l2; } if (l2 == null){ return l1; } ListNode superHead = new ListNode(-1); ListNode temp = superHead; while (l1 != null&&l2 != null){ if(l1.val<l2.val){ temp.next = l1; l1 = l1.next; } else { temp.next = l2; l2 = l2.next; } temp = temp.next; } if (l1 != null){ temp.next = l1; } if (l2 != null){ temp.next = l2; } return superHead.next; }
87dd5cd7-6c4b-4141-9f81-65aa72848b70
2
@Override public void init(GameContainer gc, StateBasedGame game) throws SlickException { renderQueue.clear(); try { renderQueue.add(player); renderQueue.add(map); for(MapLayer l : map.getLayers()) { renderQueue.add(l); } } catch(Exception e) { } }
bc2f7f78-0229-496f-b95c-53e77f352802
3
@SuppressWarnings("unused") public void captureMovie() { boolean done = false; BufferedImage image = null; long startTime = 0; long endTime = 0; int timeToSleep = (int) (1000 / framesPerSecond); int actualTime = timeToSleep; int count = 0; Thread current = Thread.currentThread(); while (current == active) { try { startTime = System.currentTimeMillis(); image = new Robot().createScreenCapture(region); frameSequencer.addFrame(new Picture(image)); endTime = System.currentTimeMillis(); if (endTime - startTime < timeToSleep) Thread.sleep(timeToSleep-(endTime-startTime)); } catch (Exception ex) { System.out.println("caught exception in StartMovieCapture"); done = true; } } }
9451a9f7-ef28-41d3-a95d-4a76fc4ea090
9
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UnorderedPair)) return false; @SuppressWarnings("unchecked") final UnorderedPair pair = (UnorderedPair) o; return (((first == null ? pair.first == null : first.equals(pair.first)) && (second == null ? pair.second == null : second.equals(pair.second))) || ((first == null ? pair.second == null : first.equals(pair.second)) && (second == null ? pair.first == null : second.equals(pair.first)))); }
5ce6b020-3ff0-4995-8ea5-7350e9f8fd71
6
public void calculateBranchStatistics() { if (branchCount == 0) { for (int i : branchData.keySet()) { List<BranchData> branchDatas = branchData.get(i); if (branchDatas != null) { for (int j = 1; j < branchDatas.size(); j++) { branchCount += 2; BranchData data = branchDatas.get(j); if (data.getEvalFalse() > 0) branchesCoveredCount++; if (data.getEvalTrue() > 0) branchesCoveredCount++; } } } } }
263e6227-273a-4d1e-8e1f-00d8e95b039a
7
public static ParseResult parseXmlPart( char[] chars, int offset ) throws XMLParseException { int c; whitespaceloop: while( offset < chars.length ) { // Skip whitespace c = chars[offset]; switch( c ) { case( '<' ): break whitespaceloop; case( ' ' ): case( '\t' ): case( '\r' ): case( '\n' ): ++offset; break; default: ParseResult r = parseXmlText( chars, offset, '<' ); r.value = ((String)r.value).trim(); return r; } } if( offset < chars.length ) { return parseXmlTag( chars, offset ); } return new ParseResult(null, offset); }
e7ea152f-7b4b-4177-89a7-cfd2a00f5a55
6
private ArrayList<String> insertPointsQuery( List<Track> tracks ) throws SQLException { Statement st = sqlite.createStatement(); ArrayList<String> strList = new ArrayList<String>(); int count = 0; StringBuilder sqlQuery = new StringBuilder(); int size = tracks.size(); for( int i = 0; i < size; i++ ) { Track t = tracks.get(i); int pSize = t.points.size(); sqlQuery = new StringBuilder("INSERT INTO points VALUES\n"); for ( int j = 0; j < pSize; j++ ) { count++; if ( (count % 100) == 0 ) { strList.add(sqlQuery.toString()); count = 1; sqlQuery = new StringBuilder("INSERT INTO points VALUES\n"); } TrackPoint p = t.points.get(j); String point; point = (" (" + t.getId()+", " + p.getLat() + ", " + p.getLon()+ ", " + p.getNum() +")"+ (( i == (size-1) && j == (pSize-1) || (count % 100) == 99 )? ";" : ",") ); sqlQuery.append(point); } } strList.add(sqlQuery.toString()); return strList; }
cb3beb66-5dab-41de-b8b7-2ed55b5600da
9
private int GetLogicActionVetric(WumpusPolje[][] wumpusWorld){ if(tmpPolje.m_vetrovno){ //Down if(tmpPolje.m_x + 1 < wumpusWorld.length && tmpPolje.m_y - 1 >= 0){ if(obiskanaPolja.contains(wumpusWorld[tmpPolje.m_x + 1][tmpPolje.m_y - 1]) && !wumpusWorld[tmpPolje.m_x + 1][tmpPolje.m_y - 1].m_vetrovno){ return WumpusActions.down; } } //Right if(tmpPolje.m_x - 1 >= 0 && tmpPolje.m_y + 1 < wumpusWorld[0].length){ if(obiskanaPolja.contains(wumpusWorld[tmpPolje.m_x - 1][tmpPolje.m_y + 1]) && !wumpusWorld[tmpPolje.m_x - 1][tmpPolje.m_y + 1].m_vetrovno){ return WumpusActions.right; } } } return WumpusActions.back; }
2b9168c8-f039-4350-aadc-d6bec86e0f30
6
private static Individual crossover(Individual indiv1, Individual indiv2) { Individual newSol = new Individual(); // Loop through genes for (int i = 0; i < indiv1.size(); i++) { // Crossover if (Math.random() <= uniformRate) { byte gene = 0; if(indiv1.getGene(i) == 1 && GA.items[i] + newSol.getFitness() > 2000) { newSol.setGene(i, (byte)0); } else { newSol.setGene(i, indiv1.getGene(i)); } } else { if(indiv2.getGene(i) == 1 && GA.items[i] + newSol.getFitness() > 2000) { newSol.setGene(i, (byte)0); } else { newSol.setGene(i, indiv2.getGene(i)); } } } return newSol; }
5b13e3eb-d39f-4607-b0c9-d9e1f3345cb3
2
public static void filterFiles() { try { DirectoryStream<Path> largerThanFourBytes = Files.newDirectoryStream( Paths.get("/home/xander/test"), new DirectoryStream.Filter<Path>(){ @Override public boolean accept(Path entry) throws IOException { return Files.size(entry) > 4; } }); for (Path file : largerThanFourBytes) { System.out.println(file); } } catch (IOException e) { e.printStackTrace(); } }
37ec4a48-6ee6-4f09-9fc0-93e7be81b08d
8
@EventHandler(priority = EventPriority.LOW) public void onTeleport(PlayerTeleportEvent event) { if (event.isCancelled()) { return; } if (plugin.settings.blockTeleport() && plugin.isInCombat(event.getPlayer().getUniqueId()) && plugin.ctIncompatible.notInArena(event.getPlayer())) { TeleportCause cause = event.getCause(); if ((cause == TeleportCause.PLUGIN || cause == TeleportCause.COMMAND)) { if(event.getPlayer().getWorld() != event.getTo().getWorld()){ event.getPlayer().sendMessage(ChatColor.RED + "[CombatTag] You can't teleport across worlds while tagged."); event.setCancelled(true); } else if(event.getFrom().distance(event.getTo()) > 8){ //Allow through small teleports as they are inconsequential, but some plugins use these event.getPlayer().sendMessage(ChatColor.RED + "[CombatTag] You can't teleport while tagged."); event.setCancelled(true); } } } }
6b3cc1d6-0a92-4f8b-b9da-85e61cb54437
8
Skeleton(JMSRemoteSystem remoteSystem, JMSRemoteRef ref, Object target) { this.remoteSystem = remoteSystem; try { this.target = target; Class<?> clazz = this.target.getClass(); if (CGLibProxyAdapter.isProxyClass(ref.getProxy().getClass())) { for (Method method : clazz.getMethods()) { if (method.getDeclaringClass() == Object.class) { continue; } // System.out.println("Class: " + clazz.getName() + " adding method: " + method.toGenericString()); String sig = JMSRemoteSystem.signature(method); methods.put(sig, clazz.getMethod(method.getName(), method.getParameterTypes())); } } else { for (Class<?> intf : ref.getInterfaces()) { for (Method method : intf.getMethods()) { // System.out.println("Class: " + clazz.getName() + " adding method: " + method.toGenericString()); String sig = JMSRemoteSystem.signature(method); methods.put(sig, intf.getMethod(method.getName(), method.getParameterTypes())); } } } } catch (NoSuchMethodException e) { throw new IllegalArgumentException("target should implement all of the interfaces provided", e); } }
fdf0d0fc-316b-4027-a7dd-84088030b334
2
public ShowBild(Bild[] b) { for(Bild bild : b) if(bild != null) filled++; filled --; value = (int) (MAX * filled); this.b = b; // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setTitle("Bild" + b.name); setSize(800, 600); setVisible(true); }
1ee772bc-a929-42a2-8c30-6e68df586d49
0
public void setDirection(int dir) { this.direction = dir; }
f6a145ce-6715-471b-9ffe-f586f8f84d72
6
private static void readData() { try { b = new BufferedReader(new FileReader(fileDirectory + dataFile)); String line; while ((line = b.readLine()) != null) { String[] s = line.split(":"); int usr = Integer.parseInt(s[0]); int mov = Integer.parseInt(s[2]); int rat = Integer.parseInt(s[4]); if (UserMovieRatings.containsKey(usr)) { UserMovieRatings.get(usr).put(mov, rat); } else { HashMap<Integer, Integer> ratings = new HashMap<Integer, Integer>(); ratings.put(mov, rat); UserMovieRatings.put(usr, ratings); } if (ratingsByMovie.containsKey(mov)) { ratingsByMovie.get(mov).add((double) rat); } else { ArrayList<Double> ratings = new ArrayList<Double>(); ratings.add((double) rat); ratingsByMovie.put(mov, ratings); } if (usersByMovie.containsKey(mov)) { usersByMovie.get(mov).add(usr); } else { HashSet<Integer> raters = new HashSet<Integer>(); raters.add(usr); usersByMovie.put(mov, raters); } } b.close(); } catch (FileNotFoundException e) { System.err.println("Couldn't read the parameter file. Check the file name: " + dataFile); e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
2ffdbc96-ee78-435e-ad01-47bf69d40b5b
7
@Override public Room unDock(boolean moveToOutside) { final Room dock=getIsDocked(); Room exitRoom = null; if(dock==null) return null; for(final Enumeration<Room> e=getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(R!=null) { for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room nextR=R.rawDoors()[d]; if((nextR!=null) &&((nextR==dock)||(nextR.getArea()!=this))) { exitRoom=R; R.rawDoors()[d]=null; } } } } shipExitCache.clear(); savedDock=null; return exitRoom; }
8dfc2c7e-d5ce-4a76-8f26-b5c7130e62e7
0
public void dosomething() { component.dosomething(); }
5caea908-5cbf-48da-ade5-f8c06220600d
5
public boolean coupPossible() { Pile pile1; Pile pile2; for (int i = 0; i < listePiles.size(); i++) { pile1 = listePiles.get(i); for (int j = 0; j < listePiles.size(); j++) { pile2 = listePiles.get(j); if(pilesDifferentes(pile1, pile2)) { if(memeHauteur(pile1, pile2)) return true; if(memeCouleurSommet(pile1, pile2)) return true; } } } return false; }
2e3cfe3b-b1dc-4556-93c5-89e60c6204c2
2
@Override public Integer getNextValue(Integer current, Integer target) { for (ConditionalRule rule : rules) { if (rule.isApplicable(current, target)) return rule.getNextValue(current, target); } return null; }
7c2406d5-0279-4a6b-ad71-4f1ebe697cdd
5
public static String formatChar(final Character object) { if (object == null) return "null"; final StringBuilder result = new StringBuilder(4).append('\''); switch (object.charValue()) { case '\'': result.append("\\\'"); break; case '\t': result.append("\\t"); break; case '\n': result.append("\\n"); break; case '\r': result.append("\\r"); break; default: result.append(object.charValue()); } return result.append('\'').toString(); }
19c1e9ce-a7e2-42f2-905e-107f55759a29
3
@Override public boolean singleStep() { if (!heap.isEmpty()) { Vertex u = heap.delMin(); u.setColor(VertexColor.GRAY); DoublyLinkedList<Vertex> neighbours = adjacency.getNeighbours(u); Vertex v = neighbours.succ(neighbours.min()); while (v != null) { relax(u, v, graph.getEdgeByVertices(u, v)); v = neighbours.succ(v); } if (u.getPath() != null) { graph.getEdgeByVertices(u.getPath(), u).setVisited(true); } u.setColor(VertexColor.BLACK); return true; } else { return false; } }
479042c0-9e0a-450d-9ad7-4a2bbdb1fef6
1
private static void killBombers(IBomber[] bombers) { for (IBomber iBomber : bombers) { iBomber.destroy(); } }
4446d5b3-4e86-4c0f-8002-ec2ab6a83bcc
8
public static void main(String[] args) { System.out.println("Starting network example ..."); try { if (args.length < 1) { System.out.println("Usage: java SCFQExample network.txt"); return; } // get the network topology String filename = args[0]; ////////////////////////////////////////// // First step: Initialize the GridSim package. It should be called // before creating any entities. We can't run this example without // initializing GridSim first. We will get run-time exception // error. int num_user = 3; // number of grid users Calendar calendar = Calendar.getInstance(); // a flag that denotes whether to trace GridSim events or not. boolean trace_flag = false; // Initialize the GridSim package System.out.println("Initializing GridSim package"); GridSim.init(num_user, calendar, trace_flag); ////////////////////////////////////////// // Second step: Builds the network topology among Routers. // use SCFQ packet scheduler. Hence, determine the // weights for each ToS (Type of Service). The more weight, // the better. // For example: ToS = 0 => weight[0] = 1 // ToS = 2 => weight[2] = 3 double[] weight = {1, 2, 3}; // % of total bandwidth System.out.println("Reading network from " + filename); LinkedList routerList = NetworkReader.createSCFQ(filename, weight); ////////////////////////////////////////// // Third step: Creates one or more GridResource entities double baud_rate = 100000000; // 100 Mbps double propDelay = 10; // propagation delay in millisecond int mtu = 1500; // max. transmission unit in byte int i = 0; // link the resources into R5 Router router = NetworkReader.getRouter("R5", routerList); // more resources can be created by // setting totalResource to an appropriate value int totalResource = 1; ArrayList resList = new ArrayList(totalResource); for (i = 0; i < totalResource; i++) { GridResource res = createGridResource("Res_"+i, baud_rate, propDelay, mtu); // add a resource into a list resList.add(res); // link a resource to this router object linkNetwork(router, res, weight); } ////////////////////////////////////////// // Fourth step: Creates one or more grid user entities // number of Gridlets that will be sent to the resource int totalGridlet = 5; // create users ArrayList userList = new ArrayList(num_user); ArrayList userNameList = new ArrayList(); // for background traffic for (i = 0; i < num_user; i++) { String name = "User_" + i; // if trace_flag is set to "true", then this experiment will // create User_i.csv where i = 0 ... (num_user-1) NetUser user = new NetUser(name, totalGridlet, baud_rate, propDelay, mtu, trace_flag); // for each user, determines the Type of Service (ToS) // for sending objects over the network. The greater ToS is, // the more bandwidth allocation int ToS = i; if (i > weight.length) { ToS = 0; } user.setNetServiceLevel(ToS); // link a User to a router object if (i == 0) { router = NetworkReader.getRouter("R1", routerList); } else if (i == 1) { router = NetworkReader.getRouter("R2", routerList); } else { router = NetworkReader.getRouter("R3", routerList); } linkNetwork(router, user, weight); // add a user into a list userList.add(user); userNameList.add(name); } ////////////////////////////////////////// // Fifth step: Starts the simulation GridSim.startGridSimulation(); ////////////////////////////////////////// // Final step: Prints the Gridlets when simulation is over // also prints the routing table router = NetworkReader.getRouter("R3", routerList); router.printRoutingTable(); router = NetworkReader.getRouter("R4", routerList); router.printRoutingTable(); GridletList glList = null; for (i = 0; i < userList.size(); i++) { NetUser obj = (NetUser) userList.get(i); glList = obj.getGridletList(); printGridletList(glList, obj.get_name(), false); } System.out.println("\nFinish network example ..."); } catch (Exception e) { e.printStackTrace(); System.out.println("Unwanted errors happen"); } }
f5287e9e-992a-4aae-b0a5-88ef144ab8ac
3
public void run() { while (true) { if (mtime != file.lastModified()) { read(); } try { Thread.sleep(1000 * seconds); } catch (InterruptedException e) { return; } } }
eb2e2115-d46d-4f84-85d1-6ab95494316d
2
protected String convertType(Class<?> clazz) { if (clazz.isEnum()) { return "INT"; } return TYPECONVERSION.get(clazz.getSimpleName().toLowerCase()); }
ed42cd1c-bc3b-429c-b1cb-62f59ddbe8d4
4
public void addOrUpdate(sharedstate.SharedState state, GameObject g, String data) { UUID id = g.getId(); boolean found = false; for (GameObject g2 : state.getObjects()) { if (id.equals(g2.getId())) { found = true; if (g.getLastTimeStamp() <= g2.getLastTimeStamp()) { break; // old data dont use } g2.fromNetString(data); break; } } if (!found) state.getObjects().add(g); }
52430157-d948-4819-ac26-d3cbd3a33178
3
private void backgroundRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backgroundRadioButtonActionPerformed if (backgroundRadioButton.isSelected()) { try { Pointer path = new Memory(300); user32.SystemParametersInfoA(User32.SPI_GETDESKWALLPAPER, 300, path, 0); if (path.getString(0).length() > 0) { System.out.println("Got the path: " + path.getString(0)); /*try { BufferedImage img = null; img = ImageIO.read(new File(path.getString(0))); System.out.println("RBG int: " + img.getRGB(0, 0)); } catch (IOException ex) { Logger.getLogger(Arduino_LED_ControllerView.class.getName()).log(Level.SEVERE, null, ex); }*/ } else { System.out.println("Didn't get a path"); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Image not found.", "Image error", JOptionPane.ERROR_MESSAGE); backgroundRadioButton.setSelected(false); } } catch (Exception ex) { System.out.println(ex.toString()); } } }//GEN-LAST:event_backgroundRadioButtonActionPerformed
699f8ae4-c07f-4e1e-aefb-7666432fa539
5
public static Map<String, String> decodeKVMap(String keyValueString) { Map<String, String> keyValueMap = new HashMap<String, String>(); /** * Only process if the KVString is not empty */ if (keyValueString != null && !keyValueString.isEmpty()) { /** * If the keyValueString has been retrieved from a browser URI then strip * the leading '?' if present */ if (keyValueString.startsWith("?")) { keyValueString = keyValueString.substring(1); } /** * Parse the URI string into key / value pairs. Decode each key value * pair, splitting the key/value pairs and populate the map with key and * (decoded) value pairs (This second-pass of decoding is important!) */ String[] keyValuePairs = keyValueString.split("&"); for (String keyValuePair : keyValuePairs) { try { String[] kv = decodeString(keyValuePair).split("="); keyValueMap.put(kv[0], decodeString(kv[1])); } catch (Exception ex) { } } } return keyValueMap; }
8c2008fd-becc-4637-9717-fc46db85923c
4
@Override public String decrypt(String str) { try { // Decode base64 to get bytes byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); // Decrypt byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 return new String(utf8, "UTF8"); } catch (javax.crypto.BadPaddingException e) { } catch (IllegalBlockSizeException e) { } catch (UnsupportedEncodingException e) { } catch (java.io.IOException e) { } return null; }
c88f13d3-ce89-4095-bf32-e1d1e2ad6632
4
private King getKing(Color color) { for (int i = 0; i < NUMBER_OF_COLS; i++) { for (int j = 0; j < NUMBER_OF_ROWS; j++) { Piece piece = pieces[j][i]; if (piece.name.equals(Constants.NAME_KING) && piece.getColor() == color) return (King)piece; } } System.out.println("There is no " + color + " King on the board"); return null; }
6caa34e7-62b3-413b-a552-1f330a1ec4c7
7
private void sendOrderCaps(RdpPacket_Localised data) { byte[] order_caps = new byte[32]; order_caps[0] = 1; /* dest blt */ order_caps[1] = 1; /* pat blt */// nb no rectangle orders if this is 0 order_caps[2] = 1; /* screen blt */ order_caps[3] = (byte) (option.isBitmapCachingEnabled() ? 1 : 0); /* memblt */ order_caps[4] = 1; /* triblt */ order_caps[8] = 1; /* line */ order_caps[9] = 1; /* line */ order_caps[10] = 1; /* rect */ order_caps[11] = (Constants.desktop_save ? 1 : 0); /* desksave */ order_caps[13] = 1; /* memblt */ order_caps[14] = 1; /* triblt */ order_caps[20] = (byte) (option.isPolygonEllipseOrdersEnabled() ? 1 : 0); /* polygon */ order_caps[21] = (byte) (option.isPolygonEllipseOrdersEnabled() ? 1 : 0); /* polygon2 */ order_caps[22] = 1; /* polyline */ order_caps[25] = (byte) (option.isPolygonEllipseOrdersEnabled() ? 1 : 0); /* ellipse */ order_caps[26] = (byte) (option.isPolygonEllipseOrdersEnabled() ? 1 : 0); /* ellipse2 */ order_caps[27] = 1; /* text2 */ data.setLittleEndian16(RDP_CAPSET_ORDER); data.setLittleEndian16(RDP_CAPLEN_ORDER); data.incrementPosition(20); /* Terminal desc, pad */ data.setLittleEndian16(1); /* Cache X granularity */ data.setLittleEndian16(20); /* Cache Y granularity */ data.setLittleEndian16(0); /* Pad */ data.setLittleEndian16(1); /* Max order level */ data.setLittleEndian16(0x147); /* Number of fonts */ data.setLittleEndian16(0x2a); /* Capability flags */ data.copyFromByteArray(order_caps, 0, data.getPosition(), 32); /* * Orders * supported */ data.incrementPosition(32); data.setLittleEndian16(0x6a1); /* Text capability flags */ data.incrementPosition(6); /* Pad */ data.setLittleEndian32(Constants.desktop_save ? 0x230400 : 0); /* * Desktop * cache * size */ data.setLittleEndian32(0x0000); /* Unknown */ data.setLittleEndian32(0x4e4); /* Unknown */ }
309b5b8b-cbe0-4bbe-a009-dd147d5d8715
5
@SuppressWarnings("unchecked") public static HashMap<String, ArrayList<String>> load(String path) { Object result = null; BufferedReader br = null; try { br = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { if (br.readLine() == null) { result = new HashMap<String, ArrayList<String>>(); } else { try { ObjectInputStream ois = new ObjectInputStream( new FileInputStream(path)); result = ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } try { br.close(); } catch (IOException e) { e.printStackTrace(); } return (HashMap<String, ArrayList<String>>) result; }
e3fffbc4-7c2d-47a5-af7d-53480e05691a
6
private void moveCrew( final CrewSprite mobileSprite ) { squareSelector.reset(); squareSelector.setCriteria(new SquareCriteria() { private final String desc = "Move: Crew"; public String getDescription() { return desc; } public boolean isSquareValid( SquareSelector squareSelector, int roomId, int squareId ) { if ( roomId < 0 || squareId < 0 ) return false; if ( blockedRegions.contains( squareSelector.getSquareRectangle() ) ) return false; for (CrewSprite crewSprite : crewSprites) { if ( crewSprite.getRoomId() == roomId && crewSprite.getSquareId() == squareId ) { return false; } } return true; } }); squareSelector.setCallback(new SquareSelectionCallback() { public boolean squareSelected( SquareSelector squareSelector, int roomId, int squareId ) { Point center = squareSelector.getSquareCenter(); placeSprite( center.x, center.y, mobileSprite ); mobileSprite.setRoomId( roomId ); mobileSprite.setSquareId( squareId ); return false; } }); squareSelector.setVisible(true); }
42162ef0-5a6e-47df-983d-fb66dd09ea55
2
public static Categorias sqlLeer(Categorias cat){ String sql="SELECT * FROM categorias WHERE idcategorias = '"+cat.getId()+"' "; if(!BD.getInstance().sqlSelect(sql)){ return null; } if(!BD.getInstance().sqlFetch()){ return null; } cat.setId(BD.getInstance().getInt("id")); cat.setNombre(BD.getInstance().getString("nombre")); return cat; }
bff259cc-d97e-4310-a545-11107792d5a1
0
public void startTime() { this.timer = new Timer(); this.timer.scheduleAtFixedRate(new TimerTask() { public void run() { updateTime(); } }, 1000, 1000); }
073867b1-7726-4124-a323-b2ebd25a930a
4
private boolean isInside(Point p) { if (p.x >= positionX && p.x <= (positionX + width) && p.y >= positionY && p.y <= (positionY + height)) { return true; } return false; }
6178e3e0-547b-4218-8f3b-79c8f19b884e
8
private void parse(String template) { int offs = 0; int lastOffs = 0; while ((offs=template.indexOf('$', lastOffs))>-1 && offs<template.length()-1) { char next = template.charAt(offs+1); switch (next) { case '$': // "$$" => escaped single dollar sign addTemplatePiece(new TemplatePiece.Text( template.substring(lastOffs, offs+1))); lastOffs = offs + 2; break; case '{': // "${...}" => variable int closingCurly = template.indexOf('}', offs+2); if (closingCurly>-1) { addTemplatePiece(new TemplatePiece.Text( template.substring(lastOffs, offs))); String varName = template.substring(offs+2, closingCurly); if (!"cursor".equals(varName) && isParamDefined(varName)) { addTemplatePiece(new TemplatePiece.ParamCopy(varName)); } else { addTemplatePiece(new TemplatePiece.Param(varName)); } lastOffs = closingCurly + 1; } break; } } if (lastOffs<template.length()) { String text = template.substring(lastOffs); addTemplatePiece(new TemplatePiece.Text(text)); } }
297be8b9-fc4d-47d6-bf1d-c2f422daff66
0
public void setPrpTerminal(String prpTerminal) { this.prpTerminal = prpTerminal; }
559882ab-eaf5-4c4f-a4c6-98b8980d7959
7
public static boolean hasSquare(String[][] grid, int caseCount){ for (int i = 0; i < grid.length; i++) { for(int j = 0; j < grid.length; j++){ if(grid[i][j].equals("#")){ if(hasNoSurroundingSquares(grid, i, j, caseCount)) return false; } } } for (int i = 0; i < grid.length; i++) { for(int j = 0; j < grid.length; j++){ if(grid[i][j].equals("#")){ return checkForSquare(grid,i,j); } } } return false; }
417fd0d2-23f3-4bae-98f2-b6b969cd09df
5
public static final void writeInteger( long num, byte encoding, OutputStream os ) throws IOException { switch( encoding ) { case NE_INT8 : writeInt8( (byte)num, os ); return; case NE_INT16 : writeInt16( (short)num, os ); return; case NE_INT32 : writeInt32( (int)num, os ); return; case NE_INT64 : writeInt64( num, os ); return; case NE_INT6 : writeInt6( (byte)num, os ); return; default: throw new UnsupportedOperationException(String.format("Unsupported integer encoding:, 0x%02x",encoding)); } }
f70aebca-abdd-47fb-b3eb-a55e8df727e4
9
void move2D(Mesh mesh, int[] vertexes, int iVertex, int x, int y, boolean moveAll) { if (vertexes == null || vertexes.length == 0) return; Point3i pt = new Point3i(); Point3f coord = new Point3f(); Point3f newcoord = new Point3f(); Vector3f move = new Vector3f(); coord.set(mesh.vertices[vertexes[iVertex]]); viewer.transformPoint(coord, pt); pt.x = x; pt.y = y; viewer.unTransformPoint(pt, newcoord); move.set(newcoord); move.sub(coord); int klast = -1; for (int i = (moveAll ? 0 : iVertex); i < vertexes.length; i++) if (moveAll || i == iVertex) { int k = vertexes[i]; if (k == klast) break; mesh.vertices[k].add(move); if (!moveAll) break; klast = k; } if (Logger.isActiveLevel(Logger.LEVEL_DEBUG)) Logger.debug(getDrawCommand(mesh)); viewer.refresh(); }
c1862ebd-1e14-4865-b303-3893e82b7c87
4
public static void main(String [] args) { try { ImportDao importDao = new ImportDao(); importDao.connect(); Dao.getInstance(); Connection conn = Dao.getConnection(); ArrayList<Activity> estudios = importDao.getEstudios(); ActivityDao activityDao = ActivityDao.getInstance(); System.out.println("Estudios"); for(Activity a : estudios) { System.out.println(a.toString()); activityDao.insertActivity(conn, a); } ArrayList<Activity> activities = activityDao.getActivities(conn); ArrayList<Time> tiempos = importDao.getTiempos(activities); TimeDao timeDao = TimeDao.getInstance(); System.out.println("Tiempos"); for(Time t : tiempos) { System.out.println(t.toString()); timeDao.insertTime(conn, t); } System.out.println("Data import ended."); } catch (ClassNotFoundException ex) { log.error("Unable to load the database driver.\nError message: {}", ex.getLocalizedMessage()); } catch (SQLException ex) { String [] errors = {ex.getLocalizedMessage(), String.valueOf(ex.getErrorCode()), ex.getSQLState()}; log.error("Error while accessing the database.\nError message: {}\nError code: {}\nSQLState: {}", errors); } }
93426a2d-2cd1-40b7-9ae8-d193b9b8e1ff
7
public String minWindow(String S, String T) { if(T.length() == 0) return ""; int lastBeginIndex = -1; String res = ""; for(int i=0,j=0; i<S.length(); i++) { if(S.charAt(i) == T.charAt(j)) { j++; if(j==1)lastBeginIndex = i; if(j==T.length()) { j=0; String sub = S.substring(lastBeginIndex, i+1); res = sub.length() < res.length() || res.length()==0 ? sub:res; } } } return res; }
d6ccce5e-cff8-4d8c-bd64-537111ccff31
8
public void purge() { //removes DEAD contacts from the bucket for (Iterator<Contact> it = contacts.values().iterator(); it.hasNext();) { Contact node = it.next(); if(!node.isAlive() && !isLocalNode(node)) it.remove(); } //replaces empty entries in the bucket with cache entries if(!isBucketFull() && !cache.isEmpty()) { // The cache Map is in LRS order. Add the Contacts to a List and // iterate it backwards so that we get the elements in MRS order. List<Contact> cont = new ArrayList<Contact>(getAllCachedContacts()); for(int i = cont.size()-1; i>=0 && !isBucketFull(); i--) { Contact node = cont.get(i); if(node.isAlive()) contacts.put(node.getNodeId(), node); cache.remove(node.getNodeId()); } } }
f01bdc9e-e5d4-4982-a3ca-d2b8cde27a9c
6
public static void pasteADocFragment(ADocument aDoc, int position, ADocumentFragment fragment){ String text = fragment.getText(); HashMap <DocSection, AttributeSet> styleMap = fragment.getStyleMap(); HashMap <DocSection, AData> fragMap = fragment.getaDataMap(); try { // inserting plain text //aDoc.blockUndoEvents(true); if (text != null )aDoc.insertString(position, text, aDoc.defaultStyle); // inserting styles if (styleMap !=null){ Set <DocSection> keys = styleMap.keySet(); Iterator <DocSection> it = keys.iterator(); DocSection section = null; while (it.hasNext()){ section = it.next(); aDoc.setCharacterAttributes(position+section.getStart(), section.getLength(), styleMap.get(section), true); } } // inserting AData if (fragMap !=null){ HashMap<ASection, AData> aDataMap = aDoc.getADataMap(); Set <DocSection> keys = fragMap.keySet(); Iterator <DocSection> it = keys.iterator(); DocSection section = null; while (it.hasNext()){ section = it.next(); aDataMap.put(aDoc.new ASection( aDoc.createPosition(position+section.getStart()), aDoc.createPosition(position+section.getEnd())), fragMap.get(section)); } } //aDoc.blockUndoEvents(false); } catch (BadLocationException e) { e.printStackTrace(); } }
69eae164-b568-4c3d-93f5-18f266b28bf5
8
public static Class<? extends Player> load(String jarFile) { try { URL url = new File(jarFile).toURI().toURL(); String playerClassName = getPlayerClassName(url); if (playerClassName == null) { throw new RuntimeException(String.format("Can not find class name for %s", jarFile)); } System.err.printf("Found %s for %s\n", playerClassName, url); URLClassLoader loader = new URLClassLoader(new URL[]{url}); if (loader == null) { throw new RuntimeException(String.format("%s is not proper jar", jarFile)); } Class<?> playerClass = loader.loadClass(playerClassName); if (playerClass == null) { throw new RuntimeException(String.format("Can not find class for name %s in %s", playerClassName, jarFile)); } if (!Player.class.isAssignableFrom(playerClass)) { throw new RuntimeException(String.format("%s is not propert Player", playerClassName)); } return (Class<? extends Player>) playerClass; } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(JarPlayerLoader.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException(ex); } }
e1ec0243-4195-431b-8e26-b9a82ad5a92f
7
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
f855a8cc-7a2b-47f1-8865-e804f85ce7cd
2
private void loadHighScore() { try { File f = new File(saveDataPath, fileName); if (!f.isFile()) { createSaveData(); } BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(f))); highScore = Integer.parseInt(reader.readLine()); fastestMS = Long.parseLong(reader.readLine()); reader.close(); } catch (Exception e) { e.printStackTrace(); } }
aa64fa59-4c95-4fbd-93d8-feaac983a13e
8
@Override protected void onMove() { if (Keyboard.isKeyPressed(Keyboard.KEY_LEFT)) { if (sprZombie.getCurrentAnimationName() == "quiet") sprZombie.setAnimation("walk"); } else { if (sprZombie.getCurrentAnimationName() == "walk" && sprZombie.getCurrentAnimationNumLoops() >= 1) sprZombie.setAnimation("quiet"); } if (sprZombie.getCurrentAnimationName() == "hit" && sprZombie.getCurrentAnimationNumLoops() >= 1) sprZombie.setAnimation("quiet"); if (sprZombie.getCurrentAnimationName() == "bite" && sprZombie.getCurrentAnimationNumLoops() >= 1) sprZombie.setAnimation("quiet"); sprZombie.move(); }
0a0cfee1-4683-4237-ae98-bbed8fbf0362
3
public Object invokeMethod(Reference ref, boolean isVirtual, Object cls, Object[] params) throws InterpreterException, InvocationTargetException { if (cls == null && ref.getClazz().equals(classSig)) { String clazzName = ref.getClazz(); clazzName = clazzName.substring(1, ref.getClazz().length() - 1) .replace('/', '.'); BytecodeInfo info = ClassInfo.forName(clazzName) .findMethod(ref.getName(), ref.getType()).getBytecode(); if (info != null) return interpreter.interpretMethod(info, null, params); throw new InterpreterException( "Can't interpret static native method: " + ref); } else return super.invokeMethod(ref, isVirtual, cls, params); }
6ae1bed7-160b-4338-a294-c644d6e27c5b
5
@Override public boolean run() { for (Gene g : config.getSnpEffectPredictor().getGenome().getGenes()) { // System.out.println(g.getGeneName()); for (Transcript tr : g) { if (!tr.isProteinCoding()) continue; if (tr.introns().size() < 2) continue; // System.out.println("\t" + tr.getId()); for (Intron i : tr.introns()) { int pos = i.getStart() + (int) (Math.random() * (i.size() - 2)) + 1; String line = i.getChromosomeName() + "\t" + pos + "\t.\tA\tT\t.\t.\tAC=1;GENE=" + g.getGeneName() + ";TR=" + tr.getId() + ";INTRON=" + i.getRank(); System.out.println(line); sb.append(line + "\n"); } } } Gpr.toFile(Gpr.HOME + "/introns_test.vcf", sb); return true; }
c689f77a-a3f3-40ea-8075-4acce98a363a
3
@WebMethod(operationName = "ReadOrderInDetail") public ArrayList<OrderInDetail> ReadOrderInDetail(@WebParam(name = "ord_in_det_id") String ord_in_det_id) { OrderInDetail ord_in_det = new OrderInDetail(); ArrayList<OrderInDetail> ord_in_dets = new ArrayList<OrderInDetail>(); ArrayList<QueryCriteria> qc = new ArrayList<QueryCriteria>(); if(!ord_in_det_id.equals("-1")){ qc.add(new QueryCriteria("ord_in_det_id", ord_in_det_id, Operand.EQUALS)); } ArrayList<String> fields = new ArrayList<String>(); ArrayList<QueryOrder> order = new ArrayList<QueryOrder>(); try { ord_in_dets = ord_in_det.Read(qc, fields, order); } catch (SQLException ex) { Logger.getLogger(JAX_WS.class.getName()).log(Level.SEVERE, null, ex); } if(ord_in_dets.isEmpty()){ return null; } return ord_in_dets; }
80bbf9e6-401e-4a2e-8943-a069acfc9425
9
public boolean evaluateLightCheckmate(Chessboard boardToCheck) { boolean isInCheckmate = false; Chessboard chessboardCopy = new Chessboard(boardToCheck); Tile[][] tileBoardCopy = chessboardCopy.getBoard(); ArrayList<Piece> offendingPieces = new ArrayList<>(); ArrayList<Location> safeAreas = new ArrayList<>(); Piece lightKing = getLightKing(tileBoardCopy, false); Location lightKingLoc = lightKing.getLocation(); //ArrayList<Location> lightKingMoves; for(int i = 0; i < BOARD_LENGTH; i++) { for(int j = 0; j < BOARD_LENGTH; j++) { //If each piece is not null if(tileBoardCopy[i][j].getPiece() != null) { Piece currentOffendingPiece = tileBoardCopy[i][j].getPiece(); //If in check if(evaluateLightCheck(board)) { //If offending piece is not same color as light king if(currentOffendingPiece.isPieceWhite() != lightKing.isPieceWhite()) { offendingPieces.add(currentOffendingPiece); //Loop through array and for each location, if offending piece can't move there //See if king can move there //If not, checkmate for(Piece p : offendingPieces) { Location potentialSafeArea = new Location(i, j); if(chessboardCopy.testMovePiece(p.getLocation(), potentialSafeArea, tileBoardCopy)) { safeAreas.add(potentialSafeArea); } } for(Location l : safeAreas) { if(chessboardCopy.testMovePiece(lightKingLoc, l, tileBoardCopy)) { isInCheckmate = false; } else { isInCheckmate = true; } } } } } } } return isInCheckmate; }
eb8d8462-b241-494b-a136-dcf4a1572e1b
3
public String getPhase() { byte[] input = getEFBytes(DatabaseOfEF.EF_PHASE);//,1 if (input[0] == (byte) 0x00) { return "Phase 1"; } if (input[0] == (byte) 0x02) { return "Phase 2"; } if (input[0] == (byte) 0x03) { return "Phase 2+ (with profile download required)"; } return "Reserved for specification by ETSI TC SMG"; }
2566ba04-2423-47b5-b579-5fe2fc5c0cd7
6
public void delete(String name, Boolean flag) throws UpYunExcetion { try { StringBuffer url = new StringBuffer(); for (String str : name.split("/")) { if (str == null || str.length() == 0) { continue; } url.append(UrlCodingUtil.encodeBase64(str.getBytes("utf-8")) + "/"); } if (flag) { url = url.delete(url.length() - 1, url.length()); } sign.setUri(url.toString()); } catch (UnsupportedEncodingException e) { LogUtil.exception(logger, e); } sign.setContentLength(0); sign.setMethod(HttpMethod.DELETE.name()); String url = autoUrl + sign.getUri(); Map<String, String> headers = sign.getHeaders(); HttpResponse httpResponse = HttpClientUtils.deleteByHttp(url, headers); if (httpResponse.getStatusLine().getStatusCode() != 200) { throw new UpYunExcetion(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine() .getReasonPhrase()); } }
40183a2e-4c37-45b3-9fb9-8a1e211dd669
5
private static Image[] fetchImages(String path, String fileBaseName, String fileType, int quantity, int stepSize) { Image[] imgs = new Image[quantity]; if (stepSize == 1) { for (int i = 0; i < quantity; i += 1) { try { imgs[i] = new Image(path + fileBaseName + (i + 1) + fileType); int sclX = (int) (imgs[i].getWidth() * Game.getWidthScale()); int sclY = (int) (imgs[i].getHeight() * Game.getHeightScale()); imgs[i] = imgs[i].getScaledCopy(sclX, sclY); } catch (SlickException e) { e.printStackTrace(); } } } else { for (int i = 0; i < quantity; i += 1) { try { imgs[i] = new Image(path + fileBaseName + (quantity-i) + fileType); int sclX = (int) (imgs[i].getWidth() * Game.getWidthScale()); int sclY = (int) (imgs[i].getHeight() * Game.getHeightScale()); imgs[i] = imgs[i].getScaledCopy(sclX, sclY); } catch (SlickException e) { e.printStackTrace(); } } } return imgs; }
ead4ed26-2278-4217-9a31-fc6250496959
6
public void testRemovedSlotPruning() { THashMap<String,String> map = new THashMap<String,String>(); map.put( "ONE", "1" ); map.put( "TWO", "2" ); map.put( "THREE", "3" ); // Compact to make sure we're at the internal capacity we want to ultimate be at map.compact(); // Make sure there are no REMOVED slots initially for( Object set_entry : map._set ) { if ( set_entry == TObjectHash.REMOVED ) fail( "Found a REMOVED entry" ); } map.remove( "TWO" ); map.put( "FOUR", "4" ); // Make sure there is 1 REMOVED slot int count = 0; for( Object set_entry : map._set ) { if ( set_entry == TObjectHash.REMOVED ) count++; } assertEquals( 1, count ); map.compact(); // Make sure there are no REMOVED slots for( Object set_entry : map._set ) { if ( set_entry == TObjectHash.REMOVED ) { fail( "Found a REMOVED entry after compaction" ); } } }